diff --git a/node_modules/.bin/babel b/node_modules/.bin/babel new file mode 120000 index 000000000..fdb319511 --- /dev/null +++ b/node_modules/.bin/babel @@ -0,0 +1 @@ +../@babel/cli/bin/babel.js \ No newline at end of file diff --git a/node_modules/.bin/babel-external-helpers b/node_modules/.bin/babel-external-helpers new file mode 120000 index 000000000..e8d78df6c --- /dev/null +++ b/node_modules/.bin/babel-external-helpers @@ -0,0 +1 @@ +../@babel/cli/bin/babel-external-helpers.js \ No newline at end of file diff --git a/node_modules/.bin/mime b/node_modules/.bin/mime new file mode 120000 index 000000000..fbb7ee0ee --- /dev/null +++ b/node_modules/.bin/mime @@ -0,0 +1 @@ +../mime/cli.js \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json index dc8fcf918..0341ba8e3 100644 --- a/node_modules/.package-lock.json +++ b/node_modules/.package-lock.json @@ -28,11 +28,71 @@ "tunnel": "0.0.6" } }, + "node_modules/@babel/cli": { + "version": "7.24.1", + "resolved": "https://registry.npmjs.org/@babel/cli/-/cli-7.24.1.tgz", + "integrity": "sha512-HbmrtxyFUr34LwAlV9jS+sSIjUp4FpdtIMGwgufY3AsxrIfsh/HxlMTywsONAZsU0RMYbZtbZFpUCrSGs7o0EA==", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.25", + "commander": "^4.0.1", + "convert-source-map": "^2.0.0", + "fs-readdir-recursive": "^1.1.0", + "glob": "^7.2.0", + "make-dir": "^2.1.0", + "slash": "^2.0.0" + }, + "bin": { + "babel": "bin/babel.js", + "babel-external-helpers": "bin/babel-external-helpers.js" + }, + "engines": { + "node": ">=6.9.0" + }, + "optionalDependencies": { + "@nicolo-ribaudo/chokidar-2": "2.1.8-no-fsevents.3", + "chokidar": "^3.4.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/cli/node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==" + }, + "node_modules/@babel/cli/node_modules/make-dir": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-2.1.0.tgz", + "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==", + "dependencies": { + "pify": "^4.0.1", + "semver": "^5.6.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@babel/cli/node_modules/semver": { + "version": "5.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz", + "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==", + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/@babel/cli/node_modules/slash": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", + "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==", + "engines": { + "node": ">=6" + } + }, "node_modules/@babel/code-frame": { "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.13.tgz", "integrity": "sha512-HV1Cm0Q3ZrpCR93tkWOYiuYIgLxZXZFVG2VgK+MBWjUqZTundupbfx2aXarXuw5Ko5aMcjtJgbSs4vUGBS5v6g==", - "dev": true, "dependencies": { "@babel/highlight": "^7.12.13" } @@ -40,14 +100,12 @@ "node_modules/@babel/compat-data": { "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.13.12.tgz", - "integrity": "sha512-3eJJ841uKxeV8dcN/2yGEUy+RfgQspPEgQat85umsE1rotuquQ2AbIub4S6j7c50a2d+4myc+zSlnXeIHrOnhQ==", - "dev": true + "integrity": "sha512-3eJJ841uKxeV8dcN/2yGEUy+RfgQspPEgQat85umsE1rotuquQ2AbIub4S6j7c50a2d+4myc+zSlnXeIHrOnhQ==" }, "node_modules/@babel/core": { "version": "7.13.10", "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.13.10.tgz", "integrity": "sha512-bfIYcT0BdKeAZrovpMqX2Mx5NrgAckGbwT982AkdS5GNfn3KMGiprlBAtmBcFZRUmpaufS6WZFP8trvx8ptFDw==", - "dev": true, "dependencies": { "@babel/code-frame": "^7.12.13", "@babel/generator": "^7.13.9", @@ -78,7 +136,6 @@ "version": "0.5.7", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", - "dev": true, "engines": { "node": ">=0.10.0" } @@ -87,7 +144,6 @@ "version": "7.13.9", "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.13.9.tgz", "integrity": "sha512-mHOOmY0Axl/JCTkxTU6Lf5sWOg/v8nUa+Xkt4zMTftX0wqmb6Sh7J8gvcehBw7q0AhrhAR+FDacKjCZ2X8K+Sw==", - "dev": true, "dependencies": { "@babel/types": "^7.13.0", "jsesc": "^2.5.1", @@ -98,7 +154,6 @@ "version": "0.5.7", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", - "dev": true, "engines": { "node": ">=0.10.0" } @@ -107,7 +162,6 @@ "version": "7.13.10", "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.13.10.tgz", "integrity": "sha512-/Xju7Qg1GQO4mHZ/Kcs6Au7gfafgZnwm+a7sy/ow/tV1sHeraRUHbjdat8/UvDor4Tez+siGKDk6zIKtCPKVJA==", - "dev": true, "dependencies": { "@babel/compat-data": "^7.13.8", "@babel/helper-validator-option": "^7.12.17", @@ -122,7 +176,6 @@ "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.12.13.tgz", "integrity": "sha512-TZvmPn0UOqmvi5G4vvw0qZTpVptGkB1GL61R6lKvrSdIxGm5Pky7Q3fpKiIkQCAtRCBUwB0PaThlx9vebCDSwA==", - "dev": true, "dependencies": { "@babel/helper-get-function-arity": "^7.12.13", "@babel/template": "^7.12.13", @@ -133,7 +186,6 @@ "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.12.13.tgz", "integrity": "sha512-DjEVzQNz5LICkzN0REdpD5prGoidvbdYk1BVgRUOINaWJP2t6avB27X1guXK1kXNrX0WMfsrm1A/ZBthYuIMQg==", - "dev": true, "dependencies": { "@babel/types": "^7.12.13" } @@ -142,7 +194,6 @@ "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.13.12.tgz", "integrity": "sha512-48ql1CLL59aKbU94Y88Xgb2VFy7a95ykGRbJJaaVv+LX5U8wFpLfiGXJJGUozsmA1oEh/o5Bp60Voq7ACyA/Sw==", - "dev": true, "dependencies": { "@babel/types": "^7.13.12" } @@ -151,7 +202,6 @@ "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.13.12.tgz", "integrity": "sha512-4cVvR2/1B693IuOvSI20xqqa/+bl7lqAMR59R4iu39R9aOX8/JoYY1sFaNvUMyMBGnHdwvJgUrzNLoUZxXypxA==", - "dev": true, "dependencies": { "@babel/types": "^7.13.12" } @@ -160,7 +210,6 @@ "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.13.12.tgz", "integrity": "sha512-7zVQqMO3V+K4JOOj40kxiCrMf6xlQAkewBB0eu2b03OO/Q21ZutOzjpfD79A5gtE/2OWi1nv625MrDlGlkbknQ==", - "dev": true, "dependencies": { "@babel/helper-module-imports": "^7.13.12", "@babel/helper-replace-supers": "^7.13.12", @@ -176,7 +225,6 @@ "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.12.13.tgz", "integrity": "sha512-BdWQhoVJkp6nVjB7nkFWcn43dkprYauqtk++Py2eaf/GRDFm5BxRqEIZCiHlZUGAVmtwKcsVL1dC68WmzeFmiA==", - "dev": true, "dependencies": { "@babel/types": "^7.12.13" } @@ -191,7 +239,6 @@ "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.13.12.tgz", "integrity": "sha512-Gz1eiX+4yDO8mT+heB94aLVNCL+rbuT2xy4YfyNqu8F+OI6vMvJK891qGBTqL9Uc8wxEvRW92Id6G7sDen3fFw==", - "dev": true, "dependencies": { "@babel/helper-member-expression-to-functions": "^7.13.12", "@babel/helper-optimise-call-expression": "^7.12.13", @@ -203,7 +250,6 @@ "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.13.12.tgz", "integrity": "sha512-7FEjbrx5SL9cWvXioDbnlYTppcZGuCY6ow3/D5vMggb2Ywgu4dMrpTJX0JdQAIcRRUElOIxF3yEooa9gUb9ZbA==", - "dev": true, "dependencies": { "@babel/types": "^7.13.12" } @@ -212,7 +258,6 @@ "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.12.13.tgz", "integrity": "sha512-tCJDltF83htUtXx5NLcaDqRmknv652ZWCHyoTETf1CXYJdPC7nohZohjUgieXhv0hTJdRf2FjDueFehdNucpzg==", - "dev": true, "dependencies": { "@babel/types": "^7.12.13" } @@ -220,20 +265,17 @@ "node_modules/@babel/helper-validator-identifier": { "version": "7.12.11", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.12.11.tgz", - "integrity": "sha512-np/lG3uARFybkoHokJUmf1QfEvRVCPbmQeUQpKow5cQ3xWrV9i3rUHodKDJPQfTVX61qKi+UdYk8kik84n7XOw==", - "dev": true + "integrity": "sha512-np/lG3uARFybkoHokJUmf1QfEvRVCPbmQeUQpKow5cQ3xWrV9i3rUHodKDJPQfTVX61qKi+UdYk8kik84n7XOw==" }, "node_modules/@babel/helper-validator-option": { "version": "7.12.17", "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.12.17.tgz", - "integrity": "sha512-TopkMDmLzq8ngChwRlyjR6raKD6gMSae4JdYDB8bByKreQgG0RBTuKe9LRxW3wFtUnjxOPRKBDwEH6Mg5KeDfw==", - "dev": true + "integrity": "sha512-TopkMDmLzq8ngChwRlyjR6raKD6gMSae4JdYDB8bByKreQgG0RBTuKe9LRxW3wFtUnjxOPRKBDwEH6Mg5KeDfw==" }, "node_modules/@babel/helpers": { "version": "7.13.10", "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.13.10.tgz", "integrity": "sha512-4VO883+MWPDUVRF3PhiLBUFHoX/bsLTGFpFK/HqvvfBZz2D57u9XzPVNFVBTc0PW/CWR9BXTOKt8NF4DInUHcQ==", - "dev": true, "dependencies": { "@babel/template": "^7.12.13", "@babel/traverse": "^7.13.0", @@ -244,7 +286,6 @@ "version": "7.13.10", "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.13.10.tgz", "integrity": "sha512-5aPpe5XQPzflQrFwL1/QoeHkP2MsA4JCntcXHRhEsdsfPVkvPi2w7Qix4iV7t5S/oC9OodGrggd8aco1g3SZFg==", - "dev": true, "dependencies": { "@babel/helper-validator-identifier": "^7.12.11", "chalk": "^2.0.0", @@ -255,7 +296,6 @@ "version": "3.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, "dependencies": { "color-convert": "^1.9.0" }, @@ -267,7 +307,6 @@ "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, "dependencies": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", @@ -281,7 +320,6 @@ "version": "1.9.3", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, "dependencies": { "color-name": "1.1.3" } @@ -289,14 +327,12 @@ "node_modules/@babel/highlight/node_modules/color-name": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", - "dev": true + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" }, "node_modules/@babel/highlight/node_modules/has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", - "dev": true, "engines": { "node": ">=4" } @@ -305,7 +341,6 @@ "version": "5.5.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, "dependencies": { "has-flag": "^3.0.0" }, @@ -317,7 +352,6 @@ "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.13.12.tgz", "integrity": "sha512-4T7Pb244rxH24yR116LAuJ+adxXXnHhZaLJjegJVKSdoNCe4x1eDBaud5YIcQFcqzsaD5BHvJw5BQ0AZapdCRw==", - "dev": true, "bin": { "parser": "bin/babel-parser.js" }, @@ -473,7 +507,6 @@ "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.12.13.tgz", "integrity": "sha512-/7xxiGA57xMo/P2GVvdEumr8ONhFOhfgq2ihK3h1e6THqzTAkHbkXgB0xI9yeTfIUoH3+oAeHhqm/I43OTbbjA==", - "dev": true, "dependencies": { "@babel/code-frame": "^7.12.13", "@babel/parser": "^7.12.13", @@ -484,7 +517,6 @@ "version": "7.13.0", "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.13.0.tgz", "integrity": "sha512-xys5xi5JEhzC3RzEmSGrs/b3pJW/o87SypZ+G/PhaE7uqVQNv/jlmVIBXuoh5atqQ434LfXV+sf23Oxj0bchJQ==", - "dev": true, "dependencies": { "@babel/code-frame": "^7.12.13", "@babel/generator": "^7.13.0", @@ -501,7 +533,6 @@ "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.13.12.tgz", "integrity": "sha512-K4nY2xFN4QMvQwkQ+zmBDp6ANMbVNw6BbxWmYA4qNjhR9W+Lj/8ky5MEY2Me5r+B2c6/v6F53oMndG+f9s3IiA==", - "dev": true, "dependencies": { "@babel/helper-validator-identifier": "^7.12.11", "lodash": "^4.17.19", @@ -817,12 +848,40 @@ "node": ">= 10.14.2" } }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.4.15", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", + "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, "node_modules/@mobsuccess-devops/asana-magics": { "version": "1.0.1-ci-4263876762.0", "resolved": "https://npm.pkg.github.com/download/@mobsuccess-devops/asana-magics/1.0.1-ci-4263876762.0/a74d8aebb535cae437157e15b019a385eedb3c0c", "integrity": "sha512-77lub4Hu7iZVuxFU+CD50tJ+0rKTxqcNNYrfx8etHmWUdMWdgSHGZx7BfIex/leDW4oxkzY/FQUmHMpp0vnZeg==", "license": "UNLICENSED" }, + "node_modules/@nicolo-ribaudo/chokidar-2": { + "version": "2.1.8-no-fsevents.3", + "resolved": "https://registry.npmjs.org/@nicolo-ribaudo/chokidar-2/-/chokidar-2-2.1.8-no-fsevents.3.tgz", + "integrity": "sha512-s88O1aVtXftvp5bCPB7WnmXc5IwOZZ7YPuwNPt+GtOOXpPvad1LfbmjYv+qII7zP6RU2QGnqve27dnLycEnyEQ==", + "optional": true + }, "node_modules/@octokit/auth-token": { "version": "2.4.5", "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.4.5.tgz", @@ -1119,6 +1178,7 @@ "version": "6.12.6", "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", @@ -1191,10 +1251,10 @@ } }, "node_modules/anymatch": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.1.tgz", - "integrity": "sha512-mM8522psRCqzV+6LhomX5wgp25YVibjh8Wj23I5RPkPppSVSjyKD2A2mBJmWGa+KN7f2D6LNh9jkBCeyLktzjg==", - "dev": true, + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "devOptional": true, "dependencies": { "normalize-path": "^3.0.0", "picomatch": "^2.0.4" @@ -1249,21 +1309,19 @@ } }, "node_modules/asana": { - "version": "0.18.5", - "resolved": "https://registry.npmjs.org/asana/-/asana-0.18.5.tgz", - "integrity": "sha512-goV903J5mkC+Km53MODyxXY/EiUjvevaH1UUzI198zuJn/sGFzScNBMFC7Ild1fJg7POXbD0GgVCN9sBsrzUGg==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/asana/-/asana-3.0.3.tgz", + "integrity": "sha512-/1+dZlRnbsfCoXanFwfFqrekbBxD8aNcTrgz1OW95p45ZE2UvdHM9sYJ8whOHOMkvQ4ARHUcEtiLrw/yH/NpWQ==", "dependencies": { - "bluebird": "^3.7.2", - "browser-request": "^0.3.2", - "lodash": "^4.17.20", - "readline": "^1.3.0", - "request": "^2.88.2" + "@babel/cli": "^7.0.0", + "superagent": "^5.3.0" } }, "node_modules/asn1": { "version": "0.2.4", "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.4.tgz", "integrity": "sha512-jxwzQpLQjSmWXgwaCZE9Nz+glAG01yF1QnWgbhGwHI5A6FRIEY6IVqtHhIepHqI7/kyEyQEagBC5mBEFlIYvdg==", + "dev": true, "dependencies": { "safer-buffer": "~2.1.0" } @@ -1272,6 +1330,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=", + "dev": true, "engines": { "node": ">=0.8" } @@ -1315,6 +1374,7 @@ "version": "0.7.0", "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=", + "dev": true, "engines": { "node": "*" } @@ -1322,7 +1382,8 @@ "node_modules/aws4": { "version": "1.11.0", "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.11.0.tgz", - "integrity": "sha512-xh1Rl34h6Fi1DC2WWKfxUTVqRsNnr6LsKz2+hfwDxQJWmrx8+c7ylaqBMcHfl1U1r2dsifOvKX3LQuLNZ+XSvA==" + "integrity": "sha512-xh1Rl34h6Fi1DC2WWKfxUTVqRsNnr6LsKz2+hfwDxQJWmrx8+c7ylaqBMcHfl1U1r2dsifOvKX3LQuLNZ+XSvA==", + "dev": true }, "node_modules/babel-jest": { "version": "26.6.3", @@ -1419,8 +1480,7 @@ "node_modules/balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", - "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", - "dev": true + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" }, "node_modules/base": { "version": "0.11.2", @@ -1503,6 +1563,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", + "dev": true, "dependencies": { "tweetnacl": "^0.14.3" } @@ -1512,16 +1573,22 @@ "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.0.tgz", "integrity": "sha512-jH6rKQIfroBbhEXVmI7XmXe3ix5S/PgJqpzdDPnR8JGLHWNYLsYZ6tK5iWOF/Ra3oqEX0NobXGlzbiylIzVphQ==" }, - "node_modules/bluebird": { - "version": "3.7.2", - "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", - "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==" + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "optional": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } }, "node_modules/brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "dev": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -1531,7 +1598,7 @@ "version": "3.0.2", "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", - "dev": true, + "devOptional": true, "dependencies": { "fill-range": "^7.0.1" }, @@ -1545,19 +1612,10 @@ "integrity": "sha512-9o5UecI3GhkpM6DrXr69PblIuWxPKk9Y0jHBRhdocZ2y7YECBFCsHm79Pr3OyR2AvjhDkabFJaDJMYRazHgsow==", "dev": true }, - "node_modules/browser-request": { - "version": "0.3.3", - "resolved": "https://registry.npmjs.org/browser-request/-/browser-request-0.3.3.tgz", - "integrity": "sha1-ns5bWsqJopkyJC4Yv5M975h2zBc=", - "engines": [ - "node" - ] - }, "node_modules/browserslist": { "version": "4.16.3", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.16.3.tgz", "integrity": "sha512-vIyhWmIkULaq04Gt93txdh+j02yX/JzlyhLYbV3YQCn/zvES3JnY7TifHHvvr1w5hTDluNKMkV05cs4vy8Q7sw==", - "dev": true, "dependencies": { "caniuse-lite": "^1.0.30001181", "colorette": "^1.2.1", @@ -1620,6 +1678,24 @@ "node": ">=0.10.0" } }, + "node_modules/call-bind": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", + "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", @@ -1641,8 +1717,7 @@ "node_modules/caniuse-lite": { "version": "1.0.30001204", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001204.tgz", - "integrity": "sha512-JUdjWpcxfJ9IPamy2f5JaRDCaqJOxDzOSKtbdx4rH9VivMd1vIzoPumsJa9LoMIi4Fx2BV2KZOxWhNkBjaYivQ==", - "dev": true + "integrity": "sha512-JUdjWpcxfJ9IPamy2f5JaRDCaqJOxDzOSKtbdx4rH9VivMd1vIzoPumsJa9LoMIi4Fx2BV2KZOxWhNkBjaYivQ==" }, "node_modules/capture-exit": { "version": "2.0.0", @@ -1659,7 +1734,8 @@ "node_modules/caseless": { "version": "0.12.0", "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", - "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=" + "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=", + "dev": true }, "node_modules/chalk": { "version": "4.1.0", @@ -1686,6 +1762,30 @@ "node": ">=10" } }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "optional": true, + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, "node_modules/ci-info": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz", @@ -1795,8 +1895,7 @@ "node_modules/colorette": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/colorette/-/colorette-1.2.2.tgz", - "integrity": "sha512-MKGMzyfeuutC/ZJ1cba9NqcNpfeqMUcYmyF1ZFY6/Cn7CNSAKx6a+s48sqLqyAiZuaP2TcqMhoo+dlwFnVxT9w==", - "dev": true + "integrity": "sha512-MKGMzyfeuutC/ZJ1cba9NqcNpfeqMUcYmyF1ZFY6/Cn7CNSAKx6a+s48sqLqyAiZuaP2TcqMhoo+dlwFnVxT9w==" }, "node_modules/combined-stream": { "version": "1.0.8", @@ -1809,27 +1908,37 @@ "node": ">= 0.8" } }, + "node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "engines": { + "node": ">= 6" + } + }, "node_modules/component-emitter": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz", - "integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==", - "dev": true + "integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==" }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", - "dev": true + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" }, "node_modules/convert-source-map": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.7.0.tgz", "integrity": "sha512-4FJkXzKXEDB1snCFZlLP4gpC3JILicCpGbzG9f9G7tGqGCzETQ2hWPrcinA9oU4wtf2biUaEH5065UnMeR33oA==", - "dev": true, "dependencies": { "safe-buffer": "~5.1.1" } }, + "node_modules/cookiejar": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/cookiejar/-/cookiejar-2.1.4.tgz", + "integrity": "sha512-LDx6oHrK+PhzLKJU9j5S7/Y3jM/mUHvD/DeI1WQmJn652iPC5Y4TBzC9l+5OMOXlyTTA+SmVUPm0HQUwpD5Jqw==" + }, "node_modules/copy-descriptor": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz", @@ -1842,7 +1951,8 @@ "node_modules/core-util-is": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", - "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", + "dev": true }, "node_modules/cross-spawn": { "version": "6.0.5", @@ -1897,6 +2007,7 @@ "version": "1.14.1", "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", + "dev": true, "dependencies": { "assert-plus": "^1.0.0" }, @@ -1922,7 +2033,6 @@ "version": "4.3.1", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz", "integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==", - "dev": true, "dependencies": { "ms": "2.1.2" }, @@ -1974,6 +2084,22 @@ "node": ">=0.10.0" } }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/define-property": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/define-property/-/define-property-2.0.2.tgz", @@ -2102,6 +2228,7 @@ "version": "0.1.2", "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=", + "dev": true, "dependencies": { "jsbn": "~0.1.0", "safer-buffer": "^2.1.0" @@ -2110,8 +2237,7 @@ "node_modules/electron-to-chromium": { "version": "1.3.700", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.700.tgz", - "integrity": "sha512-wQtaxVZzpOeCjW1CGuC5W3bYjE2jglvk076LcTautBOB9UtHztty7wNzjVsndiMcSsdUsdMy5w76w5J1U7OPTQ==", - "dev": true + "integrity": "sha512-wQtaxVZzpOeCjW1CGuC5W3bYjE2jglvk076LcTautBOB9UtHztty7wNzjVsndiMcSsdUsdMy5w76w5J1U7OPTQ==" }, "node_modules/emittery": { "version": "0.7.2", @@ -2161,11 +2287,29 @@ "is-arrayish": "^0.2.1" } }, + "node_modules/es-define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", + "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "dependencies": { + "get-intrinsic": "^1.2.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/escalade": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", - "dev": true, "engines": { "node": ">=6" } @@ -2174,7 +2318,6 @@ "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true, "engines": { "node": ">=0.8.0" } @@ -2671,7 +2814,8 @@ "node_modules/extend": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", - "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "dev": true }, "node_modules/extend-shallow": { "version": "3.0.2", @@ -2804,6 +2948,7 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=", + "dev": true, "engines": [ "node >=0.6.0" ] @@ -2811,12 +2956,14 @@ "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true }, "node_modules/fast-json-stable-stringify": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==" + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true }, "node_modules/fast-levenshtein": { "version": "2.0.6", @@ -2824,6 +2971,11 @@ "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", "dev": true }, + "node_modules/fast-safe-stringify": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", + "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==" + }, "node_modules/fb-watchman": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.1.tgz", @@ -2849,7 +3001,7 @@ "version": "7.0.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", - "dev": true, + "devOptional": true, "dependencies": { "to-regex-range": "^5.0.1" }, @@ -2902,6 +3054,7 @@ "version": "0.6.1", "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=", + "dev": true, "engines": { "node": "*" } @@ -2910,6 +3063,7 @@ "version": "2.3.3", "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz", "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", + "dev": true, "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.6", @@ -2919,6 +3073,15 @@ "node": ">= 0.12" } }, + "node_modules/formidable": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/formidable/-/formidable-1.2.6.tgz", + "integrity": "sha512-KcpbcpuLNOwrEjnbpMC0gS+X8ciDoZE1kkqzat4a8vrprf+s9pKNQ/QIwWfbfs4ltgmFl3MD177SNTkve3BwGQ==", + "deprecated": "Please upgrade to latest, formidable@v2 or formidable@v3! Check these notes: https://bit.ly/2ZEqIau", + "funding": { + "url": "https://ko-fi.com/tunnckoCore/commissions" + } + }, "node_modules/fragment-cache": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/fragment-cache/-/fragment-cache-0.2.1.tgz", @@ -2931,17 +3094,23 @@ "node": ">=0.10.0" } }, + "node_modules/fs-readdir-recursive": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fs-readdir-recursive/-/fs-readdir-recursive-1.1.0.tgz", + "integrity": "sha512-GNanXlVr2pf02+sPN40XN8HG+ePaNcvM0q5mZBd668Obwb0yD5GiUbZOFgwn8kGMY6I3mdyDJzieUy3PTYyTRA==" + }, "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", - "dev": true + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" }, "node_modules/function-bind": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", - "dev": true + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, "node_modules/functional-red-black-tree": { "version": "1.0.1", @@ -2953,7 +3122,6 @@ "version": "1.0.0-beta.2", "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", - "dev": true, "engines": { "node": ">=6.9.0" } @@ -2967,6 +3135,24 @@ "node": "6.* || 8.* || >= 10.*" } }, + "node_modules/get-intrinsic": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", + "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/get-package-type": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", @@ -3001,20 +3187,20 @@ "version": "0.1.7", "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", + "dev": true, "dependencies": { "assert-plus": "^1.0.0" } }, "node_modules/glob": { - "version": "7.1.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", - "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", - "dev": true, + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", - "minimatch": "^3.0.4", + "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" }, @@ -3029,7 +3215,7 @@ "version": "5.1.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "dev": true, + "devOptional": true, "dependencies": { "is-glob": "^4.0.1" }, @@ -3041,11 +3227,21 @@ "version": "11.12.0", "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", - "dev": true, "engines": { "node": ">=4" } }, + "node_modules/gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/graceful-fs": { "version": "4.2.6", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.6.tgz", @@ -3063,6 +3259,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=", + "dev": true, "engines": { "node": ">=4" } @@ -3072,6 +3269,7 @@ "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.5.tgz", "integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==", "deprecated": "this library is no longer supported", + "dev": true, "dependencies": { "ajv": "^6.12.3", "har-schema": "^2.0.0" @@ -3101,6 +3299,39 @@ "node": ">=8" } }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", + "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/has-value": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/has-value/-/has-value-1.0.0.tgz", @@ -3173,6 +3404,17 @@ "node": ">=0.10.0" } }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/hosted-git-info": { "version": "2.8.8", "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.8.tgz", @@ -3201,6 +3443,7 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=", + "dev": true, "dependencies": { "assert-plus": "^1.0.0", "jsprim": "^1.2.2", @@ -3295,7 +3538,6 @@ "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", - "dev": true, "dependencies": { "once": "^1.3.0", "wrappy": "1" @@ -3304,8 +3546,7 @@ "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, "node_modules/is-accessor-descriptor": { "version": "0.1.6", @@ -3337,6 +3578,18 @@ "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", "dev": true }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "optional": true, + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/is-buffer": { "version": "1.1.6", "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", @@ -3443,7 +3696,7 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", - "dev": true, + "devOptional": true, "engines": { "node": ">=0.10.0" } @@ -3470,7 +3723,7 @@ "version": "4.0.1", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", - "dev": true, + "devOptional": true, "dependencies": { "is-extglob": "^2.1.1" }, @@ -3482,7 +3735,7 @@ "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", - "dev": true, + "devOptional": true, "engines": { "node": ">=0.12.0" } @@ -3513,7 +3766,8 @@ "node_modules/is-typedarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", - "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=" + "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=", + "dev": true }, "node_modules/is-windows": { "version": "1.0.2", @@ -3552,7 +3806,8 @@ "node_modules/isstream": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", - "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=" + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", + "dev": true }, "node_modules/istanbul-lib-coverage": { "version": "3.0.0", @@ -4303,8 +4558,7 @@ "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" }, "node_modules/js-yaml": { "version": "3.14.1", @@ -4322,7 +4576,8 @@ "node_modules/jsbn": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", - "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=" + "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=", + "dev": true }, "node_modules/jsdom": { "version": "16.5.1", @@ -4428,7 +4683,6 @@ "version": "2.5.2", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", - "dev": true, "bin": { "jsesc": "bin/jsesc" }, @@ -4445,12 +4699,14 @@ "node_modules/json-schema": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", - "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=" + "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=", + "dev": true }, "node_modules/json-schema-traverse": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==" + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true }, "node_modules/json-stable-stringify-without-jsonify": { "version": "1.0.1", @@ -4461,13 +4717,13 @@ "node_modules/json-stringify-safe": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", - "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=" + "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=", + "dev": true }, "node_modules/json5": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.0.tgz", "integrity": "sha512-f+8cldu7X/y7RAJurMEJmdoKXGB/X550w2Nr3tTbezL6RwEE/iMcm+tZnXeoZtKuOq6ft8+CqzEkrIgx1fPoQA==", - "dev": true, "dependencies": { "minimist": "^1.2.5" }, @@ -4482,6 +4738,7 @@ "version": "1.4.1", "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz", "integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=", + "dev": true, "engines": [ "node >=0.6.0" ], @@ -4559,7 +4816,6 @@ "version": "6.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dev": true, "dependencies": { "yallist": "^4.0.0" }, @@ -4618,6 +4874,14 @@ "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", "dev": true }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/micromatch": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.2.tgz", @@ -4631,6 +4895,17 @@ "node": ">=8" } }, + "node_modules/mime": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz", + "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4.0.0" + } + }, "node_modules/mime-db": { "version": "1.46.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.46.0.tgz", @@ -4660,10 +4935,9 @@ } }, "node_modules/minimatch": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", - "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", - "dev": true, + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", "dependencies": { "brace-expansion": "^1.1.7" }, @@ -4674,8 +4948,7 @@ "node_modules/minimist": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", - "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", - "dev": true + "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==" }, "node_modules/mixin-deep": { "version": "1.3.2", @@ -4726,8 +4999,7 @@ "node_modules/ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "dev": true + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" }, "node_modules/nanomatch": { "version": "1.2.13", @@ -4836,8 +5108,7 @@ "node_modules/node-releases": { "version": "1.1.71", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-1.1.71.tgz", - "integrity": "sha512-zR6HoT6LrLCRBwukmrVbHv0EpEQjksO6GmFcZQQuCAy139BEsoVKPYnf3jongYW83fAa1torLGYwxxky/p28sg==", - "dev": true + "integrity": "sha512-zR6HoT6LrLCRBwukmrVbHv0EpEQjksO6GmFcZQQuCAy139BEsoVKPYnf3jongYW83fAa1torLGYwxxky/p28sg==" }, "node_modules/normalize-package-data": { "version": "2.5.0", @@ -4864,7 +5135,7 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true, + "devOptional": true, "engines": { "node": ">=0.10.0" } @@ -4891,6 +5162,7 @@ "version": "0.9.0", "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==", + "dev": true, "engines": { "node": "*" } @@ -4933,6 +5205,14 @@ "node": ">=0.10.0" } }, + "node_modules/object-inspect": { + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz", + "integrity": "sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/object-visit": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/object-visit/-/object-visit-1.0.1.tgz", @@ -5130,7 +5410,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", - "dev": true, "engines": { "node": ">=0.10.0" } @@ -5153,13 +5432,14 @@ "node_modules/performance-now": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", - "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=" + "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=", + "dev": true }, "node_modules/picomatch": { "version": "2.2.2", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.2.2.tgz", "integrity": "sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg==", - "dev": true, + "devOptional": true, "engines": { "node": ">=8.6" }, @@ -5167,6 +5447,14 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pify": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", + "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", + "engines": { + "node": ">=6" + } + }, "node_modules/pirates": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.1.tgz", @@ -5261,7 +5549,8 @@ "node_modules/psl": { "version": "1.8.0", "resolved": "https://registry.npmjs.org/psl/-/psl-1.8.0.tgz", - "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==" + "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==", + "dev": true }, "node_modules/pump": { "version": "3.0.0", @@ -5277,6 +5566,7 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "dev": true, "engines": { "node": ">=6" } @@ -5285,6 +5575,7 @@ "version": "6.5.2", "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz", "integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==", + "dev": true, "engines": { "node": ">=0.6" } @@ -5336,10 +5627,30 @@ "node": ">=8" } }, - "node_modules/readline": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/readline/-/readline-1.3.0.tgz", - "integrity": "sha1-xYDXfvLPyHUrEySYBg3JeTp6wBw=" + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "optional": true, + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } }, "node_modules/regex-not": { "version": "1.0.2", @@ -5395,6 +5706,8 @@ "resolved": "https://registry.npmjs.org/request/-/request-2.88.2.tgz", "integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==", "deprecated": "request has been deprecated, see https://github.com/request/request/issues/3142", + "dev": true, + "peer": true, "dependencies": { "aws-sign2": "~0.7.0", "aws4": "^1.8.0", @@ -5471,6 +5784,8 @@ "version": "2.5.0", "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz", "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", + "dev": true, + "peer": true, "dependencies": { "psl": "^1.1.28", "punycode": "^2.1.1" @@ -5484,6 +5799,8 @@ "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==", "deprecated": "Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.", + "dev": true, + "peer": true, "bin": { "uuid": "bin/uuid" } @@ -5603,7 +5920,8 @@ "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true }, "node_modules/sane": { "version": "4.1.0", @@ -5797,7 +6115,6 @@ "version": "6.3.0", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true, "bin": { "semver": "bin/semver.js" } @@ -5808,6 +6125,22 @@ "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", "dev": true }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/set-value": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.1.tgz", @@ -5884,6 +6217,23 @@ "dev": true, "optional": true }, + "node_modules/side-channel": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", + "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/signal-exit": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz", @@ -6180,6 +6530,7 @@ "version": "1.16.1", "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.16.1.tgz", "integrity": "sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==", + "dev": true, "dependencies": { "asn1": "~0.2.3", "assert-plus": "^1.0.0", @@ -6255,6 +6606,33 @@ "node": ">=0.10.0" } }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, "node_modules/string-length": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", @@ -6333,6 +6711,69 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/superagent": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/superagent/-/superagent-5.3.1.tgz", + "integrity": "sha512-wjJ/MoTid2/RuGCOFtlacyGNxN9QLMgcpYLDQlWFIhhdJ93kNscFonGvrpAHSCVjRVj++DGCglocF7Aej1KHvQ==", + "deprecated": "Please upgrade to v7.0.2+ of superagent. We have fixed numerous issues with streams, form-data, attach(), filesystem errors not bubbling up (ENOENT on attach()), and all tests are now passing. See the releases tab for more information at .", + "dependencies": { + "component-emitter": "^1.3.0", + "cookiejar": "^2.1.2", + "debug": "^4.1.1", + "fast-safe-stringify": "^2.0.7", + "form-data": "^3.0.0", + "formidable": "^1.2.2", + "methods": "^1.1.2", + "mime": "^2.4.6", + "qs": "^6.9.4", + "readable-stream": "^3.6.0", + "semver": "^7.3.2" + }, + "engines": { + "node": ">= 7.0.0" + } + }, + "node_modules/superagent/node_modules/form-data": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz", + "integrity": "sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/superagent/node_modules/qs": { + "version": "6.12.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.12.0.tgz", + "integrity": "sha512-trVZiI6RMOkO476zLGaBIzszOdFPnCCXHPG9kn0yuS1uz6xdVxPfZdB3vUig9pxPFDM9BRAgz/YUIVQ1/vuiUg==", + "dependencies": { + "side-channel": "^1.0.6" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/superagent/node_modules/semver": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.0.tgz", + "integrity": "sha512-EnwXhrlwXMk9gKu5/flx5sv/an57AkRplG3hTK68W7FRDN+k+OWBj65M7719OkA82XLBxrcX0KSHj+X5COhOVg==", + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/supports-color": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", @@ -6453,7 +6894,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=", - "dev": true, "engines": { "node": ">=4" } @@ -6501,7 +6941,7 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", - "dev": true, + "devOptional": true, "dependencies": { "is-number": "^7.0.0" }, @@ -6547,6 +6987,7 @@ "version": "0.6.0", "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", + "dev": true, "dependencies": { "safe-buffer": "^5.0.1" }, @@ -6557,7 +6998,8 @@ "node_modules/tweetnacl": { "version": "0.14.5", "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", - "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=" + "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=", + "dev": true }, "node_modules/type-check": { "version": "0.3.2", @@ -6688,6 +7130,7 @@ "version": "4.4.1", "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, "dependencies": { "punycode": "^2.1.0" } @@ -6708,6 +7151,11 @@ "node": ">=0.10.0" } }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" + }, "node_modules/uuid": { "version": "8.3.2", "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", @@ -6761,6 +7209,7 @@ "version": "1.10.0", "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", + "dev": true, "engines": [ "node >=0.6.0" ], @@ -6938,8 +7387,7 @@ "node_modules/yallist": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" }, "node_modules/yargs": { "version": "15.4.1", diff --git a/node_modules/@babel/cli/LICENSE b/node_modules/@babel/cli/LICENSE new file mode 100644 index 000000000..f31575ec7 --- /dev/null +++ b/node_modules/@babel/cli/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/cli/README.md b/node_modules/@babel/cli/README.md new file mode 100644 index 000000000..ee5fecbc8 --- /dev/null +++ b/node_modules/@babel/cli/README.md @@ -0,0 +1,19 @@ +# @babel/cli + +> Babel command line. + +See our website [@babel/cli](https://babeljs.io/docs/babel-cli) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20cli%22+is%3Aopen) associated with this package. + +## Install + +Using npm: + +```sh +npm install --save-dev @babel/cli +``` + +or using yarn: + +```sh +yarn add @babel/cli --dev +``` diff --git a/node_modules/@babel/cli/bin/babel-external-helpers.js b/node_modules/@babel/cli/bin/babel-external-helpers.js new file mode 100755 index 000000000..9701b072b --- /dev/null +++ b/node_modules/@babel/cli/bin/babel-external-helpers.js @@ -0,0 +1,3 @@ +#!/usr/bin/env node + +require("../lib/babel-external-helpers"); diff --git a/node_modules/@babel/cli/bin/babel-external-helpers.mjs b/node_modules/@babel/cli/bin/babel-external-helpers.mjs new file mode 100644 index 000000000..85a6c7a5c --- /dev/null +++ b/node_modules/@babel/cli/bin/babel-external-helpers.mjs @@ -0,0 +1,3 @@ +#!/usr/bin/env node + +import "../lib/babel-external-helpers.js"; diff --git a/node_modules/@babel/cli/bin/babel.js b/node_modules/@babel/cli/bin/babel.js new file mode 100755 index 000000000..7c227455f --- /dev/null +++ b/node_modules/@babel/cli/bin/babel.js @@ -0,0 +1,3 @@ +#!/usr/bin/env node + +require("../lib/babel"); diff --git a/node_modules/@babel/cli/bin/babel.mjs b/node_modules/@babel/cli/bin/babel.mjs new file mode 100644 index 000000000..9ad45a8cc --- /dev/null +++ b/node_modules/@babel/cli/bin/babel.mjs @@ -0,0 +1,3 @@ +#!/usr/bin/env node + +import "../lib/babel/index.js"; diff --git a/node_modules/@babel/cli/index.js b/node_modules/@babel/cli/index.js new file mode 100644 index 000000000..b1762389a --- /dev/null +++ b/node_modules/@babel/cli/index.js @@ -0,0 +1 @@ +throw new Error("Use the `@babel/core` package instead of `@babel/cli`."); diff --git a/node_modules/@babel/cli/lib/babel-external-helpers.js b/node_modules/@babel/cli/lib/babel-external-helpers.js new file mode 100644 index 000000000..e4932b192 --- /dev/null +++ b/node_modules/@babel/cli/lib/babel-external-helpers.js @@ -0,0 +1,32 @@ +"use strict"; + +function _commander() { + const data = require("commander"); + _commander = function () { + return data; + }; + return data; +} +function _core() { + const data = require("@babel/core"); + _core = function () { + return data; + }; + return data; +} +function collect(value, previousValue) { + if (typeof value !== "string") return previousValue; + const values = value.split(","); + if (previousValue) { + previousValue.push(...values); + return previousValue; + } + return values; +} +_commander().option("-l, --whitelist [whitelist]", "Whitelist of helpers to ONLY include", collect); +_commander().option("-t, --output-type [type]", "Type of output (global|umd|var)", "global"); +_commander().usage("[options]"); +_commander().parse(process.argv); +console.log((0, _core().buildExternalHelpers)(_commander().whitelist, _commander().outputType)); + +//# sourceMappingURL=babel-external-helpers.js.map diff --git a/node_modules/@babel/cli/lib/babel-external-helpers.js.map b/node_modules/@babel/cli/lib/babel-external-helpers.js.map new file mode 100644 index 000000000..8d4d991e8 --- /dev/null +++ b/node_modules/@babel/cli/lib/babel-external-helpers.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_commander","data","require","_core","collect","value","previousValue","values","split","push","commander","option","usage","parse","process","argv","console","log","buildExternalHelpers","whitelist","outputType"],"sources":["../src/babel-external-helpers.ts"],"sourcesContent":["import commander from \"commander\";\nimport { buildExternalHelpers } from \"@babel/core\";\n\nfunction collect(value: unknown, previousValue: Array): Array {\n // If the user passed the option with no value, like \"babel-external-helpers --whitelist\", do nothing.\n if (typeof value !== \"string\") return previousValue;\n\n const values = value.split(\",\");\n\n if (previousValue) {\n previousValue.push(...values);\n return previousValue;\n }\n return values;\n}\n\ncommander.option(\n \"-l, --whitelist [whitelist]\",\n \"Whitelist of helpers to ONLY include\",\n collect,\n);\ncommander.option(\n \"-t, --output-type [type]\",\n \"Type of output (global|umd|var)\",\n \"global\",\n);\n\ncommander.usage(\"[options]\");\ncommander.parse(process.argv);\n\nconsole.log(buildExternalHelpers(commander.whitelist, commander.outputType));\n"],"mappings":";;AAAA,SAAAA,WAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,UAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,MAAA;EAAA,MAAAF,IAAA,GAAAC,OAAA;EAAAC,KAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,SAASG,OAAOA,CAACC,KAAc,EAAEC,aAA4B,EAAiB;EAE5E,IAAI,OAAOD,KAAK,KAAK,QAAQ,EAAE,OAAOC,aAAa;EAEnD,MAAMC,MAAM,GAAGF,KAAK,CAACG,KAAK,CAAC,GAAG,CAAC;EAE/B,IAAIF,aAAa,EAAE;IACjBA,aAAa,CAACG,IAAI,CAAC,GAAGF,MAAM,CAAC;IAC7B,OAAOD,aAAa;EACtB;EACA,OAAOC,MAAM;AACf;AAEAG,WAAQA,CAAC,CAACC,MAAM,CACd,6BAA6B,EAC7B,sCAAsC,EACtCP,OACF,CAAC;AACDM,WAAQA,CAAC,CAACC,MAAM,CACd,0BAA0B,EAC1B,iCAAiC,EACjC,QACF,CAAC;AAEDD,WAAQA,CAAC,CAACE,KAAK,CAAC,WAAW,CAAC;AAC5BF,WAAQA,CAAC,CAACG,KAAK,CAACC,OAAO,CAACC,IAAI,CAAC;AAE7BC,OAAO,CAACC,GAAG,CAAC,IAAAC,4BAAoB,EAACR,WAAQA,CAAC,CAACS,SAAS,EAAET,WAAQA,CAAC,CAACU,UAAU,CAAC,CAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/cli/lib/babel/dir.js b/node_modules/@babel/cli/lib/babel/dir.js new file mode 100644 index 000000000..d809c3836 --- /dev/null +++ b/node_modules/@babel/cli/lib/babel/dir.js @@ -0,0 +1,236 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; +function _slash() { + const data = require("slash"); + _slash = function () { + return data; + }; + return data; +} +function _path() { + const data = require("path"); + _path = function () { + return data; + }; + return data; +} +function _fs() { + const data = require("fs"); + _fs = function () { + return data; + }; + return data; +} +var util = require("./util.js"); +var watcher = require("./watcher.js"); +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +const FILE_TYPE = Object.freeze({ + NON_COMPILABLE: "NON_COMPILABLE", + COMPILED: "COMPILED", + IGNORED: "IGNORED", + ERR_COMPILATION: "ERR_COMPILATION" +}); +function outputFileSync(filePath, data) { + (((v, w) => (v = v.split("."), w = w.split("."), +v[0] > +w[0] || v[0] == w[0] && +v[1] >= +w[1]))(process.versions.node, "10.12") ? _fs().mkdirSync : require("make-dir").sync)(_path().dirname(filePath), { + recursive: true + }); + _fs().writeFileSync(filePath, data); +} +function _default(_x) { + return _ref.apply(this, arguments); +} +function _ref() { + _ref = _asyncToGenerator(function* ({ + cliOptions, + babelOptions + }) { + function write(_x2, _x3) { + return _write.apply(this, arguments); + } + function _write() { + _write = _asyncToGenerator(function* (src, base) { + let relative = _path().relative(base, src); + if (!util.isCompilableExtension(relative, cliOptions.extensions)) { + return FILE_TYPE.NON_COMPILABLE; + } + relative = util.withExtension(relative, cliOptions.keepFileExtension ? _path().extname(relative) : cliOptions.outFileExtension); + const dest = getDest(relative, base); + try { + const res = yield util.compile(src, Object.assign({}, babelOptions, { + sourceFileName: _slash()(_path().relative(dest + "/..", src)) + })); + if (!res) return FILE_TYPE.IGNORED; + if (res.map) { + let outputMap = false; + if (babelOptions.sourceMaps && babelOptions.sourceMaps !== "inline") { + outputMap = "external"; + } else if (babelOptions.sourceMaps == undefined) { + outputMap = util.hasDataSourcemap(res.code) ? "external" : "both"; + } + if (outputMap) { + const mapLoc = dest + ".map"; + if (outputMap === "external") { + res.code = util.addSourceMappingUrl(res.code, mapLoc); + } + res.map.file = _path().basename(relative); + outputFileSync(mapLoc, JSON.stringify(res.map)); + } + } + outputFileSync(dest, res.code); + util.chmod(src, dest); + if (cliOptions.verbose) { + console.log(_path().relative(process.cwd(), src) + " -> " + dest); + } + return FILE_TYPE.COMPILED; + } catch (err) { + if (cliOptions.watch) { + console.error(err); + return FILE_TYPE.ERR_COMPILATION; + } + throw err; + } + }); + return _write.apply(this, arguments); + } + function getDest(filename, base) { + if (cliOptions.relative) { + return _path().join(base, cliOptions.outDir, filename); + } + return _path().join(cliOptions.outDir, filename); + } + function handleFile(_x4, _x5) { + return _handleFile.apply(this, arguments); + } + function _handleFile() { + _handleFile = _asyncToGenerator(function* (src, base) { + const written = yield write(src, base); + if (cliOptions.copyFiles && written === FILE_TYPE.NON_COMPILABLE || cliOptions.copyIgnored && written === FILE_TYPE.IGNORED) { + const filename = _path().relative(base, src); + const dest = getDest(filename, base); + outputFileSync(dest, _fs().readFileSync(src)); + util.chmod(src, dest); + } + return written === FILE_TYPE.COMPILED; + }); + return _handleFile.apply(this, arguments); + } + function handle(_x6) { + return _handle.apply(this, arguments); + } + function _handle() { + _handle = _asyncToGenerator(function* (filenameOrDir) { + if (!_fs().existsSync(filenameOrDir)) return 0; + const stat = _fs().statSync(filenameOrDir); + if (stat.isDirectory()) { + const dirname = filenameOrDir; + let count = 0; + const files = util.readdir(dirname, cliOptions.includeDotfiles); + for (const filename of files) { + const src = _path().join(dirname, filename); + const written = yield handleFile(src, dirname); + if (written) count += 1; + } + return count; + } else { + const filename = filenameOrDir; + const written = yield handleFile(filename, _path().dirname(filename)); + return written ? 1 : 0; + } + }); + return _handle.apply(this, arguments); + } + let compiledFiles = 0; + let startTime = null; + const logSuccess = util.debounce(function () { + if (startTime === null) { + return; + } + const diff = process.hrtime(startTime); + console.log(`Successfully compiled ${compiledFiles} ${compiledFiles !== 1 ? "files" : "file"} with Babel (${diff[0] * 1e3 + Math.round(diff[1] / 1e6)}ms).`); + compiledFiles = 0; + startTime = null; + }, 100); + if (cliOptions.watch) watcher.enable({ + enableGlobbing: true + }); + if (!cliOptions.skipInitialBuild) { + if (cliOptions.deleteDirOnStart) { + util.deleteDir(cliOptions.outDir); + } + (((v, w) => (v = v.split("."), w = w.split("."), +v[0] > +w[0] || v[0] == w[0] && +v[1] >= +w[1]))(process.versions.node, "10.12") ? _fs().mkdirSync : require("make-dir").sync)(cliOptions.outDir, { + recursive: true + }); + startTime = process.hrtime(); + for (const filename of cliOptions.filenames) { + compiledFiles += yield handle(filename); + } + if (!cliOptions.quiet) { + logSuccess(); + logSuccess.flush(); + } + } + if (cliOptions.watch) { + let processing = 0; + const { + filenames + } = cliOptions; + let getBase; + if (filenames.length === 1) { + const base = filenames[0]; + const absoluteBase = _path().resolve(base); + getBase = filename => { + return filename === absoluteBase ? _path().dirname(base) : base; + }; + } else { + const filenameToBaseMap = new Map(filenames.map(filename => { + const absoluteFilename = _path().resolve(filename); + return [absoluteFilename, _path().dirname(filename)]; + })); + const absoluteFilenames = new Map(filenames.map(filename => { + const absoluteFilename = _path().resolve(filename); + return [absoluteFilename, filename]; + })); + const { + sep + } = _path(); + getBase = filename => { + const base = filenameToBaseMap.get(filename); + if (base !== undefined) { + return base; + } + for (const [absoluteFilenameOrDir, relative] of absoluteFilenames) { + if (filename.startsWith(absoluteFilenameOrDir + sep)) { + filenameToBaseMap.set(filename, relative); + return relative; + } + } + return ""; + }; + } + filenames.forEach(filenameOrDir => { + watcher.watch(filenameOrDir); + }); + watcher.startWatcher(); + watcher.onFilesChange(_asyncToGenerator(function* (filenames) { + processing++; + if (startTime === null) startTime = process.hrtime(); + try { + const written = yield Promise.all(filenames.map(filename => handleFile(filename, getBase(filename)))); + compiledFiles += written.filter(Boolean).length; + } catch (err) { + console.error(err); + } + processing--; + if (processing === 0 && !cliOptions.quiet) logSuccess(); + })); + } + }); + return _ref.apply(this, arguments); +} + +//# sourceMappingURL=dir.js.map diff --git a/node_modules/@babel/cli/lib/babel/dir.js.map b/node_modules/@babel/cli/lib/babel/dir.js.map new file mode 100644 index 000000000..a604c2e66 --- /dev/null +++ b/node_modules/@babel/cli/lib/babel/dir.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_slash","data","require","_path","_fs","util","watcher","asyncGeneratorStep","gen","resolve","reject","_next","_throw","key","arg","info","value","error","done","Promise","then","_asyncToGenerator","fn","self","args","arguments","apply","err","undefined","FILE_TYPE","Object","freeze","NON_COMPILABLE","COMPILED","IGNORED","ERR_COMPILATION","outputFileSync","filePath","v","w","split","process","versions","node","mkdirSync","sync","path","dirname","recursive","fs","writeFileSync","_default","_x","_ref","cliOptions","babelOptions","write","_x2","_x3","_write","src","base","relative","isCompilableExtension","extensions","withExtension","keepFileExtension","extname","outFileExtension","dest","getDest","res","compile","assign","sourceFileName","slash","map","outputMap","sourceMaps","hasDataSourcemap","code","mapLoc","addSourceMappingUrl","file","basename","JSON","stringify","chmod","verbose","console","log","cwd","watch","filename","join","outDir","handleFile","_x4","_x5","_handleFile","written","copyFiles","copyIgnored","readFileSync","handle","_x6","_handle","filenameOrDir","existsSync","stat","statSync","isDirectory","count","files","readdir","includeDotfiles","compiledFiles","startTime","logSuccess","debounce","diff","hrtime","Math","round","enable","enableGlobbing","skipInitialBuild","deleteDirOnStart","deleteDir","filenames","quiet","flush","processing","getBase","length","absoluteBase","filenameToBaseMap","Map","absoluteFilename","absoluteFilenames","sep","get","absoluteFilenameOrDir","startsWith","set","forEach","startWatcher","onFilesChange","all","filter","Boolean"],"sources":["../../src/babel/dir.ts"],"sourcesContent":["import slash from \"slash\";\nimport path from \"path\";\nimport fs from \"fs\";\n\nimport * as util from \"./util.ts\";\nimport * as watcher from \"./watcher.ts\";\nimport type { CmdOptions } from \"./options.ts\";\n\nconst FILE_TYPE = Object.freeze({\n NON_COMPILABLE: \"NON_COMPILABLE\",\n COMPILED: \"COMPILED\",\n IGNORED: \"IGNORED\",\n ERR_COMPILATION: \"ERR_COMPILATION\",\n} as const);\n\nfunction outputFileSync(filePath: string, data: string | Buffer): void {\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, data);\n}\n\nexport default async function ({\n cliOptions,\n babelOptions,\n}: CmdOptions): Promise {\n async function write(\n src: string,\n base: string,\n ): Promise {\n let relative = path.relative(base, src);\n\n if (!util.isCompilableExtension(relative, cliOptions.extensions)) {\n return FILE_TYPE.NON_COMPILABLE;\n }\n\n relative = util.withExtension(\n relative,\n cliOptions.keepFileExtension\n ? path.extname(relative)\n : cliOptions.outFileExtension,\n );\n\n const dest = getDest(relative, base);\n\n try {\n const res = await util.compile(src, {\n ...babelOptions,\n sourceFileName: slash(path.relative(dest + \"/..\", src)),\n });\n\n if (!res) return FILE_TYPE.IGNORED;\n\n if (res.map) {\n let outputMap: \"both\" | \"external\" | false = false;\n if (babelOptions.sourceMaps && babelOptions.sourceMaps !== \"inline\") {\n outputMap = \"external\";\n } else if (babelOptions.sourceMaps == undefined) {\n outputMap = util.hasDataSourcemap(res.code) ? \"external\" : \"both\";\n }\n\n if (outputMap) {\n const mapLoc = dest + \".map\";\n if (outputMap === \"external\") {\n res.code = util.addSourceMappingUrl(res.code, mapLoc);\n }\n res.map.file = path.basename(relative);\n outputFileSync(mapLoc, JSON.stringify(res.map));\n }\n }\n\n outputFileSync(dest, res.code);\n util.chmod(src, dest);\n\n if (cliOptions.verbose) {\n console.log(path.relative(process.cwd(), src) + \" -> \" + dest);\n }\n\n return FILE_TYPE.COMPILED;\n } catch (err) {\n if (cliOptions.watch) {\n console.error(err);\n return FILE_TYPE.ERR_COMPILATION;\n }\n\n throw err;\n }\n }\n\n function getDest(filename: string, base: string): string {\n if (cliOptions.relative) {\n return path.join(base, cliOptions.outDir, filename);\n }\n return path.join(cliOptions.outDir, filename);\n }\n\n async function handleFile(src: string, base: string): Promise {\n const written = await write(src, base);\n\n if (\n (cliOptions.copyFiles && written === FILE_TYPE.NON_COMPILABLE) ||\n (cliOptions.copyIgnored && written === FILE_TYPE.IGNORED)\n ) {\n const filename = path.relative(base, src);\n const dest = getDest(filename, base);\n outputFileSync(dest, fs.readFileSync(src));\n util.chmod(src, dest);\n }\n return written === FILE_TYPE.COMPILED;\n }\n\n async function handle(filenameOrDir: string): Promise {\n if (!fs.existsSync(filenameOrDir)) return 0;\n\n const stat = fs.statSync(filenameOrDir);\n\n if (stat.isDirectory()) {\n const dirname = filenameOrDir;\n\n let count = 0;\n\n const files = util.readdir(dirname, cliOptions.includeDotfiles);\n for (const filename of files) {\n const src = path.join(dirname, filename);\n\n const written = await handleFile(src, dirname);\n if (written) count += 1;\n }\n\n return count;\n } else {\n const filename = filenameOrDir;\n const written = await handleFile(filename, path.dirname(filename));\n\n return written ? 1 : 0;\n }\n }\n\n let compiledFiles = 0;\n let startTime: [number, number] | null = null;\n\n const logSuccess = util.debounce(function () {\n if (startTime === null) {\n // This should never happen, but just in case it's better\n // to ignore the log message rather than making @babel/cli crash.\n return;\n }\n\n const diff = process.hrtime(startTime);\n\n console.log(\n `Successfully compiled ${compiledFiles} ${\n compiledFiles !== 1 ? \"files\" : \"file\"\n } with Babel (${diff[0] * 1e3 + Math.round(diff[1] / 1e6)}ms).`,\n );\n compiledFiles = 0;\n startTime = null;\n }, 100);\n\n if (cliOptions.watch) watcher.enable({ enableGlobbing: true });\n\n if (!cliOptions.skipInitialBuild) {\n if (cliOptions.deleteDirOnStart) {\n util.deleteDir(cliOptions.outDir);\n }\n\n fs.mkdirSync(cliOptions.outDir, { recursive: true });\n\n startTime = process.hrtime();\n\n for (const filename of cliOptions.filenames) {\n // compiledFiles is just incremented without reading its value, so we\n // don't risk race conditions.\n // eslint-disable-next-line require-atomic-updates\n compiledFiles += await handle(filename);\n }\n\n if (!cliOptions.quiet) {\n logSuccess();\n logSuccess.flush();\n }\n }\n\n if (cliOptions.watch) {\n // This, alongside with debounce, allows us to only log\n // when we are sure that all the files have been compiled.\n let processing = 0;\n const { filenames } = cliOptions;\n let getBase: (filename: string) => string | null;\n if (filenames.length === 1) {\n // fast path: If there is only one filenames, we know it must be the base\n const base = filenames[0];\n const absoluteBase = path.resolve(base);\n getBase = filename => {\n return filename === absoluteBase ? path.dirname(base) : base;\n };\n } else {\n // A map from absolute compiled file path to its base, from which\n // the output destination will be determined\n const filenameToBaseMap: Map = new Map(\n filenames.map(filename => {\n const absoluteFilename = path.resolve(filename);\n return [absoluteFilename, path.dirname(filename)];\n }),\n );\n\n const absoluteFilenames: Map = new Map(\n filenames.map(filename => {\n const absoluteFilename = path.resolve(filename);\n return [absoluteFilename, filename];\n }),\n );\n\n const { sep } = path;\n // determine base from the absolute file path\n getBase = filename => {\n const base = filenameToBaseMap.get(filename);\n if (base !== undefined) {\n return base;\n }\n for (const [absoluteFilenameOrDir, relative] of absoluteFilenames) {\n if (filename.startsWith(absoluteFilenameOrDir + sep)) {\n filenameToBaseMap.set(filename, relative);\n return relative;\n }\n }\n // Can't determine the base, probably external deps\n return \"\";\n };\n }\n\n filenames.forEach(filenameOrDir => {\n watcher.watch(filenameOrDir);\n });\n\n watcher.startWatcher();\n\n watcher.onFilesChange(async filenames => {\n processing++;\n if (startTime === null) startTime = process.hrtime();\n\n try {\n const written = await Promise.all(\n filenames.map(filename => handleFile(filename, getBase(filename))),\n );\n\n compiledFiles += written.filter(Boolean).length;\n } catch (err) {\n console.error(err);\n }\n\n processing--;\n if (processing === 0 && !cliOptions.quiet) logSuccess();\n });\n }\n}\n"],"mappings":";;;;;;AAAA,SAAAA,OAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,MAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,MAAA;EAAA,MAAAF,IAAA,GAAAC,OAAA;EAAAC,KAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAG,IAAA;EAAA,MAAAH,IAAA,GAAAC,OAAA;EAAAE,GAAA,YAAAA,CAAA;IAAA,OAAAH,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,IAAAI,IAAA,GAAAH,OAAA;AACA,IAAAI,OAAA,GAAAJ,OAAA;AAAwC,SAAAK,mBAAAC,GAAA,EAAAC,OAAA,EAAAC,MAAA,EAAAC,KAAA,EAAAC,MAAA,EAAAC,GAAA,EAAAC,GAAA,cAAAC,IAAA,GAAAP,GAAA,CAAAK,GAAA,EAAAC,GAAA,OAAAE,KAAA,GAAAD,IAAA,CAAAC,KAAA,WAAAC,KAAA,IAAAP,MAAA,CAAAO,KAAA,iBAAAF,IAAA,CAAAG,IAAA,IAAAT,OAAA,CAAAO,KAAA,YAAAG,OAAA,CAAAV,OAAA,CAAAO,KAAA,EAAAI,IAAA,CAAAT,KAAA,EAAAC,MAAA;AAAA,SAAAS,kBAAAC,EAAA,6BAAAC,IAAA,SAAAC,IAAA,GAAAC,SAAA,aAAAN,OAAA,WAAAV,OAAA,EAAAC,MAAA,QAAAF,GAAA,GAAAc,EAAA,CAAAI,KAAA,CAAAH,IAAA,EAAAC,IAAA,YAAAb,MAAAK,KAAA,IAAAT,kBAAA,CAAAC,GAAA,EAAAC,OAAA,EAAAC,MAAA,EAAAC,KAAA,EAAAC,MAAA,UAAAI,KAAA,cAAAJ,OAAAe,GAAA,IAAApB,kBAAA,CAAAC,GAAA,EAAAC,OAAA,EAAAC,MAAA,EAAAC,KAAA,EAAAC,MAAA,WAAAe,GAAA,KAAAhB,KAAA,CAAAiB,SAAA;AAGxC,MAAMC,SAAS,GAAGC,MAAM,CAACC,MAAM,CAAC;EAC9BC,cAAc,EAAE,gBAAgB;EAChCC,QAAQ,EAAE,UAAU;EACpBC,OAAO,EAAE,SAAS;EAClBC,eAAe,EAAE;AACnB,CAAU,CAAC;AAEX,SAASC,cAAcA,CAACC,QAAgB,EAAEpC,IAAqB,EAAQ;EACrE,GAAAqC,CAAA,EAAAC,CAAA,MAAAD,CAAA,GAAAA,CAAA,CAAAE,KAAA,OAAAD,CAAA,GAAAA,CAAA,CAAAC,KAAA,QAAAF,CAAA,OAAAC,CAAA,OAAAD,CAAA,OAAAC,CAAA,QAAAD,CAAA,QAAAC,CAAA,MAAAE,OAAA,CAAAC,QAAA,CAAAC,IAAA,aAAAvC,GAAA,GAAAwC,SAAA,GAAA1C,OAAA,aAAA2C,IAAA,EAAaC,MAAGA,CAAC,CAACC,OAAO,CAACV,QAAQ,CAAC,EAAE;IAAEW,SAAS,EAAE;EAAK,CAAC,CAAC;EACzDC,IAACA,CAAC,CAACC,aAAa,CAACb,QAAQ,EAAEpC,IAAI,CAAC;AAClC;AAAC,SAAAkD,SAAAC,EAAA;EAAA,OAAAC,IAAA,CAAA3B,KAAA,OAAAD,SAAA;AAAA;AAAA,SAAA4B,KAAA;EAAAA,IAAA,GAAAhC,iBAAA,CAEc,WAAgB;IAC7BiC,UAAU;IACVC;EACU,CAAC,EAAiB;IAAA,SACbC,KAAKA,CAAAC,GAAA,EAAAC,GAAA;MAAA,OAAAC,MAAA,CAAAjC,KAAA,OAAAD,SAAA;IAAA;IAAA,SAAAkC,OAAA;MAAAA,MAAA,GAAAtC,iBAAA,CAApB,WACEuC,GAAW,EACXC,IAAY,EACqB;QACjC,IAAIC,QAAQ,GAAGhB,MAAGA,CAAC,CAACgB,QAAQ,CAACD,IAAI,EAAED,GAAG,CAAC;QAEvC,IAAI,CAACvD,IAAI,CAAC0D,qBAAqB,CAACD,QAAQ,EAAER,UAAU,CAACU,UAAU,CAAC,EAAE;UAChE,OAAOnC,SAAS,CAACG,cAAc;QACjC;QAEA8B,QAAQ,GAAGzD,IAAI,CAAC4D,aAAa,CAC3BH,QAAQ,EACRR,UAAU,CAACY,iBAAiB,GACxBpB,MAAGA,CAAC,CAACqB,OAAO,CAACL,QAAQ,CAAC,GACtBR,UAAU,CAACc,gBACjB,CAAC;QAED,MAAMC,IAAI,GAAGC,OAAO,CAACR,QAAQ,EAAED,IAAI,CAAC;QAEpC,IAAI;UACF,MAAMU,GAAG,SAASlE,IAAI,CAACmE,OAAO,CAACZ,GAAG,EAAA9B,MAAA,CAAA2C,MAAA,KAC7BlB,YAAY;YACfmB,cAAc,EAAEC,OAAIA,CAAC,CAAC7B,MAAGA,CAAC,CAACgB,QAAQ,CAACO,IAAI,GAAG,KAAK,EAAET,GAAG,CAAC;UAAC,EACxD,CAAC;UAEF,IAAI,CAACW,GAAG,EAAE,OAAO1C,SAAS,CAACK,OAAO;UAElC,IAAIqC,GAAG,CAACK,GAAG,EAAE;YACX,IAAIC,SAAsC,GAAG,KAAK;YAClD,IAAItB,YAAY,CAACuB,UAAU,IAAIvB,YAAY,CAACuB,UAAU,KAAK,QAAQ,EAAE;cACnED,SAAS,GAAG,UAAU;YACxB,CAAC,MAAM,IAAItB,YAAY,CAACuB,UAAU,IAAIlD,SAAS,EAAE;cAC/CiD,SAAS,GAAGxE,IAAI,CAAC0E,gBAAgB,CAACR,GAAG,CAACS,IAAI,CAAC,GAAG,UAAU,GAAG,MAAM;YACnE;YAEA,IAAIH,SAAS,EAAE;cACb,MAAMI,MAAM,GAAGZ,IAAI,GAAG,MAAM;cAC5B,IAAIQ,SAAS,KAAK,UAAU,EAAE;gBAC5BN,GAAG,CAACS,IAAI,GAAG3E,IAAI,CAAC6E,mBAAmB,CAACX,GAAG,CAACS,IAAI,EAAEC,MAAM,CAAC;cACvD;cACAV,GAAG,CAACK,GAAG,CAACO,IAAI,GAAGrC,MAAGA,CAAC,CAACsC,QAAQ,CAACtB,QAAQ,CAAC;cACtC1B,cAAc,CAAC6C,MAAM,EAAEI,IAAI,CAACC,SAAS,CAACf,GAAG,CAACK,GAAG,CAAC,CAAC;YACjD;UACF;UAEAxC,cAAc,CAACiC,IAAI,EAAEE,GAAG,CAACS,IAAI,CAAC;UAC9B3E,IAAI,CAACkF,KAAK,CAAC3B,GAAG,EAAES,IAAI,CAAC;UAErB,IAAIf,UAAU,CAACkC,OAAO,EAAE;YACtBC,OAAO,CAACC,GAAG,CAAC5C,MAAGA,CAAC,CAACgB,QAAQ,CAACrB,OAAO,CAACkD,GAAG,CAAC,CAAC,EAAE/B,GAAG,CAAC,GAAG,MAAM,GAAGS,IAAI,CAAC;UAChE;UAEA,OAAOxC,SAAS,CAACI,QAAQ;QAC3B,CAAC,CAAC,OAAON,GAAG,EAAE;UACZ,IAAI2B,UAAU,CAACsC,KAAK,EAAE;YACpBH,OAAO,CAACxE,KAAK,CAACU,GAAG,CAAC;YAClB,OAAOE,SAAS,CAACM,eAAe;UAClC;UAEA,MAAMR,GAAG;QACX;MACF,CAAC;MAAA,OAAAgC,MAAA,CAAAjC,KAAA,OAAAD,SAAA;IAAA;IAED,SAAS6C,OAAOA,CAACuB,QAAgB,EAAEhC,IAAY,EAAU;MACvD,IAAIP,UAAU,CAACQ,QAAQ,EAAE;QACvB,OAAOhB,MAAGA,CAAC,CAACgD,IAAI,CAACjC,IAAI,EAAEP,UAAU,CAACyC,MAAM,EAAEF,QAAQ,CAAC;MACrD;MACA,OAAO/C,MAAGA,CAAC,CAACgD,IAAI,CAACxC,UAAU,CAACyC,MAAM,EAAEF,QAAQ,CAAC;IAC/C;IAAC,SAEcG,UAAUA,CAAAC,GAAA,EAAAC,GAAA;MAAA,OAAAC,WAAA,CAAAzE,KAAA,OAAAD,SAAA;IAAA;IAAA,SAAA0E,YAAA;MAAAA,WAAA,GAAA9E,iBAAA,CAAzB,WAA0BuC,GAAW,EAAEC,IAAY,EAAoB;QACrE,MAAMuC,OAAO,SAAS5C,KAAK,CAACI,GAAG,EAAEC,IAAI,CAAC;QAEtC,IACGP,UAAU,CAAC+C,SAAS,IAAID,OAAO,KAAKvE,SAAS,CAACG,cAAc,IAC5DsB,UAAU,CAACgD,WAAW,IAAIF,OAAO,KAAKvE,SAAS,CAACK,OAAQ,EACzD;UACA,MAAM2D,QAAQ,GAAG/C,MAAGA,CAAC,CAACgB,QAAQ,CAACD,IAAI,EAAED,GAAG,CAAC;UACzC,MAAMS,IAAI,GAAGC,OAAO,CAACuB,QAAQ,EAAEhC,IAAI,CAAC;UACpCzB,cAAc,CAACiC,IAAI,EAAEpB,IAACA,CAAC,CAACsD,YAAY,CAAC3C,GAAG,CAAC,CAAC;UAC1CvD,IAAI,CAACkF,KAAK,CAAC3B,GAAG,EAAES,IAAI,CAAC;QACvB;QACA,OAAO+B,OAAO,KAAKvE,SAAS,CAACI,QAAQ;MACvC,CAAC;MAAA,OAAAkE,WAAA,CAAAzE,KAAA,OAAAD,SAAA;IAAA;IAAA,SAEc+E,MAAMA,CAAAC,GAAA;MAAA,OAAAC,OAAA,CAAAhF,KAAA,OAAAD,SAAA;IAAA;IAAA,SAAAiF,QAAA;MAAAA,OAAA,GAAArF,iBAAA,CAArB,WAAsBsF,aAAqB,EAAmB;QAC5D,IAAI,CAAC1D,IAACA,CAAC,CAAC2D,UAAU,CAACD,aAAa,CAAC,EAAE,OAAO,CAAC;QAE3C,MAAME,IAAI,GAAG5D,IAACA,CAAC,CAAC6D,QAAQ,CAACH,aAAa,CAAC;QAEvC,IAAIE,IAAI,CAACE,WAAW,CAAC,CAAC,EAAE;UACtB,MAAMhE,OAAO,GAAG4D,aAAa;UAE7B,IAAIK,KAAK,GAAG,CAAC;UAEb,MAAMC,KAAK,GAAG5G,IAAI,CAAC6G,OAAO,CAACnE,OAAO,EAAEO,UAAU,CAAC6D,eAAe,CAAC;UAC/D,KAAK,MAAMtB,QAAQ,IAAIoB,KAAK,EAAE;YAC5B,MAAMrD,GAAG,GAAGd,MAAGA,CAAC,CAACgD,IAAI,CAAC/C,OAAO,EAAE8C,QAAQ,CAAC;YAExC,MAAMO,OAAO,SAASJ,UAAU,CAACpC,GAAG,EAAEb,OAAO,CAAC;YAC9C,IAAIqD,OAAO,EAAEY,KAAK,IAAI,CAAC;UACzB;UAEA,OAAOA,KAAK;QACd,CAAC,MAAM;UACL,MAAMnB,QAAQ,GAAGc,aAAa;UAC9B,MAAMP,OAAO,SAASJ,UAAU,CAACH,QAAQ,EAAE/C,MAAGA,CAAC,CAACC,OAAO,CAAC8C,QAAQ,CAAC,CAAC;UAElE,OAAOO,OAAO,GAAG,CAAC,GAAG,CAAC;QACxB;MACF,CAAC;MAAA,OAAAM,OAAA,CAAAhF,KAAA,OAAAD,SAAA;IAAA;IAED,IAAI2F,aAAa,GAAG,CAAC;IACrB,IAAIC,SAAkC,GAAG,IAAI;IAE7C,MAAMC,UAAU,GAAGjH,IAAI,CAACkH,QAAQ,CAAC,YAAY;MAC3C,IAAIF,SAAS,KAAK,IAAI,EAAE;QAGtB;MACF;MAEA,MAAMG,IAAI,GAAG/E,OAAO,CAACgF,MAAM,CAACJ,SAAS,CAAC;MAEtC5B,OAAO,CAACC,GAAG,CACR,yBAAwB0B,aAAc,IACrCA,aAAa,KAAK,CAAC,GAAG,OAAO,GAAG,MACjC,gBAAeI,IAAI,CAAC,CAAC,CAAC,GAAG,GAAG,GAAGE,IAAI,CAACC,KAAK,CAACH,IAAI,CAAC,CAAC,CAAC,GAAG,GAAG,CAAE,MAC5D,CAAC;MACDJ,aAAa,GAAG,CAAC;MACjBC,SAAS,GAAG,IAAI;IAClB,CAAC,EAAE,GAAG,CAAC;IAEP,IAAI/D,UAAU,CAACsC,KAAK,EAAEtF,OAAO,CAACsH,MAAM,CAAC;MAAEC,cAAc,EAAE;IAAK,CAAC,CAAC;IAE9D,IAAI,CAACvE,UAAU,CAACwE,gBAAgB,EAAE;MAChC,IAAIxE,UAAU,CAACyE,gBAAgB,EAAE;QAC/B1H,IAAI,CAAC2H,SAAS,CAAC1E,UAAU,CAACyC,MAAM,CAAC;MACnC;MAEA,GAAAzD,CAAA,EAAAC,CAAA,MAAAD,CAAA,GAAAA,CAAA,CAAAE,KAAA,OAAAD,CAAA,GAAAA,CAAA,CAAAC,KAAA,QAAAF,CAAA,OAAAC,CAAA,OAAAD,CAAA,OAAAC,CAAA,QAAAD,CAAA,QAAAC,CAAA,MAAAE,OAAA,CAAAC,QAAA,CAAAC,IAAA,aAAAvC,GAAA,GAAAwC,SAAA,GAAA1C,OAAA,aAAA2C,IAAA,EAAaS,UAAU,CAACyC,MAAM,EAAE;QAAE/C,SAAS,EAAE;MAAK,CAAC,CAAC;MAEpDqE,SAAS,GAAG5E,OAAO,CAACgF,MAAM,CAAC,CAAC;MAE5B,KAAK,MAAM5B,QAAQ,IAAIvC,UAAU,CAAC2E,SAAS,EAAE;QAI3Cb,aAAa,UAAUZ,MAAM,CAACX,QAAQ,CAAC;MACzC;MAEA,IAAI,CAACvC,UAAU,CAAC4E,KAAK,EAAE;QACrBZ,UAAU,CAAC,CAAC;QACZA,UAAU,CAACa,KAAK,CAAC,CAAC;MACpB;IACF;IAEA,IAAI7E,UAAU,CAACsC,KAAK,EAAE;MAGpB,IAAIwC,UAAU,GAAG,CAAC;MAClB,MAAM;QAAEH;MAAU,CAAC,GAAG3E,UAAU;MAChC,IAAI+E,OAA4C;MAChD,IAAIJ,SAAS,CAACK,MAAM,KAAK,CAAC,EAAE;QAE1B,MAAMzE,IAAI,GAAGoE,SAAS,CAAC,CAAC,CAAC;QACzB,MAAMM,YAAY,GAAGzF,MAAGA,CAAC,CAACrC,OAAO,CAACoD,IAAI,CAAC;QACvCwE,OAAO,GAAGxC,QAAQ,IAAI;UACpB,OAAOA,QAAQ,KAAK0C,YAAY,GAAGzF,MAAGA,CAAC,CAACC,OAAO,CAACc,IAAI,CAAC,GAAGA,IAAI;QAC9D,CAAC;MACH,CAAC,MAAM;QAGL,MAAM2E,iBAAsC,GAAG,IAAIC,GAAG,CACpDR,SAAS,CAACrD,GAAG,CAACiB,QAAQ,IAAI;UACxB,MAAM6C,gBAAgB,GAAG5F,MAAGA,CAAC,CAACrC,OAAO,CAACoF,QAAQ,CAAC;UAC/C,OAAO,CAAC6C,gBAAgB,EAAE5F,MAAGA,CAAC,CAACC,OAAO,CAAC8C,QAAQ,CAAC,CAAC;QACnD,CAAC,CACH,CAAC;QAED,MAAM8C,iBAAsC,GAAG,IAAIF,GAAG,CACpDR,SAAS,CAACrD,GAAG,CAACiB,QAAQ,IAAI;UACxB,MAAM6C,gBAAgB,GAAG5F,MAAGA,CAAC,CAACrC,OAAO,CAACoF,QAAQ,CAAC;UAC/C,OAAO,CAAC6C,gBAAgB,EAAE7C,QAAQ,CAAC;QACrC,CAAC,CACH,CAAC;QAED,MAAM;UAAE+C;QAAI,CAAC,GAAG9F,MAAGA,CAAC;QAEpBuF,OAAO,GAAGxC,QAAQ,IAAI;UACpB,MAAMhC,IAAI,GAAG2E,iBAAiB,CAACK,GAAG,CAAChD,QAAQ,CAAC;UAC5C,IAAIhC,IAAI,KAAKjC,SAAS,EAAE;YACtB,OAAOiC,IAAI;UACb;UACA,KAAK,MAAM,CAACiF,qBAAqB,EAAEhF,QAAQ,CAAC,IAAI6E,iBAAiB,EAAE;YACjE,IAAI9C,QAAQ,CAACkD,UAAU,CAACD,qBAAqB,GAAGF,GAAG,CAAC,EAAE;cACpDJ,iBAAiB,CAACQ,GAAG,CAACnD,QAAQ,EAAE/B,QAAQ,CAAC;cACzC,OAAOA,QAAQ;YACjB;UACF;UAEA,OAAO,EAAE;QACX,CAAC;MACH;MAEAmE,SAAS,CAACgB,OAAO,CAACtC,aAAa,IAAI;QACjCrG,OAAO,CAACsF,KAAK,CAACe,aAAa,CAAC;MAC9B,CAAC,CAAC;MAEFrG,OAAO,CAAC4I,YAAY,CAAC,CAAC;MAEtB5I,OAAO,CAAC6I,aAAa,CAAA9H,iBAAA,CAAC,WAAM4G,SAAS,EAAI;QACvCG,UAAU,EAAE;QACZ,IAAIf,SAAS,KAAK,IAAI,EAAEA,SAAS,GAAG5E,OAAO,CAACgF,MAAM,CAAC,CAAC;QAEpD,IAAI;UACF,MAAMrB,OAAO,SAASjF,OAAO,CAACiI,GAAG,CAC/BnB,SAAS,CAACrD,GAAG,CAACiB,QAAQ,IAAIG,UAAU,CAACH,QAAQ,EAAEwC,OAAO,CAACxC,QAAQ,CAAC,CAAC,CACnE,CAAC;UAEDuB,aAAa,IAAIhB,OAAO,CAACiD,MAAM,CAACC,OAAO,CAAC,CAAChB,MAAM;QACjD,CAAC,CAAC,OAAO3G,GAAG,EAAE;UACZ8D,OAAO,CAACxE,KAAK,CAACU,GAAG,CAAC;QACpB;QAEAyG,UAAU,EAAE;QACZ,IAAIA,UAAU,KAAK,CAAC,IAAI,CAAC9E,UAAU,CAAC4E,KAAK,EAAEZ,UAAU,CAAC,CAAC;MACzD,CAAC,EAAC;IACJ;EACF,CAAC;EAAA,OAAAjE,IAAA,CAAA3B,KAAA,OAAAD,SAAA;AAAA","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/cli/lib/babel/file.js b/node_modules/@babel/cli/lib/babel/file.js new file mode 100644 index 000000000..a363c6139 --- /dev/null +++ b/node_modules/@babel/cli/lib/babel/file.js @@ -0,0 +1,231 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; +function _convertSourceMap() { + const data = require("convert-source-map"); + _convertSourceMap = function () { + return data; + }; + return data; +} +function _traceMapping() { + const data = require("@jridgewell/trace-mapping"); + _traceMapping = function () { + return data; + }; + return data; +} +function _slash() { + const data = require("slash"); + _slash = function () { + return data; + }; + return data; +} +function _path() { + const data = require("path"); + _path = function () { + return data; + }; + return data; +} +function _fs() { + const data = require("fs"); + _fs = function () { + return data; + }; + return data; +} +var util = require("./util.js"); +var watcher = require("./watcher.js"); +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function _default(_x) { + return _ref.apply(this, arguments); +} +function _ref() { + _ref = _asyncToGenerator(function* ({ + cliOptions, + babelOptions + }) { + function buildResult(fileResults) { + const mapSections = []; + let code = ""; + let offset = 0; + let hasRawMap = false; + for (const result of fileResults) { + if (!result) continue; + hasRawMap = !!result.map; + mapSections.push({ + offset: { + line: offset, + column: 0 + }, + map: result.map || { + version: 3, + names: [], + sources: [], + mappings: [] + } + }); + code += result.code + "\n"; + offset += countNewlines(result.code) + 1; + } + const map = new (_traceMapping().AnyMap)({ + version: 3, + file: cliOptions.sourceMapTarget || _path().basename(cliOptions.outFile || "") || "stdout", + sections: mapSections + }); + map.sourceRoot = babelOptions.sourceRoot; + if (babelOptions.sourceMaps === "inline" || !cliOptions.outFile && babelOptions.sourceMaps) { + code += "\n" + _convertSourceMap().fromObject((0, _traceMapping().encodedMap)(map)).toComment(); + } + return { + map: map, + code: code, + hasRawMap: hasRawMap + }; + } + function countNewlines(code) { + let count = 0; + let index = -1; + while ((index = code.indexOf("\n", index + 1)) !== -1) { + count++; + } + return count; + } + function output(fileResults) { + const result = buildResult(fileResults); + if (cliOptions.outFile) { + (((v, w) => (v = v.split("."), w = w.split("."), +v[0] > +w[0] || v[0] == w[0] && +v[1] >= +w[1]))(process.versions.node, "10.12") ? _fs().mkdirSync : require("make-dir").sync)(_path().dirname(cliOptions.outFile), { + recursive: true + }); + let outputMap = false; + if (babelOptions.sourceMaps && babelOptions.sourceMaps !== "inline") { + outputMap = "external"; + } else if (babelOptions.sourceMaps == undefined && result.hasRawMap) { + outputMap = util.hasDataSourcemap(result.code) ? "external" : "both"; + } + if (outputMap) { + const mapLoc = cliOptions.outFile + ".map"; + if (outputMap === "external") { + result.code = util.addSourceMappingUrl(result.code, mapLoc); + } + _fs().writeFileSync(mapLoc, JSON.stringify((0, _traceMapping().encodedMap)(result.map))); + } + _fs().writeFileSync(cliOptions.outFile, result.code); + } else { + process.stdout.write(result.code + "\n"); + } + } + function readStdin() { + return new Promise((resolve, reject) => { + let code = ""; + process.stdin.setEncoding("utf8"); + process.stdin.on("readable", function () { + const chunk = process.stdin.read(); + if (chunk !== null) code += chunk; + }); + process.stdin.on("end", function () { + resolve(code); + }); + process.stdin.on("error", reject); + }); + } + function stdin() { + return _stdin.apply(this, arguments); + } + function _stdin() { + _stdin = _asyncToGenerator(function* () { + const code = yield readStdin(); + const res = yield util.transformRepl(cliOptions.filename, code, Object.assign({}, babelOptions, { + sourceFileName: "stdin" + })); + output([res]); + }); + return _stdin.apply(this, arguments); + } + function walk(_x2) { + return _walk.apply(this, arguments); + } + function _walk() { + _walk = _asyncToGenerator(function* (filenames) { + const _filenames = []; + filenames.forEach(function (filename) { + if (!_fs().existsSync(filename)) return; + const stat = _fs().statSync(filename); + if (stat.isDirectory()) { + const dirname = filename; + util.readdirForCompilable(filename, cliOptions.includeDotfiles, cliOptions.extensions).forEach(function (filename) { + _filenames.push(_path().join(dirname, filename)); + }); + } else { + _filenames.push(filename); + } + }); + const results = yield Promise.all(_filenames.map(_asyncToGenerator(function* (filename) { + let sourceFilename = filename; + if (cliOptions.outFile) { + sourceFilename = _path().relative(_path().dirname(cliOptions.outFile), sourceFilename); + } + sourceFilename = _slash()(sourceFilename); + try { + return yield util.compile(filename, Object.assign({}, babelOptions, { + sourceFileName: sourceFilename, + sourceMaps: babelOptions.sourceMaps === "inline" ? true : babelOptions.sourceMaps + })); + } catch (err) { + if (!cliOptions.watch) { + throw err; + } + console.error(err); + return null; + } + }))); + output(results); + }); + return _walk.apply(this, arguments); + } + function files(_x3) { + return _files.apply(this, arguments); + } + function _files() { + _files = _asyncToGenerator(function* (filenames) { + if (cliOptions.watch) { + watcher.enable({ + enableGlobbing: false + }); + } + if (!cliOptions.skipInitialBuild) { + yield walk(filenames); + } + if (cliOptions.watch) { + filenames.forEach(watcher.watch); + watcher.startWatcher(); + watcher.onFilesChange((changes, event, cause) => { + const actionableChange = changes.some(filename => util.isCompilableExtension(filename, cliOptions.extensions) || filenames.includes(filename)); + if (!actionableChange) return; + if (cliOptions.verbose) { + console.log(`${event} ${cause}`); + } + walk(filenames).catch(err => { + console.error(err); + }); + }); + } + }); + return _files.apply(this, arguments); + } + if (cliOptions.filenames.length) { + yield files(cliOptions.filenames); + } else { + yield stdin(); + } + }); + return _ref.apply(this, arguments); +} + +//# sourceMappingURL=file.js.map diff --git a/node_modules/@babel/cli/lib/babel/file.js.map b/node_modules/@babel/cli/lib/babel/file.js.map new file mode 100644 index 000000000..7dec8cd57 --- /dev/null +++ b/node_modules/@babel/cli/lib/babel/file.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_convertSourceMap","data","require","_traceMapping","_slash","_path","_fs","util","watcher","asyncGeneratorStep","gen","resolve","reject","_next","_throw","key","arg","info","value","error","done","Promise","then","_asyncToGenerator","fn","self","args","arguments","apply","err","undefined","_default","_x","_ref","cliOptions","babelOptions","buildResult","fileResults","mapSections","code","offset","hasRawMap","result","map","push","line","column","version","names","sources","mappings","countNewlines","AnyMap","file","sourceMapTarget","path","basename","outFile","sections","sourceRoot","sourceMaps","convertSourceMap","fromObject","encodedMap","toComment","count","index","indexOf","output","v","w","split","process","versions","node","mkdirSync","sync","dirname","recursive","outputMap","hasDataSourcemap","mapLoc","addSourceMappingUrl","fs","writeFileSync","JSON","stringify","stdout","write","readStdin","stdin","setEncoding","on","chunk","read","_stdin","res","transformRepl","filename","Object","assign","sourceFileName","walk","_x2","_walk","filenames","_filenames","forEach","existsSync","stat","statSync","isDirectory","readdirForCompilable","includeDotfiles","extensions","join","results","all","sourceFilename","relative","slash","compile","watch","console","files","_x3","_files","enable","enableGlobbing","skipInitialBuild","startWatcher","onFilesChange","changes","event","cause","actionableChange","some","isCompilableExtension","includes","verbose","log","catch","length"],"sources":["../../src/babel/file.ts"],"sourcesContent":["import convertSourceMap from \"convert-source-map\";\nimport { AnyMap, encodedMap } from \"@jridgewell/trace-mapping\";\nimport slash from \"slash\";\nimport path from \"path\";\nimport fs from \"fs\";\n\nimport * as util from \"./util.ts\";\nimport type { CmdOptions } from \"./options.ts\";\nimport * as watcher from \"./watcher.ts\";\n\nimport type {\n EncodedSourceMap,\n SectionedSourceMap,\n SourceMapInput,\n TraceMap,\n} from \"@jridgewell/trace-mapping\";\nimport type { FileResult } from \"@babel/core\";\n\ntype CompilationOutput = {\n code: string;\n map: SourceMapInput;\n hasRawMap: boolean;\n};\n\nexport default async function ({\n cliOptions,\n babelOptions,\n}: CmdOptions): Promise {\n function buildResult(fileResults: Array): CompilationOutput {\n const mapSections: SectionedSourceMap[\"sections\"] = [];\n\n let code = \"\";\n let offset = 0;\n\n let hasRawMap = false;\n\n for (const result of fileResults) {\n if (!result) continue;\n\n hasRawMap = !!result.map;\n\n mapSections.push({\n offset: { line: offset, column: 0 },\n map: (result.map as EncodedSourceMap) || {\n version: 3,\n names: [],\n sources: [],\n mappings: [],\n },\n });\n\n code += result.code + \"\\n\";\n offset += countNewlines(result.code) + 1;\n }\n\n const map = new AnyMap({\n version: 3,\n file:\n cliOptions.sourceMapTarget ||\n path.basename(cliOptions.outFile || \"\") ||\n \"stdout\",\n sections: mapSections,\n });\n // For some reason, the spec doesn't allow sourceRoot when constructing a\n // sectioned sourcemap. But AllMap returns a regular sourcemap, we can\n // freely add to with a sourceRoot.\n map.sourceRoot = babelOptions.sourceRoot;\n\n // add the inline sourcemap comment if we've either explicitly asked for inline source\n // maps, or we've requested them without any output file\n if (\n babelOptions.sourceMaps === \"inline\" ||\n (!cliOptions.outFile && babelOptions.sourceMaps)\n ) {\n code += \"\\n\" + convertSourceMap.fromObject(encodedMap(map)).toComment();\n }\n\n return {\n map: map,\n code: code,\n hasRawMap: hasRawMap,\n };\n }\n\n function countNewlines(code: string): number {\n let count = 0;\n let index = -1;\n while ((index = code.indexOf(\"\\n\", index + 1)) !== -1) {\n count++;\n }\n return count;\n }\n\n function output(fileResults: Array): void {\n const result = buildResult(fileResults);\n\n if (cliOptions.outFile) {\n fs.mkdirSync(path.dirname(cliOptions.outFile), { recursive: true });\n\n let outputMap: \"both\" | \"external\" | false = false;\n if (babelOptions.sourceMaps && babelOptions.sourceMaps !== \"inline\") {\n outputMap = \"external\";\n } else if (babelOptions.sourceMaps == undefined && result.hasRawMap) {\n outputMap = util.hasDataSourcemap(result.code) ? \"external\" : \"both\";\n }\n\n if (outputMap) {\n const mapLoc = cliOptions.outFile + \".map\";\n if (outputMap === \"external\") {\n result.code = util.addSourceMappingUrl(result.code, mapLoc);\n }\n fs.writeFileSync(\n mapLoc,\n JSON.stringify(encodedMap(result.map as TraceMap)),\n );\n }\n\n fs.writeFileSync(cliOptions.outFile, result.code);\n } else {\n process.stdout.write(result.code + \"\\n\");\n }\n }\n\n function readStdin(): Promise {\n return new Promise((resolve, reject): void => {\n let code = \"\";\n\n process.stdin.setEncoding(\"utf8\");\n\n process.stdin.on(\"readable\", function () {\n const chunk = process.stdin.read();\n if (chunk !== null) code += chunk;\n });\n\n process.stdin.on(\"end\", function () {\n resolve(code);\n });\n process.stdin.on(\"error\", reject);\n });\n }\n\n async function stdin(): Promise {\n const code = await readStdin();\n\n const res = await util.transformRepl(cliOptions.filename, code, {\n ...babelOptions,\n sourceFileName: \"stdin\",\n });\n\n output([res]);\n }\n\n async function walk(filenames: Array): Promise {\n const _filenames: string[] = [];\n\n filenames.forEach(function (filename) {\n if (!fs.existsSync(filename)) return;\n\n const stat = fs.statSync(filename);\n if (stat.isDirectory()) {\n const dirname = filename;\n\n util\n .readdirForCompilable(\n filename,\n cliOptions.includeDotfiles,\n cliOptions.extensions,\n )\n .forEach(function (filename) {\n _filenames.push(path.join(dirname, filename));\n });\n } else {\n _filenames.push(filename);\n }\n });\n\n const results = await Promise.all(\n _filenames.map(async function (filename: string): Promise {\n let sourceFilename = filename;\n if (cliOptions.outFile) {\n sourceFilename = path.relative(\n path.dirname(cliOptions.outFile),\n sourceFilename,\n );\n }\n sourceFilename = slash(sourceFilename);\n\n try {\n return await util.compile(filename, {\n ...babelOptions,\n sourceFileName: sourceFilename,\n // Since we're compiling everything to be merged together,\n // \"inline\" applies to the final output file, but not to the individual\n // files being concatenated.\n sourceMaps:\n babelOptions.sourceMaps === \"inline\"\n ? true\n : babelOptions.sourceMaps,\n });\n } catch (err) {\n if (!cliOptions.watch) {\n throw err;\n }\n\n console.error(err);\n return null;\n }\n }),\n );\n\n output(results);\n }\n\n async function files(filenames: Array): Promise {\n if (cliOptions.watch) {\n watcher.enable({ enableGlobbing: false });\n }\n\n if (!cliOptions.skipInitialBuild) {\n await walk(filenames);\n }\n\n if (cliOptions.watch) {\n filenames.forEach(watcher.watch);\n\n watcher.startWatcher();\n\n watcher.onFilesChange((changes, event, cause) => {\n const actionableChange = changes.some(\n filename =>\n util.isCompilableExtension(filename, cliOptions.extensions) ||\n filenames.includes(filename),\n );\n if (!actionableChange) return;\n\n if (cliOptions.verbose) {\n console.log(`${event} ${cause}`);\n }\n\n walk(filenames).catch(err => {\n console.error(err);\n });\n });\n }\n }\n\n if (cliOptions.filenames.length) {\n await files(cliOptions.filenames);\n } else {\n await stdin();\n }\n}\n"],"mappings":";;;;;;AAAA,SAAAA,kBAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,iBAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,cAAA;EAAA,MAAAF,IAAA,GAAAC,OAAA;EAAAC,aAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAG,OAAA;EAAA,MAAAH,IAAA,GAAAC,OAAA;EAAAE,MAAA,YAAAA,CAAA;IAAA,OAAAH,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAI,MAAA;EAAA,MAAAJ,IAAA,GAAAC,OAAA;EAAAG,KAAA,YAAAA,CAAA;IAAA,OAAAJ,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAK,IAAA;EAAA,MAAAL,IAAA,GAAAC,OAAA;EAAAI,GAAA,YAAAA,CAAA;IAAA,OAAAL,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,IAAAM,IAAA,GAAAL,OAAA;AAEA,IAAAM,OAAA,GAAAN,OAAA;AAAwC,SAAAO,mBAAAC,GAAA,EAAAC,OAAA,EAAAC,MAAA,EAAAC,KAAA,EAAAC,MAAA,EAAAC,GAAA,EAAAC,GAAA,cAAAC,IAAA,GAAAP,GAAA,CAAAK,GAAA,EAAAC,GAAA,OAAAE,KAAA,GAAAD,IAAA,CAAAC,KAAA,WAAAC,KAAA,IAAAP,MAAA,CAAAO,KAAA,iBAAAF,IAAA,CAAAG,IAAA,IAAAT,OAAA,CAAAO,KAAA,YAAAG,OAAA,CAAAV,OAAA,CAAAO,KAAA,EAAAI,IAAA,CAAAT,KAAA,EAAAC,MAAA;AAAA,SAAAS,kBAAAC,EAAA,6BAAAC,IAAA,SAAAC,IAAA,GAAAC,SAAA,aAAAN,OAAA,WAAAV,OAAA,EAAAC,MAAA,QAAAF,GAAA,GAAAc,EAAA,CAAAI,KAAA,CAAAH,IAAA,EAAAC,IAAA,YAAAb,MAAAK,KAAA,IAAAT,kBAAA,CAAAC,GAAA,EAAAC,OAAA,EAAAC,MAAA,EAAAC,KAAA,EAAAC,MAAA,UAAAI,KAAA,cAAAJ,OAAAe,GAAA,IAAApB,kBAAA,CAAAC,GAAA,EAAAC,OAAA,EAAAC,MAAA,EAAAC,KAAA,EAAAC,MAAA,WAAAe,GAAA,KAAAhB,KAAA,CAAAiB,SAAA;AAAA,SAAAC,SAAAC,EAAA;EAAA,OAAAC,IAAA,CAAAL,KAAA,OAAAD,SAAA;AAAA;AAAA,SAAAM,KAAA;EAAAA,IAAA,GAAAV,iBAAA,CAgBzB,WAAgB;IAC7BW,UAAU;IACVC;EACU,CAAC,EAAiB;IAC5B,SAASC,WAAWA,CAACC,WAA8B,EAAqB;MACtE,MAAMC,WAA2C,GAAG,EAAE;MAEtD,IAAIC,IAAI,GAAG,EAAE;MACb,IAAIC,MAAM,GAAG,CAAC;MAEd,IAAIC,SAAS,GAAG,KAAK;MAErB,KAAK,MAAMC,MAAM,IAAIL,WAAW,EAAE;QAChC,IAAI,CAACK,MAAM,EAAE;QAEbD,SAAS,GAAG,CAAC,CAACC,MAAM,CAACC,GAAG;QAExBL,WAAW,CAACM,IAAI,CAAC;UACfJ,MAAM,EAAE;YAAEK,IAAI,EAAEL,MAAM;YAAEM,MAAM,EAAE;UAAE,CAAC;UACnCH,GAAG,EAAGD,MAAM,CAACC,GAAG,IAAyB;YACvCI,OAAO,EAAE,CAAC;YACVC,KAAK,EAAE,EAAE;YACTC,OAAO,EAAE,EAAE;YACXC,QAAQ,EAAE;UACZ;QACF,CAAC,CAAC;QAEFX,IAAI,IAAIG,MAAM,CAACH,IAAI,GAAG,IAAI;QAC1BC,MAAM,IAAIW,aAAa,CAACT,MAAM,CAACH,IAAI,CAAC,GAAG,CAAC;MAC1C;MAEA,MAAMI,GAAG,GAAG,KAAIS,sBAAM,EAAC;QACrBL,OAAO,EAAE,CAAC;QACVM,IAAI,EACFnB,UAAU,CAACoB,eAAe,IAC1BC,MAAGA,CAAC,CAACC,QAAQ,CAACtB,UAAU,CAACuB,OAAO,IAAI,EAAE,CAAC,IACvC,QAAQ;QACVC,QAAQ,EAAEpB;MACZ,CAAC,CAAC;MAIFK,GAAG,CAACgB,UAAU,GAAGxB,YAAY,CAACwB,UAAU;MAIxC,IACExB,YAAY,CAACyB,UAAU,KAAK,QAAQ,IACnC,CAAC1B,UAAU,CAACuB,OAAO,IAAItB,YAAY,CAACyB,UAAW,EAChD;QACArB,IAAI,IAAI,IAAI,GAAGsB,kBAAeA,CAAC,CAACC,UAAU,CAAC,IAAAC,0BAAU,EAACpB,GAAG,CAAC,CAAC,CAACqB,SAAS,CAAC,CAAC;MACzE;MAEA,OAAO;QACLrB,GAAG,EAAEA,GAAG;QACRJ,IAAI,EAAEA,IAAI;QACVE,SAAS,EAAEA;MACb,CAAC;IACH;IAEA,SAASU,aAAaA,CAACZ,IAAY,EAAU;MAC3C,IAAI0B,KAAK,GAAG,CAAC;MACb,IAAIC,KAAK,GAAG,CAAC,CAAC;MACd,OAAO,CAACA,KAAK,GAAG3B,IAAI,CAAC4B,OAAO,CAAC,IAAI,EAAED,KAAK,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE;QACrDD,KAAK,EAAE;MACT;MACA,OAAOA,KAAK;IACd;IAEA,SAASG,MAAMA,CAAC/B,WAA8B,EAAQ;MACpD,MAAMK,MAAM,GAAGN,WAAW,CAACC,WAAW,CAAC;MAEvC,IAAIH,UAAU,CAACuB,OAAO,EAAE;QACtB,GAAAY,CAAA,EAAAC,CAAA,MAAAD,CAAA,GAAAA,CAAA,CAAAE,KAAA,OAAAD,CAAA,GAAAA,CAAA,CAAAC,KAAA,QAAAF,CAAA,OAAAC,CAAA,OAAAD,CAAA,OAAAC,CAAA,QAAAD,CAAA,QAAAC,CAAA,MAAAE,OAAA,CAAAC,QAAA,CAAAC,IAAA,aAAApE,GAAA,GAAAqE,SAAA,GAAAzE,OAAA,aAAA0E,IAAA,EAAarB,MAAGA,CAAC,CAACsB,OAAO,CAAC3C,UAAU,CAACuB,OAAO,CAAC,EAAE;UAAEqB,SAAS,EAAE;QAAK,CAAC,CAAC;QAEnE,IAAIC,SAAsC,GAAG,KAAK;QAClD,IAAI5C,YAAY,CAACyB,UAAU,IAAIzB,YAAY,CAACyB,UAAU,KAAK,QAAQ,EAAE;UACnEmB,SAAS,GAAG,UAAU;QACxB,CAAC,MAAM,IAAI5C,YAAY,CAACyB,UAAU,IAAI9B,SAAS,IAAIY,MAAM,CAACD,SAAS,EAAE;UACnEsC,SAAS,GAAGxE,IAAI,CAACyE,gBAAgB,CAACtC,MAAM,CAACH,IAAI,CAAC,GAAG,UAAU,GAAG,MAAM;QACtE;QAEA,IAAIwC,SAAS,EAAE;UACb,MAAME,MAAM,GAAG/C,UAAU,CAACuB,OAAO,GAAG,MAAM;UAC1C,IAAIsB,SAAS,KAAK,UAAU,EAAE;YAC5BrC,MAAM,CAACH,IAAI,GAAGhC,IAAI,CAAC2E,mBAAmB,CAACxC,MAAM,CAACH,IAAI,EAAE0C,MAAM,CAAC;UAC7D;UACAE,IAACA,CAAC,CAACC,aAAa,CACdH,MAAM,EACNI,IAAI,CAACC,SAAS,CAAC,IAAAvB,0BAAU,EAACrB,MAAM,CAACC,GAAe,CAAC,CACnD,CAAC;QACH;QAEAwC,IAACA,CAAC,CAACC,aAAa,CAAClD,UAAU,CAACuB,OAAO,EAAEf,MAAM,CAACH,IAAI,CAAC;MACnD,CAAC,MAAM;QACLiC,OAAO,CAACe,MAAM,CAACC,KAAK,CAAC9C,MAAM,CAACH,IAAI,GAAG,IAAI,CAAC;MAC1C;IACF;IAEA,SAASkD,SAASA,CAAA,EAAoB;MACpC,OAAO,IAAIpE,OAAO,CAAC,CAACV,OAAO,EAAEC,MAAM,KAAW;QAC5C,IAAI2B,IAAI,GAAG,EAAE;QAEbiC,OAAO,CAACkB,KAAK,CAACC,WAAW,CAAC,MAAM,CAAC;QAEjCnB,OAAO,CAACkB,KAAK,CAACE,EAAE,CAAC,UAAU,EAAE,YAAY;UACvC,MAAMC,KAAK,GAAGrB,OAAO,CAACkB,KAAK,CAACI,IAAI,CAAC,CAAC;UAClC,IAAID,KAAK,KAAK,IAAI,EAAEtD,IAAI,IAAIsD,KAAK;QACnC,CAAC,CAAC;QAEFrB,OAAO,CAACkB,KAAK,CAACE,EAAE,CAAC,KAAK,EAAE,YAAY;UAClCjF,OAAO,CAAC4B,IAAI,CAAC;QACf,CAAC,CAAC;QACFiC,OAAO,CAACkB,KAAK,CAACE,EAAE,CAAC,OAAO,EAAEhF,MAAM,CAAC;MACnC,CAAC,CAAC;IACJ;IAAC,SAEc8E,KAAKA,CAAA;MAAA,OAAAK,MAAA,CAAAnE,KAAA,OAAAD,SAAA;IAAA;IAAA,SAAAoE,OAAA;MAAAA,MAAA,GAAAxE,iBAAA,CAApB,aAAsC;QACpC,MAAMgB,IAAI,SAASkD,SAAS,CAAC,CAAC;QAE9B,MAAMO,GAAG,SAASzF,IAAI,CAAC0F,aAAa,CAAC/D,UAAU,CAACgE,QAAQ,EAAE3D,IAAI,EAAA4D,MAAA,CAAAC,MAAA,KACzDjE,YAAY;UACfkE,cAAc,EAAE;QAAO,EACxB,CAAC;QAEFjC,MAAM,CAAC,CAAC4B,GAAG,CAAC,CAAC;MACf,CAAC;MAAA,OAAAD,MAAA,CAAAnE,KAAA,OAAAD,SAAA;IAAA;IAAA,SAEc2E,IAAIA,CAAAC,GAAA;MAAA,OAAAC,KAAA,CAAA5E,KAAA,OAAAD,SAAA;IAAA;IAAA,SAAA6E,MAAA;MAAAA,KAAA,GAAAjF,iBAAA,CAAnB,WAAoBkF,SAAwB,EAAiB;QAC3D,MAAMC,UAAoB,GAAG,EAAE;QAE/BD,SAAS,CAACE,OAAO,CAAC,UAAUT,QAAQ,EAAE;UACpC,IAAI,CAACf,IAACA,CAAC,CAACyB,UAAU,CAACV,QAAQ,CAAC,EAAE;UAE9B,MAAMW,IAAI,GAAG1B,IAACA,CAAC,CAAC2B,QAAQ,CAACZ,QAAQ,CAAC;UAClC,IAAIW,IAAI,CAACE,WAAW,CAAC,CAAC,EAAE;YACtB,MAAMlC,OAAO,GAAGqB,QAAQ;YAExB3F,IAAI,CACDyG,oBAAoB,CACnBd,QAAQ,EACRhE,UAAU,CAAC+E,eAAe,EAC1B/E,UAAU,CAACgF,UACb,CAAC,CACAP,OAAO,CAAC,UAAUT,QAAQ,EAAE;cAC3BQ,UAAU,CAAC9D,IAAI,CAACW,MAAGA,CAAC,CAAC4D,IAAI,CAACtC,OAAO,EAAEqB,QAAQ,CAAC,CAAC;YAC/C,CAAC,CAAC;UACN,CAAC,MAAM;YACLQ,UAAU,CAAC9D,IAAI,CAACsD,QAAQ,CAAC;UAC3B;QACF,CAAC,CAAC;QAEF,MAAMkB,OAAO,SAAS/F,OAAO,CAACgG,GAAG,CAC/BX,UAAU,CAAC/D,GAAG,CAAApB,iBAAA,CAAC,WAAgB2E,QAAgB,EAAgB;UAC7D,IAAIoB,cAAc,GAAGpB,QAAQ;UAC7B,IAAIhE,UAAU,CAACuB,OAAO,EAAE;YACtB6D,cAAc,GAAG/D,MAAGA,CAAC,CAACgE,QAAQ,CAC5BhE,MAAGA,CAAC,CAACsB,OAAO,CAAC3C,UAAU,CAACuB,OAAO,CAAC,EAChC6D,cACF,CAAC;UACH;UACAA,cAAc,GAAGE,OAAIA,CAAC,CAACF,cAAc,CAAC;UAEtC,IAAI;YACF,aAAa/G,IAAI,CAACkH,OAAO,CAACvB,QAAQ,EAAAC,MAAA,CAAAC,MAAA,KAC7BjE,YAAY;cACfkE,cAAc,EAAEiB,cAAc;cAI9B1D,UAAU,EACRzB,YAAY,CAACyB,UAAU,KAAK,QAAQ,GAChC,IAAI,GACJzB,YAAY,CAACyB;YAAU,EAC9B,CAAC;UACJ,CAAC,CAAC,OAAO/B,GAAG,EAAE;YACZ,IAAI,CAACK,UAAU,CAACwF,KAAK,EAAE;cACrB,MAAM7F,GAAG;YACX;YAEA8F,OAAO,CAACxG,KAAK,CAACU,GAAG,CAAC;YAClB,OAAO,IAAI;UACb;QACF,CAAC,EACH,CAAC;QAEDuC,MAAM,CAACgD,OAAO,CAAC;MACjB,CAAC;MAAA,OAAAZ,KAAA,CAAA5E,KAAA,OAAAD,SAAA;IAAA;IAAA,SAEciG,KAAKA,CAAAC,GAAA;MAAA,OAAAC,MAAA,CAAAlG,KAAA,OAAAD,SAAA;IAAA;IAAA,SAAAmG,OAAA;MAAAA,MAAA,GAAAvG,iBAAA,CAApB,WAAqBkF,SAAwB,EAAiB;QAC5D,IAAIvE,UAAU,CAACwF,KAAK,EAAE;UACpBlH,OAAO,CAACuH,MAAM,CAAC;YAAEC,cAAc,EAAE;UAAM,CAAC,CAAC;QAC3C;QAEA,IAAI,CAAC9F,UAAU,CAAC+F,gBAAgB,EAAE;UAChC,MAAM3B,IAAI,CAACG,SAAS,CAAC;QACvB;QAEA,IAAIvE,UAAU,CAACwF,KAAK,EAAE;UACpBjB,SAAS,CAACE,OAAO,CAACnG,OAAO,CAACkH,KAAK,CAAC;UAEhClH,OAAO,CAAC0H,YAAY,CAAC,CAAC;UAEtB1H,OAAO,CAAC2H,aAAa,CAAC,CAACC,OAAO,EAAEC,KAAK,EAAEC,KAAK,KAAK;YAC/C,MAAMC,gBAAgB,GAAGH,OAAO,CAACI,IAAI,CACnCtC,QAAQ,IACN3F,IAAI,CAACkI,qBAAqB,CAACvC,QAAQ,EAAEhE,UAAU,CAACgF,UAAU,CAAC,IAC3DT,SAAS,CAACiC,QAAQ,CAACxC,QAAQ,CAC/B,CAAC;YACD,IAAI,CAACqC,gBAAgB,EAAE;YAEvB,IAAIrG,UAAU,CAACyG,OAAO,EAAE;cACtBhB,OAAO,CAACiB,GAAG,CAAE,GAAEP,KAAM,IAAGC,KAAM,EAAC,CAAC;YAClC;YAEAhC,IAAI,CAACG,SAAS,CAAC,CAACoC,KAAK,CAAChH,GAAG,IAAI;cAC3B8F,OAAO,CAACxG,KAAK,CAACU,GAAG,CAAC;YACpB,CAAC,CAAC;UACJ,CAAC,CAAC;QACJ;MACF,CAAC;MAAA,OAAAiG,MAAA,CAAAlG,KAAA,OAAAD,SAAA;IAAA;IAED,IAAIO,UAAU,CAACuE,SAAS,CAACqC,MAAM,EAAE;MAC/B,MAAMlB,KAAK,CAAC1F,UAAU,CAACuE,SAAS,CAAC;IACnC,CAAC,MAAM;MACL,MAAMf,KAAK,CAAC,CAAC;IACf;EACF,CAAC;EAAA,OAAAzD,IAAA,CAAAL,KAAA,OAAAD,SAAA;AAAA","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/cli/lib/babel/index.js b/node_modules/@babel/cli/lib/babel/index.js new file mode 100644 index 000000000..c66da0d00 --- /dev/null +++ b/node_modules/@babel/cli/lib/babel/index.js @@ -0,0 +1,18 @@ +#!/usr/bin/env node +"use strict"; + +var _options = require("./options.js"); +var _dir = require("./dir.js"); +var _file = require("./file.js"); +const opts = (0, _options.default)(process.argv); +if (opts) { + const fn = opts.cliOptions.outDir ? _dir.default : _file.default; + fn(opts).catch(err => { + console.error(err); + process.exitCode = 1; + }); +} else { + process.exitCode = 2; +} + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/cli/lib/babel/index.js.map b/node_modules/@babel/cli/lib/babel/index.js.map new file mode 100644 index 000000000..7e6f5a0a3 --- /dev/null +++ b/node_modules/@babel/cli/lib/babel/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_options","require","_dir","_file","opts","parseArgv","process","argv","fn","cliOptions","outDir","dirCommand","fileCommand","catch","err","console","error","exitCode"],"sources":["../../src/babel/index.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport parseArgv from \"./options.ts\";\nimport dirCommand from \"./dir.ts\";\nimport fileCommand from \"./file.ts\";\n\nconst opts = parseArgv(process.argv);\n\nif (opts) {\n const fn = opts.cliOptions.outDir ? dirCommand : fileCommand;\n fn(opts).catch(err => {\n console.error(err);\n process.exitCode = 1;\n });\n} else {\n process.exitCode = 2;\n}\n"],"mappings":"AAAA;AAAmB;;AAEnB,IAAAA,QAAA,GAAAC,OAAA;AACA,IAAAC,IAAA,GAAAD,OAAA;AACA,IAAAE,KAAA,GAAAF,OAAA;AAEA,MAAMG,IAAI,GAAG,IAAAC,gBAAS,EAACC,OAAO,CAACC,IAAI,CAAC;AAEpC,IAAIH,IAAI,EAAE;EACR,MAAMI,EAAE,GAAGJ,IAAI,CAACK,UAAU,CAACC,MAAM,GAAGC,YAAU,GAAGC,aAAW;EAC5DJ,EAAE,CAACJ,IAAI,CAAC,CAACS,KAAK,CAACC,GAAG,IAAI;IACpBC,OAAO,CAACC,KAAK,CAACF,GAAG,CAAC;IAClBR,OAAO,CAACW,QAAQ,GAAG,CAAC;EACtB,CAAC,CAAC;AACJ,CAAC,MAAM;EACLX,OAAO,CAACW,QAAQ,GAAG,CAAC;AACtB","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/cli/lib/babel/options.js b/node_modules/@babel/cli/lib/babel/options.js new file mode 100644 index 000000000..8c77f8ecb --- /dev/null +++ b/node_modules/@babel/cli/lib/babel/options.js @@ -0,0 +1,209 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = parseArgv; +function _fs() { + const data = require("fs"); + _fs = function () { + return data; + }; + return data; +} +function _commander() { + const data = require("commander"); + _commander = function () { + return data; + }; + return data; +} +function _core() { + const data = require("@babel/core"); + _core = function () { + return data; + }; + return data; +} +function _glob() { + const data = require("glob"); + _glob = function () { + return data; + }; + return data; +} +_commander().option("-f, --filename [filename]", "The filename to use when reading from stdin. This will be used in source-maps, errors etc."); +_commander().option("--presets [list]", "A comma-separated list of preset names.", collect); +_commander().option("--plugins [list]", "A comma-separated list of plugin names.", collect); +_commander().option("--config-file [path]", "Path to a .babelrc file to use."); +_commander().option("--env-name [name]", "The name of the 'env' to use when loading configs and plugins. " + "Defaults to the value of BABEL_ENV, or else NODE_ENV, or else 'development'."); +_commander().option("--root-mode [mode]", "The project-root resolution mode. " + "One of 'root' (the default), 'upward', or 'upward-optional'."); +_commander().option("--source-type [script|module]", ""); +_commander().option("--no-babelrc", "Whether or not to look up .babelrc and .babelignore files."); +_commander().option("--ignore [list]", "List of glob paths to **not** compile.", collect); +_commander().option("--only [list]", "List of glob paths to **only** compile.", collect); +_commander().option("--no-highlight-code", "Enable or disable ANSI syntax highlighting of code frames. (on by default)"); +_commander().option("--no-comments", "Write comments to generated output. (true by default)"); +_commander().option("--retain-lines", "Retain line numbers. This will result in really ugly code."); +_commander().option("--compact [true|false|auto]", "Do not include superfluous whitespace characters and line terminators.", booleanify); +_commander().option("--minified", "Save as many bytes when printing. (false by default)"); +_commander().option("--auxiliary-comment-before [string]", "Print a comment before any injected non-user code."); +_commander().option("--auxiliary-comment-after [string]", "Print a comment after any injected non-user code."); +_commander().option("-s, --source-maps [true|false|inline|both]", "", booleanify, undefined); +_commander().option("--source-map-target [string]", "Set `file` on returned source map."); +_commander().option("--source-file-name [string]", "Set `sources[0]` on returned source map."); +_commander().option("--source-root [filename]", "The root from which all sources are relative."); +{ + _commander().option("--module-root [filename]", "Optional prefix for the AMD module formatter that will be prepended to the filename on module definitions."); + _commander().option("-M, --module-ids", "Insert an explicit id for modules."); + _commander().option("--module-id [string]", "Specify a custom name for module ids."); +} +_commander().option("-x, --extensions [extensions]", "List of extensions to compile when a directory has been the input. [" + _core().DEFAULT_EXTENSIONS.join() + "]", collect); +_commander().option("--keep-file-extension", "Preserve the file extensions of the input files."); +_commander().option("-w, --watch", "Recompile files on changes."); +_commander().option("--skip-initial-build", "Do not compile files before watching."); +_commander().option("-o, --out-file [out]", "Compile all input files into a single file."); +_commander().option("-d, --out-dir [out]", "Compile an input directory of modules into an output directory."); +_commander().option("--relative", "Compile into an output directory relative to input directory or file. Requires --out-dir [out]"); +_commander().option("-D, --copy-files", "When compiling a directory copy over non-compilable files."); +_commander().option("--include-dotfiles", "Include dotfiles when compiling and copying non-compilable files."); +_commander().option("--no-copy-ignored", "Exclude ignored files when copying non-compilable files."); +_commander().option("--verbose", "Log everything. This option conflicts with --quiet"); +_commander().option("--quiet", "Don't log anything. This option conflicts with --verbose"); +_commander().option("--delete-dir-on-start", "Delete the out directory before compilation."); +_commander().option("--out-file-extension [string]", "Use a specific extension for the output files"); +_commander().version("7.24.1" + " (@babel/core " + _core().version + ")"); +_commander().usage("[options] "); +_commander().action(() => {}); +function parseArgv(args) { + _commander().parse(args); + const errors = []; + let filenames = _commander().args.reduce(function (globbed, input) { + let files = _glob().sync(input); + if (!files.length) files = [input]; + globbed.push(...files); + return globbed; + }, []); + filenames = Array.from(new Set(filenames)); + filenames.forEach(function (filename) { + if (!_fs().existsSync(filename)) { + errors.push(filename + " does not exist"); + } + }); + if (_commander().outDir && !filenames.length) { + errors.push("--out-dir requires filenames"); + } + if (_commander().outFile && _commander().outDir) { + errors.push("--out-file and --out-dir cannot be used together"); + } + if (_commander().relative && !_commander().outDir) { + errors.push("--relative requires --out-dir usage"); + } + if (_commander().watch) { + if (!_commander().outFile && !_commander().outDir) { + errors.push("--watch requires --out-file or --out-dir"); + } + if (!filenames.length) { + errors.push("--watch requires filenames"); + } + } + if (_commander().skipInitialBuild && !_commander().watch) { + errors.push("--skip-initial-build requires --watch"); + } + if (_commander().deleteDirOnStart && !_commander().outDir) { + errors.push("--delete-dir-on-start requires --out-dir"); + } + if (_commander().verbose && _commander().quiet) { + errors.push("--verbose and --quiet cannot be used together"); + } + if (!_commander().outDir && filenames.length === 0 && typeof _commander().filename !== "string" && _commander().babelrc !== false) { + errors.push("stdin compilation requires either -f/--filename [filename] or --no-babelrc"); + } + if (_commander().keepFileExtension && _commander().outFileExtension) { + errors.push("--out-file-extension cannot be used with --keep-file-extension"); + } + if (errors.length) { + console.error("babel:"); + errors.forEach(function (e) { + console.error(" " + e); + }); + return null; + } + const opts = _commander().opts(); + const babelOptions = { + presets: opts.presets, + plugins: opts.plugins, + rootMode: opts.rootMode, + configFile: opts.configFile, + envName: opts.envName, + sourceType: opts.sourceType, + ignore: opts.ignore, + only: opts.only, + retainLines: opts.retainLines, + compact: opts.compact, + minified: opts.minified, + auxiliaryCommentBefore: opts.auxiliaryCommentBefore, + auxiliaryCommentAfter: opts.auxiliaryCommentAfter, + sourceMaps: opts.sourceMaps, + sourceFileName: opts.sourceFileName, + sourceRoot: opts.sourceRoot, + babelrc: opts.babelrc === true ? undefined : opts.babelrc, + highlightCode: opts.highlightCode === true ? undefined : opts.highlightCode, + comments: opts.comments === true ? undefined : opts.comments + }; + { + Object.assign(babelOptions, { + moduleRoot: opts.moduleRoot, + moduleIds: opts.moduleIds, + moduleId: opts.moduleId + }); + } + for (const key of Object.keys(babelOptions)) { + if (babelOptions[key] === undefined) { + delete babelOptions[key]; + } + } + return { + babelOptions, + cliOptions: { + filename: opts.filename, + filenames, + extensions: opts.extensions, + keepFileExtension: opts.keepFileExtension, + outFileExtension: opts.outFileExtension, + watch: opts.watch, + skipInitialBuild: opts.skipInitialBuild, + outFile: opts.outFile, + outDir: opts.outDir, + relative: opts.relative, + copyFiles: opts.copyFiles, + copyIgnored: opts.copyFiles && opts.copyIgnored, + includeDotfiles: opts.includeDotfiles, + verbose: opts.verbose, + quiet: opts.quiet, + deleteDirOnStart: opts.deleteDirOnStart, + sourceMapTarget: opts.sourceMapTarget + } + }; +} +function booleanify(val) { + if (val === undefined) return undefined; + if (val === "true" || val == 1) { + return true; + } + if (val === "false" || val == 0 || !val) { + return false; + } + return val; +} +function collect(value, previousValue) { + if (typeof value !== "string") return previousValue; + const values = value.split(","); + if (previousValue) { + previousValue.push(...values); + return previousValue; + } + return values; +} + +//# sourceMappingURL=options.js.map diff --git a/node_modules/@babel/cli/lib/babel/options.js.map b/node_modules/@babel/cli/lib/babel/options.js.map new file mode 100644 index 000000000..d57af8e7f --- /dev/null +++ b/node_modules/@babel/cli/lib/babel/options.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_fs","data","require","_commander","_core","_glob","commander","option","collect","booleanify","undefined","DEFAULT_EXTENSIONS","join","version","usage","action","parseArgv","args","parse","errors","filenames","reduce","globbed","input","files","glob","sync","length","push","Array","from","Set","forEach","filename","fs","existsSync","outDir","outFile","relative","watch","skipInitialBuild","deleteDirOnStart","verbose","quiet","babelrc","keepFileExtension","outFileExtension","console","error","e","opts","babelOptions","presets","plugins","rootMode","configFile","envName","sourceType","ignore","only","retainLines","compact","minified","auxiliaryCommentBefore","auxiliaryCommentAfter","sourceMaps","sourceFileName","sourceRoot","highlightCode","comments","Object","assign","moduleRoot","moduleIds","moduleId","key","keys","cliOptions","extensions","copyFiles","copyIgnored","includeDotfiles","sourceMapTarget","val","value","previousValue","values","split"],"sources":["../../src/babel/options.ts"],"sourcesContent":["import fs from \"fs\";\n\nimport commander from \"commander\";\nimport { version, DEFAULT_EXTENSIONS } from \"@babel/core\";\nimport glob from \"glob\";\n\nimport type { InputOptions } from \"@babel/core\";\n\n// Standard Babel input configs.\ncommander.option(\n \"-f, --filename [filename]\",\n \"The filename to use when reading from stdin. This will be used in source-maps, errors etc.\",\n);\ncommander.option(\n \"--presets [list]\",\n \"A comma-separated list of preset names.\",\n collect,\n);\ncommander.option(\n \"--plugins [list]\",\n \"A comma-separated list of plugin names.\",\n collect,\n);\ncommander.option(\"--config-file [path]\", \"Path to a .babelrc file to use.\");\ncommander.option(\n \"--env-name [name]\",\n \"The name of the 'env' to use when loading configs and plugins. \" +\n \"Defaults to the value of BABEL_ENV, or else NODE_ENV, or else 'development'.\",\n);\ncommander.option(\n \"--root-mode [mode]\",\n \"The project-root resolution mode. \" +\n \"One of 'root' (the default), 'upward', or 'upward-optional'.\",\n);\n\n// Basic file input configuration.\ncommander.option(\"--source-type [script|module]\", \"\");\ncommander.option(\n \"--no-babelrc\",\n \"Whether or not to look up .babelrc and .babelignore files.\",\n);\ncommander.option(\n \"--ignore [list]\",\n \"List of glob paths to **not** compile.\",\n collect,\n);\ncommander.option(\n \"--only [list]\",\n \"List of glob paths to **only** compile.\",\n collect,\n);\n\n// Misc babel config.\ncommander.option(\n \"--no-highlight-code\",\n \"Enable or disable ANSI syntax highlighting of code frames. (on by default)\",\n);\n\n// General output formatting.\ncommander.option(\n \"--no-comments\",\n \"Write comments to generated output. (true by default)\",\n);\ncommander.option(\n \"--retain-lines\",\n \"Retain line numbers. This will result in really ugly code.\",\n);\ncommander.option(\n \"--compact [true|false|auto]\",\n \"Do not include superfluous whitespace characters and line terminators.\",\n booleanify,\n);\ncommander.option(\n \"--minified\",\n \"Save as many bytes when printing. (false by default)\",\n);\ncommander.option(\n \"--auxiliary-comment-before [string]\",\n \"Print a comment before any injected non-user code.\",\n);\ncommander.option(\n \"--auxiliary-comment-after [string]\",\n \"Print a comment after any injected non-user code.\",\n);\n\n// General source map formatting.\ncommander.option(\n \"-s, --source-maps [true|false|inline|both]\",\n \"\",\n booleanify,\n undefined,\n);\ncommander.option(\n \"--source-map-target [string]\",\n \"Set `file` on returned source map.\",\n);\ncommander.option(\n \"--source-file-name [string]\",\n \"Set `sources[0]` on returned source map.\",\n);\ncommander.option(\n \"--source-root [filename]\",\n \"The root from which all sources are relative.\",\n);\n\nif (!process.env.BABEL_8_BREAKING) {\n // Config params for certain module output formats.\n commander.option(\n \"--module-root [filename]\",\n \"Optional prefix for the AMD module formatter that will be prepended to the filename on module definitions.\",\n );\n commander.option(\"-M, --module-ids\", \"Insert an explicit id for modules.\");\n commander.option(\n \"--module-id [string]\",\n \"Specify a custom name for module ids.\",\n );\n}\n\n// \"babel\" command specific arguments that are not passed to @babel/core.\ncommander.option(\n \"-x, --extensions [extensions]\",\n \"List of extensions to compile when a directory has been the input. [\" +\n DEFAULT_EXTENSIONS.join() +\n \"]\",\n collect,\n);\ncommander.option(\n \"--keep-file-extension\",\n \"Preserve the file extensions of the input files.\",\n);\ncommander.option(\"-w, --watch\", \"Recompile files on changes.\");\ncommander.option(\n \"--skip-initial-build\",\n \"Do not compile files before watching.\",\n);\ncommander.option(\n \"-o, --out-file [out]\",\n \"Compile all input files into a single file.\",\n);\ncommander.option(\n \"-d, --out-dir [out]\",\n \"Compile an input directory of modules into an output directory.\",\n);\ncommander.option(\n \"--relative\",\n \"Compile into an output directory relative to input directory or file. Requires --out-dir [out]\",\n);\n\ncommander.option(\n \"-D, --copy-files\",\n \"When compiling a directory copy over non-compilable files.\",\n);\ncommander.option(\n \"--include-dotfiles\",\n \"Include dotfiles when compiling and copying non-compilable files.\",\n);\ncommander.option(\n \"--no-copy-ignored\",\n \"Exclude ignored files when copying non-compilable files.\",\n);\n\ncommander.option(\n \"--verbose\",\n \"Log everything. This option conflicts with --quiet\",\n);\ncommander.option(\n \"--quiet\",\n \"Don't log anything. This option conflicts with --verbose\",\n);\ncommander.option(\n \"--delete-dir-on-start\",\n \"Delete the out directory before compilation.\",\n);\ncommander.option(\n \"--out-file-extension [string]\",\n \"Use a specific extension for the output files\",\n);\n\ncommander.version(PACKAGE_JSON.version + \" (@babel/core \" + version + \")\");\ncommander.usage(\"[options] \");\n// register an empty action handler so that commander.js can throw on\n// unknown options _after_ args\n// see https://github.com/tj/commander.js/issues/561#issuecomment-522209408\ncommander.action(() => {});\n\nexport type CmdOptions = {\n babelOptions: InputOptions;\n cliOptions: {\n filename: string;\n filenames: string[];\n extensions: string[];\n keepFileExtension: boolean;\n outFileExtension: string;\n watch: boolean;\n skipInitialBuild: boolean;\n outFile: string;\n outDir: string;\n relative: boolean;\n copyFiles: boolean;\n copyIgnored: boolean;\n includeDotfiles: boolean;\n verbose: boolean;\n quiet: boolean;\n deleteDirOnStart: boolean;\n sourceMapTarget: string;\n };\n};\n\nexport default function parseArgv(args: Array): CmdOptions | null {\n //\n commander.parse(args);\n\n const errors: string[] = [];\n\n let filenames = commander.args.reduce(function (globbed: string[], input) {\n let files = glob.sync(input);\n if (!files.length) files = [input];\n globbed.push(...files);\n return globbed;\n }, []);\n\n filenames = Array.from(new Set(filenames));\n\n filenames.forEach(function (filename) {\n if (!fs.existsSync(filename)) {\n errors.push(filename + \" does not exist\");\n }\n });\n\n if (commander.outDir && !filenames.length) {\n errors.push(\"--out-dir requires filenames\");\n }\n\n if (commander.outFile && commander.outDir) {\n errors.push(\"--out-file and --out-dir cannot be used together\");\n }\n\n if (commander.relative && !commander.outDir) {\n errors.push(\"--relative requires --out-dir usage\");\n }\n\n if (commander.watch) {\n if (!commander.outFile && !commander.outDir) {\n errors.push(\"--watch requires --out-file or --out-dir\");\n }\n\n if (!filenames.length) {\n errors.push(\"--watch requires filenames\");\n }\n }\n\n if (commander.skipInitialBuild && !commander.watch) {\n errors.push(\"--skip-initial-build requires --watch\");\n }\n if (commander.deleteDirOnStart && !commander.outDir) {\n errors.push(\"--delete-dir-on-start requires --out-dir\");\n }\n\n if (commander.verbose && commander.quiet) {\n errors.push(\"--verbose and --quiet cannot be used together\");\n }\n\n if (\n !commander.outDir &&\n filenames.length === 0 &&\n typeof commander.filename !== \"string\" &&\n commander.babelrc !== false\n ) {\n errors.push(\n \"stdin compilation requires either -f/--filename [filename] or --no-babelrc\",\n );\n }\n\n if (commander.keepFileExtension && commander.outFileExtension) {\n errors.push(\n \"--out-file-extension cannot be used with --keep-file-extension\",\n );\n }\n\n if (errors.length) {\n console.error(\"babel:\");\n errors.forEach(function (e) {\n console.error(\" \" + e);\n });\n return null;\n }\n\n const opts = commander.opts();\n\n const babelOptions: InputOptions = {\n presets: opts.presets,\n plugins: opts.plugins,\n rootMode: opts.rootMode,\n configFile: opts.configFile,\n envName: opts.envName,\n sourceType: opts.sourceType,\n ignore: opts.ignore,\n only: opts.only,\n retainLines: opts.retainLines,\n compact: opts.compact,\n minified: opts.minified,\n auxiliaryCommentBefore: opts.auxiliaryCommentBefore,\n auxiliaryCommentAfter: opts.auxiliaryCommentAfter,\n sourceMaps: opts.sourceMaps,\n sourceFileName: opts.sourceFileName,\n sourceRoot: opts.sourceRoot,\n\n // Commander will default the \"--no-\" arguments to true, but we want to\n // leave them undefined so that @babel/core can handle the\n // default-assignment logic on its own.\n babelrc: opts.babelrc === true ? undefined : opts.babelrc,\n highlightCode: opts.highlightCode === true ? undefined : opts.highlightCode,\n comments: opts.comments === true ? undefined : opts.comments,\n };\n\n if (!process.env.BABEL_8_BREAKING) {\n Object.assign(babelOptions, {\n moduleRoot: opts.moduleRoot,\n moduleIds: opts.moduleIds,\n moduleId: opts.moduleId,\n });\n }\n\n // If the @babel/cli version is newer than the @babel/core version, and we have added\n // new options for @babel/core, we'll potentially get option validation errors from\n // @babel/core. To avoid that, we delete undefined options, so @babel/core will only\n // give the error if users actually pass an unsupported CLI option.\n for (const key of Object.keys(babelOptions) as Array<\n keyof typeof babelOptions\n >) {\n if (babelOptions[key] === undefined) {\n delete babelOptions[key];\n }\n }\n\n return {\n babelOptions,\n cliOptions: {\n filename: opts.filename,\n filenames,\n extensions: opts.extensions,\n keepFileExtension: opts.keepFileExtension,\n outFileExtension: opts.outFileExtension,\n watch: opts.watch,\n skipInitialBuild: opts.skipInitialBuild,\n outFile: opts.outFile,\n outDir: opts.outDir,\n relative: opts.relative,\n copyFiles: opts.copyFiles,\n copyIgnored: opts.copyFiles && opts.copyIgnored,\n includeDotfiles: opts.includeDotfiles,\n verbose: opts.verbose,\n quiet: opts.quiet,\n deleteDirOnStart: opts.deleteDirOnStart,\n sourceMapTarget: opts.sourceMapTarget,\n },\n };\n}\n\nfunction booleanify(val: \"false\" | 0 | \"\"): false;\nfunction booleanify(val: \"true\" | 1): true;\nfunction booleanify(val: any): any {\n if (val === undefined) return undefined;\n\n if (val === \"true\" || val == 1) {\n return true;\n }\n\n if (val === \"false\" || val == 0 || !val) {\n return false;\n }\n\n return val;\n}\n\nfunction collect(value: unknown, previousValue: Array): Array {\n // If the user passed the option with no value, like \"babel file.js --presets\", do nothing.\n if (typeof value !== \"string\") return previousValue;\n\n const values = value.split(\",\");\n\n if (previousValue) {\n previousValue.push(...values);\n return previousValue;\n }\n return values;\n}\n"],"mappings":";;;;;;AAAA,SAAAA,IAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,GAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,SAAAE,WAAA;EAAA,MAAAF,IAAA,GAAAC,OAAA;EAAAC,UAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAG,MAAA;EAAA,MAAAH,IAAA,GAAAC,OAAA;EAAAE,KAAA,YAAAA,CAAA;IAAA,OAAAH,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAI,MAAA;EAAA,MAAAJ,IAAA,GAAAC,OAAA;EAAAG,KAAA,YAAAA,CAAA;IAAA,OAAAJ,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAKAK,WAAQA,CAAC,CAACC,MAAM,CACd,2BAA2B,EAC3B,4FACF,CAAC;AACDD,WAAQA,CAAC,CAACC,MAAM,CACd,kBAAkB,EAClB,yCAAyC,EACzCC,OACF,CAAC;AACDF,WAAQA,CAAC,CAACC,MAAM,CACd,kBAAkB,EAClB,yCAAyC,EACzCC,OACF,CAAC;AACDF,WAAQA,CAAC,CAACC,MAAM,CAAC,sBAAsB,EAAE,iCAAiC,CAAC;AAC3ED,WAAQA,CAAC,CAACC,MAAM,CACd,mBAAmB,EACnB,iEAAiE,GAC/D,8EACJ,CAAC;AACDD,WAAQA,CAAC,CAACC,MAAM,CACd,oBAAoB,EACpB,oCAAoC,GAClC,8DACJ,CAAC;AAGDD,WAAQA,CAAC,CAACC,MAAM,CAAC,+BAA+B,EAAE,EAAE,CAAC;AACrDD,WAAQA,CAAC,CAACC,MAAM,CACd,cAAc,EACd,4DACF,CAAC;AACDD,WAAQA,CAAC,CAACC,MAAM,CACd,iBAAiB,EACjB,wCAAwC,EACxCC,OACF,CAAC;AACDF,WAAQA,CAAC,CAACC,MAAM,CACd,eAAe,EACf,yCAAyC,EACzCC,OACF,CAAC;AAGDF,WAAQA,CAAC,CAACC,MAAM,CACd,qBAAqB,EACrB,4EACF,CAAC;AAGDD,WAAQA,CAAC,CAACC,MAAM,CACd,eAAe,EACf,uDACF,CAAC;AACDD,WAAQA,CAAC,CAACC,MAAM,CACd,gBAAgB,EAChB,4DACF,CAAC;AACDD,WAAQA,CAAC,CAACC,MAAM,CACd,6BAA6B,EAC7B,wEAAwE,EACxEE,UACF,CAAC;AACDH,WAAQA,CAAC,CAACC,MAAM,CACd,YAAY,EACZ,sDACF,CAAC;AACDD,WAAQA,CAAC,CAACC,MAAM,CACd,qCAAqC,EACrC,oDACF,CAAC;AACDD,WAAQA,CAAC,CAACC,MAAM,CACd,oCAAoC,EACpC,mDACF,CAAC;AAGDD,WAAQA,CAAC,CAACC,MAAM,CACd,4CAA4C,EAC5C,EAAE,EACFE,UAAU,EACVC,SACF,CAAC;AACDJ,WAAQA,CAAC,CAACC,MAAM,CACd,8BAA8B,EAC9B,oCACF,CAAC;AACDD,WAAQA,CAAC,CAACC,MAAM,CACd,6BAA6B,EAC7B,0CACF,CAAC;AACDD,WAAQA,CAAC,CAACC,MAAM,CACd,0BAA0B,EAC1B,+CACF,CAAC;AAEkC;EAEjCD,WAAQA,CAAC,CAACC,MAAM,CACd,0BAA0B,EAC1B,4GACF,CAAC;EACDD,WAAQA,CAAC,CAACC,MAAM,CAAC,kBAAkB,EAAE,oCAAoC,CAAC;EAC1ED,WAAQA,CAAC,CAACC,MAAM,CACd,sBAAsB,EACtB,uCACF,CAAC;AACH;AAGAD,WAAQA,CAAC,CAACC,MAAM,CACd,+BAA+B,EAC/B,sEAAsE,GACpEI,0BAAkB,CAACC,IAAI,CAAC,CAAC,GACzB,GAAG,EACLJ,OACF,CAAC;AACDF,WAAQA,CAAC,CAACC,MAAM,CACd,uBAAuB,EACvB,kDACF,CAAC;AACDD,WAAQA,CAAC,CAACC,MAAM,CAAC,aAAa,EAAE,6BAA6B,CAAC;AAC9DD,WAAQA,CAAC,CAACC,MAAM,CACd,sBAAsB,EACtB,uCACF,CAAC;AACDD,WAAQA,CAAC,CAACC,MAAM,CACd,sBAAsB,EACtB,6CACF,CAAC;AACDD,WAAQA,CAAC,CAACC,MAAM,CACd,qBAAqB,EACrB,iEACF,CAAC;AACDD,WAAQA,CAAC,CAACC,MAAM,CACd,YAAY,EACZ,gGACF,CAAC;AAEDD,WAAQA,CAAC,CAACC,MAAM,CACd,kBAAkB,EAClB,4DACF,CAAC;AACDD,WAAQA,CAAC,CAACC,MAAM,CACd,oBAAoB,EACpB,mEACF,CAAC;AACDD,WAAQA,CAAC,CAACC,MAAM,CACd,mBAAmB,EACnB,0DACF,CAAC;AAEDD,WAAQA,CAAC,CAACC,MAAM,CACd,WAAW,EACX,oDACF,CAAC;AACDD,WAAQA,CAAC,CAACC,MAAM,CACd,SAAS,EACT,0DACF,CAAC;AACDD,WAAQA,CAAC,CAACC,MAAM,CACd,uBAAuB,EACvB,8CACF,CAAC;AACDD,WAAQA,CAAC,CAACC,MAAM,CACd,+BAA+B,EAC/B,+CACF,CAAC;AAEDD,WAAQA,CAAC,CAACO,OAAO,CAAC,WAAuB,gBAAgB,GAAGA,eAAO,GAAG,GAAG,CAAC;AAC1EP,WAAQA,CAAC,CAACQ,KAAK,CAAC,uBAAuB,CAAC;AAIxCR,WAAQA,CAAC,CAACS,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;AAyBX,SAASC,SAASA,CAACC,IAAmB,EAAqB;EAExEX,WAAQA,CAAC,CAACY,KAAK,CAACD,IAAI,CAAC;EAErB,MAAME,MAAgB,GAAG,EAAE;EAE3B,IAAIC,SAAS,GAAGd,WAAQA,CAAC,CAACW,IAAI,CAACI,MAAM,CAAC,UAAUC,OAAiB,EAAEC,KAAK,EAAE;IACxE,IAAIC,KAAK,GAAGC,MAAGA,CAAC,CAACC,IAAI,CAACH,KAAK,CAAC;IAC5B,IAAI,CAACC,KAAK,CAACG,MAAM,EAAEH,KAAK,GAAG,CAACD,KAAK,CAAC;IAClCD,OAAO,CAACM,IAAI,CAAC,GAAGJ,KAAK,CAAC;IACtB,OAAOF,OAAO;EAChB,CAAC,EAAE,EAAE,CAAC;EAENF,SAAS,GAAGS,KAAK,CAACC,IAAI,CAAC,IAAIC,GAAG,CAACX,SAAS,CAAC,CAAC;EAE1CA,SAAS,CAACY,OAAO,CAAC,UAAUC,QAAQ,EAAE;IACpC,IAAI,CAACC,IAACA,CAAC,CAACC,UAAU,CAACF,QAAQ,CAAC,EAAE;MAC5Bd,MAAM,CAACS,IAAI,CAACK,QAAQ,GAAG,iBAAiB,CAAC;IAC3C;EACF,CAAC,CAAC;EAEF,IAAI3B,WAAQA,CAAC,CAAC8B,MAAM,IAAI,CAAChB,SAAS,CAACO,MAAM,EAAE;IACzCR,MAAM,CAACS,IAAI,CAAC,8BAA8B,CAAC;EAC7C;EAEA,IAAItB,WAAQA,CAAC,CAAC+B,OAAO,IAAI/B,WAAQA,CAAC,CAAC8B,MAAM,EAAE;IACzCjB,MAAM,CAACS,IAAI,CAAC,kDAAkD,CAAC;EACjE;EAEA,IAAItB,WAAQA,CAAC,CAACgC,QAAQ,IAAI,CAAChC,WAAQA,CAAC,CAAC8B,MAAM,EAAE;IAC3CjB,MAAM,CAACS,IAAI,CAAC,qCAAqC,CAAC;EACpD;EAEA,IAAItB,WAAQA,CAAC,CAACiC,KAAK,EAAE;IACnB,IAAI,CAACjC,WAAQA,CAAC,CAAC+B,OAAO,IAAI,CAAC/B,WAAQA,CAAC,CAAC8B,MAAM,EAAE;MAC3CjB,MAAM,CAACS,IAAI,CAAC,0CAA0C,CAAC;IACzD;IAEA,IAAI,CAACR,SAAS,CAACO,MAAM,EAAE;MACrBR,MAAM,CAACS,IAAI,CAAC,4BAA4B,CAAC;IAC3C;EACF;EAEA,IAAItB,WAAQA,CAAC,CAACkC,gBAAgB,IAAI,CAAClC,WAAQA,CAAC,CAACiC,KAAK,EAAE;IAClDpB,MAAM,CAACS,IAAI,CAAC,uCAAuC,CAAC;EACtD;EACA,IAAItB,WAAQA,CAAC,CAACmC,gBAAgB,IAAI,CAACnC,WAAQA,CAAC,CAAC8B,MAAM,EAAE;IACnDjB,MAAM,CAACS,IAAI,CAAC,0CAA0C,CAAC;EACzD;EAEA,IAAItB,WAAQA,CAAC,CAACoC,OAAO,IAAIpC,WAAQA,CAAC,CAACqC,KAAK,EAAE;IACxCxB,MAAM,CAACS,IAAI,CAAC,+CAA+C,CAAC;EAC9D;EAEA,IACE,CAACtB,WAAQA,CAAC,CAAC8B,MAAM,IACjBhB,SAAS,CAACO,MAAM,KAAK,CAAC,IACtB,OAAOrB,WAAQA,CAAC,CAAC2B,QAAQ,KAAK,QAAQ,IACtC3B,WAAQA,CAAC,CAACsC,OAAO,KAAK,KAAK,EAC3B;IACAzB,MAAM,CAACS,IAAI,CACT,4EACF,CAAC;EACH;EAEA,IAAItB,WAAQA,CAAC,CAACuC,iBAAiB,IAAIvC,WAAQA,CAAC,CAACwC,gBAAgB,EAAE;IAC7D3B,MAAM,CAACS,IAAI,CACT,gEACF,CAAC;EACH;EAEA,IAAIT,MAAM,CAACQ,MAAM,EAAE;IACjBoB,OAAO,CAACC,KAAK,CAAC,QAAQ,CAAC;IACvB7B,MAAM,CAACa,OAAO,CAAC,UAAUiB,CAAC,EAAE;MAC1BF,OAAO,CAACC,KAAK,CAAC,IAAI,GAAGC,CAAC,CAAC;IACzB,CAAC,CAAC;IACF,OAAO,IAAI;EACb;EAEA,MAAMC,IAAI,GAAG5C,WAAQA,CAAC,CAAC4C,IAAI,CAAC,CAAC;EAE7B,MAAMC,YAA0B,GAAG;IACjCC,OAAO,EAAEF,IAAI,CAACE,OAAO;IACrBC,OAAO,EAAEH,IAAI,CAACG,OAAO;IACrBC,QAAQ,EAAEJ,IAAI,CAACI,QAAQ;IACvBC,UAAU,EAAEL,IAAI,CAACK,UAAU;IAC3BC,OAAO,EAAEN,IAAI,CAACM,OAAO;IACrBC,UAAU,EAAEP,IAAI,CAACO,UAAU;IAC3BC,MAAM,EAAER,IAAI,CAACQ,MAAM;IACnBC,IAAI,EAAET,IAAI,CAACS,IAAI;IACfC,WAAW,EAAEV,IAAI,CAACU,WAAW;IAC7BC,OAAO,EAAEX,IAAI,CAACW,OAAO;IACrBC,QAAQ,EAAEZ,IAAI,CAACY,QAAQ;IACvBC,sBAAsB,EAAEb,IAAI,CAACa,sBAAsB;IACnDC,qBAAqB,EAAEd,IAAI,CAACc,qBAAqB;IACjDC,UAAU,EAAEf,IAAI,CAACe,UAAU;IAC3BC,cAAc,EAAEhB,IAAI,CAACgB,cAAc;IACnCC,UAAU,EAAEjB,IAAI,CAACiB,UAAU;IAK3BvB,OAAO,EAAEM,IAAI,CAACN,OAAO,KAAK,IAAI,GAAGlC,SAAS,GAAGwC,IAAI,CAACN,OAAO;IACzDwB,aAAa,EAAElB,IAAI,CAACkB,aAAa,KAAK,IAAI,GAAG1D,SAAS,GAAGwC,IAAI,CAACkB,aAAa;IAC3EC,QAAQ,EAAEnB,IAAI,CAACmB,QAAQ,KAAK,IAAI,GAAG3D,SAAS,GAAGwC,IAAI,CAACmB;EACtD,CAAC;EAEkC;IACjCC,MAAM,CAACC,MAAM,CAACpB,YAAY,EAAE;MAC1BqB,UAAU,EAAEtB,IAAI,CAACsB,UAAU;MAC3BC,SAAS,EAAEvB,IAAI,CAACuB,SAAS;MACzBC,QAAQ,EAAExB,IAAI,CAACwB;IACjB,CAAC,CAAC;EACJ;EAMA,KAAK,MAAMC,GAAG,IAAIL,MAAM,CAACM,IAAI,CAACzB,YAAY,CAAC,EAExC;IACD,IAAIA,YAAY,CAACwB,GAAG,CAAC,KAAKjE,SAAS,EAAE;MACnC,OAAOyC,YAAY,CAACwB,GAAG,CAAC;IAC1B;EACF;EAEA,OAAO;IACLxB,YAAY;IACZ0B,UAAU,EAAE;MACV5C,QAAQ,EAAEiB,IAAI,CAACjB,QAAQ;MACvBb,SAAS;MACT0D,UAAU,EAAE5B,IAAI,CAAC4B,UAAU;MAC3BjC,iBAAiB,EAAEK,IAAI,CAACL,iBAAiB;MACzCC,gBAAgB,EAAEI,IAAI,CAACJ,gBAAgB;MACvCP,KAAK,EAAEW,IAAI,CAACX,KAAK;MACjBC,gBAAgB,EAAEU,IAAI,CAACV,gBAAgB;MACvCH,OAAO,EAAEa,IAAI,CAACb,OAAO;MACrBD,MAAM,EAAEc,IAAI,CAACd,MAAM;MACnBE,QAAQ,EAAEY,IAAI,CAACZ,QAAQ;MACvByC,SAAS,EAAE7B,IAAI,CAAC6B,SAAS;MACzBC,WAAW,EAAE9B,IAAI,CAAC6B,SAAS,IAAI7B,IAAI,CAAC8B,WAAW;MAC/CC,eAAe,EAAE/B,IAAI,CAAC+B,eAAe;MACrCvC,OAAO,EAAEQ,IAAI,CAACR,OAAO;MACrBC,KAAK,EAAEO,IAAI,CAACP,KAAK;MACjBF,gBAAgB,EAAES,IAAI,CAACT,gBAAgB;MACvCyC,eAAe,EAAEhC,IAAI,CAACgC;IACxB;EACF,CAAC;AACH;AAIA,SAASzE,UAAUA,CAAC0E,GAAQ,EAAO;EACjC,IAAIA,GAAG,KAAKzE,SAAS,EAAE,OAAOA,SAAS;EAEvC,IAAIyE,GAAG,KAAK,MAAM,IAAIA,GAAG,IAAI,CAAC,EAAE;IAC9B,OAAO,IAAI;EACb;EAEA,IAAIA,GAAG,KAAK,OAAO,IAAIA,GAAG,IAAI,CAAC,IAAI,CAACA,GAAG,EAAE;IACvC,OAAO,KAAK;EACd;EAEA,OAAOA,GAAG;AACZ;AAEA,SAAS3E,OAAOA,CAAC4E,KAAc,EAAEC,aAA4B,EAAiB;EAE5E,IAAI,OAAOD,KAAK,KAAK,QAAQ,EAAE,OAAOC,aAAa;EAEnD,MAAMC,MAAM,GAAGF,KAAK,CAACG,KAAK,CAAC,GAAG,CAAC;EAE/B,IAAIF,aAAa,EAAE;IACjBA,aAAa,CAACzD,IAAI,CAAC,GAAG0D,MAAM,CAAC;IAC7B,OAAOD,aAAa;EACtB;EACA,OAAOC,MAAM;AACf","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/cli/lib/babel/util.js b/node_modules/@babel/cli/lib/babel/util.js new file mode 100644 index 000000000..2bef3e098 --- /dev/null +++ b/node_modules/@babel/cli/lib/babel/util.js @@ -0,0 +1,150 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.addSourceMappingUrl = addSourceMappingUrl; +exports.chmod = chmod; +exports.compile = compile; +exports.debounce = debounce; +exports.deleteDir = deleteDir; +exports.hasDataSourcemap = hasDataSourcemap; +exports.isCompilableExtension = isCompilableExtension; +exports.readdir = readdir; +exports.readdirForCompilable = readdirForCompilable; +exports.transformRepl = transformRepl; +exports.withExtension = withExtension; +function _fsReaddirRecursive() { + const data = require("fs-readdir-recursive"); + _fsReaddirRecursive = function () { + return data; + }; + return data; +} +function babel() { + const data = require("@babel/core"); + babel = function () { + return data; + }; + return data; +} +function _path() { + const data = require("path"); + _path = function () { + return data; + }; + return data; +} +function _fs() { + const data = require("fs"); + _fs = function () { + return data; + }; + return data; +} +var watcher = require("./watcher.js"); +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function chmod(src, dest) { + try { + _fs().chmodSync(dest, _fs().statSync(src).mode); + } catch (err) { + console.warn(`Cannot change permissions of ${dest}`); + } +} +function readdir(dirname, includeDotfiles, filter) { + return _fsReaddirRecursive()(dirname, (filename, index, currentDirectory) => { + const stat = _fs().statSync(_path().join(currentDirectory, filename)); + if (stat.isDirectory()) return true; + return (includeDotfiles || filename[0] !== ".") && (!filter || filter(filename)); + }); +} +function readdirForCompilable(dirname, includeDotfiles, altExts) { + return readdir(dirname, includeDotfiles, function (filename) { + return isCompilableExtension(filename, altExts); + }); +} +function isCompilableExtension(filename, altExts) { + const exts = altExts || babel().DEFAULT_EXTENSIONS; + const ext = _path().extname(filename); + return exts.includes(ext); +} +function addSourceMappingUrl(code, loc) { + return code + "\n//# sourceMappingURL=" + _path().basename(loc); +} +function hasDataSourcemap(code) { + const pos = code.lastIndexOf("\n", code.length - 2); + return pos != -1 && code.lastIndexOf("//# sourceMappingURL") < pos; +} +const CALLER = { + name: "@babel/cli" +}; +function transformRepl(filename, code, opts) { + opts = Object.assign({}, opts, { + caller: CALLER, + filename + }); + return new Promise((resolve, reject) => { + babel().transform(code, opts, (err, result) => { + if (err) reject(err);else resolve(result); + }); + }); +} +function compile(_x, _x2) { + return _compile.apply(this, arguments); +} +function _compile() { + _compile = _asyncToGenerator(function* (filename, opts) { + opts = Object.assign({}, opts, { + caller: CALLER + }); + const result = yield new Promise((resolve, reject) => { + babel().transformFile(filename, opts, (err, result) => { + if (err) reject(err);else resolve(result); + }); + }); + if (result) { + { + if (!result.externalDependencies) return result; + } + watcher.updateExternalDependencies(filename, result.externalDependencies); + } + return result; + }); + return _compile.apply(this, arguments); +} +function deleteDir(path) { + if (_fs().existsSync(path)) { + _fs().readdirSync(path).forEach(function (file) { + const curPath = path + "/" + file; + if (_fs().lstatSync(curPath).isDirectory()) { + deleteDir(curPath); + } else { + _fs().unlinkSync(curPath); + } + }); + _fs().rmdirSync(path); + } +} +process.on("uncaughtException", function (err) { + console.error(err); + process.exitCode = 1; +}); +function withExtension(filename, ext = ".js") { + const newBasename = _path().basename(filename, _path().extname(filename)) + ext; + return _path().join(_path().dirname(filename), newBasename); +} +function debounce(fn, time) { + let timer; + function debounced() { + clearTimeout(timer); + timer = setTimeout(fn, time); + } + debounced.flush = () => { + clearTimeout(timer); + fn(); + }; + return debounced; +} + +//# sourceMappingURL=util.js.map diff --git a/node_modules/@babel/cli/lib/babel/util.js.map b/node_modules/@babel/cli/lib/babel/util.js.map new file mode 100644 index 000000000..3b5071e8d --- /dev/null +++ b/node_modules/@babel/cli/lib/babel/util.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_fsReaddirRecursive","data","require","babel","_path","_fs","watcher","asyncGeneratorStep","gen","resolve","reject","_next","_throw","key","arg","info","value","error","done","Promise","then","_asyncToGenerator","fn","self","args","arguments","apply","err","undefined","chmod","src","dest","fs","chmodSync","statSync","mode","console","warn","readdir","dirname","includeDotfiles","filter","readdirRecursive","filename","index","currentDirectory","stat","path","join","isDirectory","readdirForCompilable","altExts","isCompilableExtension","exts","DEFAULT_EXTENSIONS","ext","extname","includes","addSourceMappingUrl","code","loc","basename","hasDataSourcemap","pos","lastIndexOf","length","CALLER","name","transformRepl","opts","Object","assign","caller","transform","result","compile","_x","_x2","_compile","transformFile","externalDependencies","updateExternalDependencies","deleteDir","existsSync","readdirSync","forEach","file","curPath","lstatSync","unlinkSync","rmdirSync","process","on","exitCode","withExtension","newBasename","debounce","time","timer","debounced","clearTimeout","setTimeout","flush"],"sources":["../../src/babel/util.ts"],"sourcesContent":["import readdirRecursive from \"fs-readdir-recursive\";\nimport * as babel from \"@babel/core\";\nimport path from \"path\";\nimport fs from \"fs\";\n\nimport * as watcher from \"./watcher.ts\";\n\nimport type { FileResult, InputOptions } from \"@babel/core\";\n\nexport function chmod(src: string, dest: string): void {\n try {\n fs.chmodSync(dest, fs.statSync(src).mode);\n } catch (err) {\n console.warn(`Cannot change permissions of ${dest}`);\n }\n}\n\ntype ReaddirFilter = (filename: string) => boolean;\n\nexport function readdir(\n dirname: string,\n includeDotfiles: boolean,\n filter?: ReaddirFilter,\n): Array {\n return readdirRecursive(dirname, (filename, index, currentDirectory) => {\n const stat = fs.statSync(path.join(currentDirectory, filename));\n\n if (stat.isDirectory()) return true;\n\n return (\n (includeDotfiles || filename[0] !== \".\") && (!filter || filter(filename))\n );\n });\n}\n\nexport function readdirForCompilable(\n dirname: string,\n includeDotfiles: boolean,\n altExts?: Array,\n): Array {\n return readdir(dirname, includeDotfiles, function (filename) {\n return isCompilableExtension(filename, altExts);\n });\n}\n\n/**\n * Test if a filename ends with a compilable extension.\n */\nexport function isCompilableExtension(\n filename: string,\n altExts?: readonly string[],\n): boolean {\n const exts = altExts || babel.DEFAULT_EXTENSIONS;\n const ext = path.extname(filename);\n return exts.includes(ext);\n}\n\nexport function addSourceMappingUrl(code: string, loc: string): string {\n return code + \"\\n//# sourceMappingURL=\" + path.basename(loc);\n}\n\nexport function hasDataSourcemap(code: string): boolean {\n const pos = code.lastIndexOf(\"\\n\", code.length - 2);\n return pos != -1 && code.lastIndexOf(\"//# sourceMappingURL\") < pos;\n}\n\nconst CALLER = {\n name: \"@babel/cli\",\n};\n\nexport function transformRepl(filename: string, code: string, opts: any) {\n opts = {\n ...opts,\n caller: CALLER,\n filename,\n };\n\n return new Promise((resolve, reject) => {\n babel.transform(code, opts, (err, result) => {\n if (err) reject(err);\n else resolve(result);\n });\n });\n}\n\nexport async function compile(filename: string, opts: InputOptions) {\n opts = {\n ...opts,\n caller: CALLER,\n };\n\n const result = process.env.BABEL_8_BREAKING\n ? await babel.transformFileAsync(filename, opts)\n : await new Promise((resolve, reject) => {\n babel.transformFile(filename, opts, (err, result) => {\n if (err) reject(err);\n else resolve(result);\n });\n });\n\n if (result) {\n if (!process.env.BABEL_8_BREAKING) {\n if (!result.externalDependencies) return result;\n }\n watcher.updateExternalDependencies(filename, result.externalDependencies);\n }\n\n return result;\n}\n\nexport function deleteDir(path: string): void {\n if (fs.existsSync(path)) {\n fs.readdirSync(path).forEach(function (file) {\n const curPath = path + \"/\" + file;\n if (fs.lstatSync(curPath).isDirectory()) {\n // recurse\n deleteDir(curPath);\n } else {\n // delete file\n fs.unlinkSync(curPath);\n }\n });\n fs.rmdirSync(path);\n }\n}\n\nprocess.on(\"uncaughtException\", function (err) {\n console.error(err);\n process.exitCode = 1;\n});\n\nexport function withExtension(filename: string, ext: string = \".js\") {\n const newBasename = path.basename(filename, path.extname(filename)) + ext;\n return path.join(path.dirname(filename), newBasename);\n}\n\nexport function debounce(fn: () => void, time: number) {\n let timer: NodeJS.Timeout;\n function debounced() {\n clearTimeout(timer);\n timer = setTimeout(fn, time);\n }\n debounced.flush = () => {\n clearTimeout(timer);\n fn();\n };\n return debounced;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,SAAAA,oBAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,mBAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,MAAA;EAAA,MAAAF,IAAA,GAAAC,OAAA;EAAAC,KAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAG,MAAA;EAAA,MAAAH,IAAA,GAAAC,OAAA;EAAAE,KAAA,YAAAA,CAAA;IAAA,OAAAH,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAI,IAAA;EAAA,MAAAJ,IAAA,GAAAC,OAAA;EAAAG,GAAA,YAAAA,CAAA;IAAA,OAAAJ,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,IAAAK,OAAA,GAAAJ,OAAA;AAAwC,SAAAK,mBAAAC,GAAA,EAAAC,OAAA,EAAAC,MAAA,EAAAC,KAAA,EAAAC,MAAA,EAAAC,GAAA,EAAAC,GAAA,cAAAC,IAAA,GAAAP,GAAA,CAAAK,GAAA,EAAAC,GAAA,OAAAE,KAAA,GAAAD,IAAA,CAAAC,KAAA,WAAAC,KAAA,IAAAP,MAAA,CAAAO,KAAA,iBAAAF,IAAA,CAAAG,IAAA,IAAAT,OAAA,CAAAO,KAAA,YAAAG,OAAA,CAAAV,OAAA,CAAAO,KAAA,EAAAI,IAAA,CAAAT,KAAA,EAAAC,MAAA;AAAA,SAAAS,kBAAAC,EAAA,6BAAAC,IAAA,SAAAC,IAAA,GAAAC,SAAA,aAAAN,OAAA,WAAAV,OAAA,EAAAC,MAAA,QAAAF,GAAA,GAAAc,EAAA,CAAAI,KAAA,CAAAH,IAAA,EAAAC,IAAA,YAAAb,MAAAK,KAAA,IAAAT,kBAAA,CAAAC,GAAA,EAAAC,OAAA,EAAAC,MAAA,EAAAC,KAAA,EAAAC,MAAA,UAAAI,KAAA,cAAAJ,OAAAe,GAAA,IAAApB,kBAAA,CAAAC,GAAA,EAAAC,OAAA,EAAAC,MAAA,EAAAC,KAAA,EAAAC,MAAA,WAAAe,GAAA,KAAAhB,KAAA,CAAAiB,SAAA;AAIjC,SAASC,KAAKA,CAACC,GAAW,EAAEC,IAAY,EAAQ;EACrD,IAAI;IACFC,IAACA,CAAC,CAACC,SAAS,CAACF,IAAI,EAAEC,IAACA,CAAC,CAACE,QAAQ,CAACJ,GAAG,CAAC,CAACK,IAAI,CAAC;EAC3C,CAAC,CAAC,OAAOR,GAAG,EAAE;IACZS,OAAO,CAACC,IAAI,CAAE,gCAA+BN,IAAK,EAAC,CAAC;EACtD;AACF;AAIO,SAASO,OAAOA,CACrBC,OAAe,EACfC,eAAwB,EACxBC,MAAsB,EACP;EACf,OAAOC,oBAAeA,CAAC,CAACH,OAAO,EAAE,CAACI,QAAQ,EAAEC,KAAK,EAAEC,gBAAgB,KAAK;IACtE,MAAMC,IAAI,GAAGd,IAACA,CAAC,CAACE,QAAQ,CAACa,MAAGA,CAAC,CAACC,IAAI,CAACH,gBAAgB,EAAEF,QAAQ,CAAC,CAAC;IAE/D,IAAIG,IAAI,CAACG,WAAW,CAAC,CAAC,EAAE,OAAO,IAAI;IAEnC,OACE,CAACT,eAAe,IAAIG,QAAQ,CAAC,CAAC,CAAC,KAAK,GAAG,MAAM,CAACF,MAAM,IAAIA,MAAM,CAACE,QAAQ,CAAC,CAAC;EAE7E,CAAC,CAAC;AACJ;AAEO,SAASO,oBAAoBA,CAClCX,OAAe,EACfC,eAAwB,EACxBW,OAAuB,EACR;EACf,OAAOb,OAAO,CAACC,OAAO,EAAEC,eAAe,EAAE,UAAUG,QAAQ,EAAE;IAC3D,OAAOS,qBAAqB,CAACT,QAAQ,EAAEQ,OAAO,CAAC;EACjD,CAAC,CAAC;AACJ;AAKO,SAASC,qBAAqBA,CACnCT,QAAgB,EAChBQ,OAA2B,EAClB;EACT,MAAME,IAAI,GAAGF,OAAO,IAAIhD,KAAK,CAAD,CAAC,CAACmD,kBAAkB;EAChD,MAAMC,GAAG,GAAGR,MAAGA,CAAC,CAACS,OAAO,CAACb,QAAQ,CAAC;EAClC,OAAOU,IAAI,CAACI,QAAQ,CAACF,GAAG,CAAC;AAC3B;AAEO,SAASG,mBAAmBA,CAACC,IAAY,EAAEC,GAAW,EAAU;EACrE,OAAOD,IAAI,GAAG,yBAAyB,GAAGZ,MAAGA,CAAC,CAACc,QAAQ,CAACD,GAAG,CAAC;AAC9D;AAEO,SAASE,gBAAgBA,CAACH,IAAY,EAAW;EACtD,MAAMI,GAAG,GAAGJ,IAAI,CAACK,WAAW,CAAC,IAAI,EAAEL,IAAI,CAACM,MAAM,GAAG,CAAC,CAAC;EACnD,OAAOF,GAAG,IAAI,CAAC,CAAC,IAAIJ,IAAI,CAACK,WAAW,CAAC,sBAAsB,CAAC,GAAGD,GAAG;AACpE;AAEA,MAAMG,MAAM,GAAG;EACbC,IAAI,EAAE;AACR,CAAC;AAEM,SAASC,aAAaA,CAACzB,QAAgB,EAAEgB,IAAY,EAAEU,IAAS,EAAE;EACvEA,IAAI,GAAAC,MAAA,CAAAC,MAAA,KACCF,IAAI;IACPG,MAAM,EAAEN,MAAM;IACdvB;EAAQ,EACT;EAED,OAAO,IAAIxB,OAAO,CAAa,CAACV,OAAO,EAAEC,MAAM,KAAK;IAClDP,KAAK,CAAD,CAAC,CAACsE,SAAS,CAACd,IAAI,EAAEU,IAAI,EAAE,CAAC1C,GAAG,EAAE+C,MAAM,KAAK;MAC3C,IAAI/C,GAAG,EAAEjB,MAAM,CAACiB,GAAG,CAAC,CAAC,KAChBlB,OAAO,CAACiE,MAAM,CAAC;IACtB,CAAC,CAAC;EACJ,CAAC,CAAC;AACJ;AAAC,SAEqBC,OAAOA,CAAAC,EAAA,EAAAC,GAAA;EAAA,OAAAC,QAAA,CAAApD,KAAA,OAAAD,SAAA;AAAA;AAAA,SAAAqD,SAAA;EAAAA,QAAA,GAAAzD,iBAAA,CAAtB,WAAuBsB,QAAgB,EAAE0B,IAAkB,EAAE;IAClEA,IAAI,GAAAC,MAAA,CAAAC,MAAA,KACCF,IAAI;MACPG,MAAM,EAAEN;IAAM,EACf;IAED,MAAMQ,MAAM,SAEF,IAAIvD,OAAO,CAAa,CAACV,OAAO,EAAEC,MAAM,KAAK;MACjDP,KAAK,CAAD,CAAC,CAAC4E,aAAa,CAACpC,QAAQ,EAAE0B,IAAI,EAAE,CAAC1C,GAAG,EAAE+C,MAAM,KAAK;QACnD,IAAI/C,GAAG,EAAEjB,MAAM,CAACiB,GAAG,CAAC,CAAC,KAChBlB,OAAO,CAACiE,MAAM,CAAC;MACtB,CAAC,CAAC;IACJ,CAAC,CAAC;IAEN,IAAIA,MAAM,EAAE;MACyB;QACjC,IAAI,CAACA,MAAM,CAACM,oBAAoB,EAAE,OAAON,MAAM;MACjD;MACApE,OAAO,CAAC2E,0BAA0B,CAACtC,QAAQ,EAAE+B,MAAM,CAACM,oBAAoB,CAAC;IAC3E;IAEA,OAAON,MAAM;EACf,CAAC;EAAA,OAAAI,QAAA,CAAApD,KAAA,OAAAD,SAAA;AAAA;AAEM,SAASyD,SAASA,CAACnC,IAAY,EAAQ;EAC5C,IAAIf,IAACA,CAAC,CAACmD,UAAU,CAACpC,IAAI,CAAC,EAAE;IACvBf,IAACA,CAAC,CAACoD,WAAW,CAACrC,IAAI,CAAC,CAACsC,OAAO,CAAC,UAAUC,IAAI,EAAE;MAC3C,MAAMC,OAAO,GAAGxC,IAAI,GAAG,GAAG,GAAGuC,IAAI;MACjC,IAAItD,IAACA,CAAC,CAACwD,SAAS,CAACD,OAAO,CAAC,CAACtC,WAAW,CAAC,CAAC,EAAE;QAEvCiC,SAAS,CAACK,OAAO,CAAC;MACpB,CAAC,MAAM;QAELvD,IAACA,CAAC,CAACyD,UAAU,CAACF,OAAO,CAAC;MACxB;IACF,CAAC,CAAC;IACFvD,IAACA,CAAC,CAAC0D,SAAS,CAAC3C,IAAI,CAAC;EACpB;AACF;AAEA4C,OAAO,CAACC,EAAE,CAAC,mBAAmB,EAAE,UAAUjE,GAAG,EAAE;EAC7CS,OAAO,CAACnB,KAAK,CAACU,GAAG,CAAC;EAClBgE,OAAO,CAACE,QAAQ,GAAG,CAAC;AACtB,CAAC,CAAC;AAEK,SAASC,aAAaA,CAACnD,QAAgB,EAAEY,GAAW,GAAG,KAAK,EAAE;EACnE,MAAMwC,WAAW,GAAGhD,MAAGA,CAAC,CAACc,QAAQ,CAAClB,QAAQ,EAAEI,MAAGA,CAAC,CAACS,OAAO,CAACb,QAAQ,CAAC,CAAC,GAAGY,GAAG;EACzE,OAAOR,MAAGA,CAAC,CAACC,IAAI,CAACD,MAAGA,CAAC,CAACR,OAAO,CAACI,QAAQ,CAAC,EAAEoD,WAAW,CAAC;AACvD;AAEO,SAASC,QAAQA,CAAC1E,EAAc,EAAE2E,IAAY,EAAE;EACrD,IAAIC,KAAqB;EACzB,SAASC,SAASA,CAAA,EAAG;IACnBC,YAAY,CAACF,KAAK,CAAC;IACnBA,KAAK,GAAGG,UAAU,CAAC/E,EAAE,EAAE2E,IAAI,CAAC;EAC9B;EACAE,SAAS,CAACG,KAAK,GAAG,MAAM;IACtBF,YAAY,CAACF,KAAK,CAAC;IACnB5E,EAAE,CAAC,CAAC;EACN,CAAC;EACD,OAAO6E,SAAS;AAClB","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/cli/lib/babel/watcher.js b/node_modules/@babel/cli/lib/babel/watcher.js new file mode 100644 index 000000000..203e8ca88 --- /dev/null +++ b/node_modules/@babel/cli/lib/babel/watcher.js @@ -0,0 +1,129 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.enable = enable; +exports.onFilesChange = onFilesChange; +exports.startWatcher = startWatcher; +exports.updateExternalDependencies = updateExternalDependencies; +exports.watch = watch; +function _path() { + const data = require("path"); + _path = function () { + return data; + }; + return data; +} +const fileToDeps = new Map(); +const depToFiles = new Map(); +let isWatchMode = false; +let watcher; +const watchQueue = new Set(); +let hasStarted = false; +function enable({ + enableGlobbing +}) { + isWatchMode = true; + const { + FSWatcher + } = requireChokidar(); + const options = { + disableGlobbing: !enableGlobbing, + persistent: true, + ignoreInitial: true, + awaitWriteFinish: { + stabilityThreshold: 50, + pollInterval: 10 + } + }; + watcher = new FSWatcher(options); + watcher.on("unlink", unwatchFile); +} +function startWatcher() { + hasStarted = true; + for (const dep of watchQueue) { + watcher.add(dep); + } + watchQueue.clear(); + watcher.on("ready", () => { + console.log("The watcher is ready."); + }); +} +function watch(filename) { + if (!isWatchMode) { + throw new Error("Internal Babel error: .watch called when not in watch mode."); + } + if (!hasStarted) { + watchQueue.add(_path().resolve(filename)); + } else { + watcher.add(_path().resolve(filename)); + } +} +function onFilesChange(callback) { + if (!isWatchMode) { + throw new Error("Internal Babel error: .onFilesChange called when not in watch mode."); + } + watcher.on("all", (event, filename) => { + var _depToFiles$get; + if (event !== "change" && event !== "add") return; + const absoluteFile = _path().resolve(filename); + callback([absoluteFile, ...((_depToFiles$get = depToFiles.get(absoluteFile)) != null ? _depToFiles$get : [])], event, absoluteFile); + }); +} +function updateExternalDependencies(filename, dependencies) { + if (!isWatchMode) return; + const absFilename = _path().resolve(filename); + const absDependencies = new Set(Array.from(dependencies, dep => _path().resolve(dep))); + const deps = fileToDeps.get(absFilename); + if (deps) { + for (const dep of deps) { + if (!absDependencies.has(dep)) { + removeFileDependency(absFilename, dep); + } + } + } + for (const dep of absDependencies) { + let deps = depToFiles.get(dep); + if (!deps) { + depToFiles.set(dep, deps = new Set()); + if (!hasStarted) { + watchQueue.add(dep); + } else { + watcher.add(dep); + } + } + deps.add(absFilename); + } + fileToDeps.set(absFilename, absDependencies); +} +function removeFileDependency(filename, dep) { + const deps = depToFiles.get(dep); + deps.delete(filename); + if (deps.size === 0) { + depToFiles.delete(dep); + if (!hasStarted) { + watchQueue.delete(dep); + } else { + watcher.unwatch(dep); + } + } +} +function unwatchFile(filename) { + const deps = fileToDeps.get(filename); + if (!deps) return; + for (const dep of deps) { + removeFileDependency(filename, dep); + } + fileToDeps.delete(filename); +} +function requireChokidar() { + try { + return parseInt(process.versions.node) >= 8 ? require("chokidar") : require("@nicolo-ribaudo/chokidar-2"); + } catch (err) { + console.error("The optional dependency chokidar failed to install and is required for " + "--watch. Chokidar is likely not supported on your platform."); + throw err; + } +} + +//# sourceMappingURL=watcher.js.map diff --git a/node_modules/@babel/cli/lib/babel/watcher.js.map b/node_modules/@babel/cli/lib/babel/watcher.js.map new file mode 100644 index 000000000..23afe8337 --- /dev/null +++ b/node_modules/@babel/cli/lib/babel/watcher.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_path","data","require","fileToDeps","Map","depToFiles","isWatchMode","watcher","watchQueue","Set","hasStarted","enable","enableGlobbing","FSWatcher","requireChokidar","options","disableGlobbing","persistent","ignoreInitial","awaitWriteFinish","stabilityThreshold","pollInterval","on","unwatchFile","startWatcher","dep","add","clear","console","log","watch","filename","Error","path","resolve","onFilesChange","callback","event","_depToFiles$get","absoluteFile","get","updateExternalDependencies","dependencies","absFilename","absDependencies","Array","from","deps","has","removeFileDependency","set","delete","size","unwatch","parseInt","process","versions","node","err","error"],"sources":["../../src/babel/watcher.ts"],"sourcesContent":["import { createRequire } from \"module\";\nimport path from \"path\";\nimport type { WatchOptions, FSWatcher } from \"chokidar\";\n\nconst fileToDeps = new Map>();\nconst depToFiles = new Map>();\n\nlet isWatchMode = false;\nlet watcher: FSWatcher;\nconst watchQueue = new Set();\nlet hasStarted = false;\n\nexport function enable({ enableGlobbing }: { enableGlobbing: boolean }) {\n isWatchMode = true;\n\n const { FSWatcher } = requireChokidar();\n\n const options: WatchOptions = {\n disableGlobbing: !enableGlobbing,\n persistent: true,\n ignoreInitial: true,\n awaitWriteFinish: {\n stabilityThreshold: 50,\n pollInterval: 10,\n },\n };\n watcher = new FSWatcher(options);\n\n watcher.on(\"unlink\", unwatchFile);\n}\n\nexport function startWatcher() {\n hasStarted = true;\n\n for (const dep of watchQueue) {\n watcher.add(dep);\n }\n watchQueue.clear();\n\n watcher.on(\"ready\", () => {\n console.log(\"The watcher is ready.\");\n });\n}\n\nexport function watch(filename: string): void {\n if (!isWatchMode) {\n throw new Error(\n \"Internal Babel error: .watch called when not in watch mode.\",\n );\n }\n\n if (!hasStarted) {\n watchQueue.add(path.resolve(filename));\n } else {\n watcher.add(path.resolve(filename));\n }\n}\n\n/**\n * Call @param callback whenever a dependency (source file)/\n * external dependency (non-source file) changes.\n *\n * Handles mapping external dependencies to their corresponding\n * dependencies.\n */\nexport function onFilesChange(\n callback: (filenames: string[], event: string, cause: string) => void,\n): void {\n if (!isWatchMode) {\n throw new Error(\n \"Internal Babel error: .onFilesChange called when not in watch mode.\",\n );\n }\n\n watcher.on(\"all\", (event, filename) => {\n if (event !== \"change\" && event !== \"add\") return;\n\n const absoluteFile = path.resolve(filename);\n callback(\n [absoluteFile, ...(depToFiles.get(absoluteFile) ?? [])],\n event,\n absoluteFile,\n );\n });\n}\n\nexport function updateExternalDependencies(\n filename: string,\n dependencies: Set,\n) {\n if (!isWatchMode) return;\n\n // Use absolute paths\n const absFilename = path.resolve(filename);\n const absDependencies = new Set(\n Array.from(dependencies, dep => path.resolve(dep)),\n );\n\n const deps = fileToDeps.get(absFilename);\n if (deps) {\n for (const dep of deps) {\n if (!absDependencies.has(dep)) {\n removeFileDependency(absFilename, dep);\n }\n }\n }\n for (const dep of absDependencies) {\n let deps = depToFiles.get(dep);\n if (!deps) {\n depToFiles.set(dep, (deps = new Set()));\n\n if (!hasStarted) {\n watchQueue.add(dep);\n } else {\n watcher.add(dep);\n }\n }\n\n deps.add(absFilename);\n }\n\n fileToDeps.set(absFilename, absDependencies);\n}\n\nfunction removeFileDependency(filename: string, dep: string) {\n const deps = depToFiles.get(dep);\n deps.delete(filename);\n\n if (deps.size === 0) {\n depToFiles.delete(dep);\n\n if (!hasStarted) {\n watchQueue.delete(dep);\n } else {\n watcher.unwatch(dep);\n }\n }\n}\n\nfunction unwatchFile(filename: string) {\n const deps = fileToDeps.get(filename);\n if (!deps) return;\n\n for (const dep of deps) {\n removeFileDependency(filename, dep);\n }\n fileToDeps.delete(filename);\n}\n\nfunction requireChokidar(): any {\n const require = createRequire(import.meta.url);\n\n try {\n return process.env.BABEL_8_BREAKING\n ? require(\"chokidar\")\n : parseInt(process.versions.node) >= 8\n ? require(\"chokidar\")\n : require(\"@nicolo-ribaudo/chokidar-2\");\n } catch (err) {\n console.error(\n \"The optional dependency chokidar failed to install and is required for \" +\n \"--watch. Chokidar is likely not supported on your platform.\",\n );\n throw err;\n }\n}\n"],"mappings":";;;;;;;;;;AACA,SAAAA,MAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,KAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAGA,MAAME,UAAU,GAAG,IAAIC,GAAG,CAAsB,CAAC;AACjD,MAAMC,UAAU,GAAG,IAAID,GAAG,CAAsB,CAAC;AAEjD,IAAIE,WAAW,GAAG,KAAK;AACvB,IAAIC,OAAkB;AACtB,MAAMC,UAAU,GAAG,IAAIC,GAAG,CAAS,CAAC;AACpC,IAAIC,UAAU,GAAG,KAAK;AAEf,SAASC,MAAMA,CAAC;EAAEC;AAA4C,CAAC,EAAE;EACtEN,WAAW,GAAG,IAAI;EAElB,MAAM;IAAEO;EAAU,CAAC,GAAGC,eAAe,CAAC,CAAC;EAEvC,MAAMC,OAAqB,GAAG;IAC5BC,eAAe,EAAE,CAACJ,cAAc;IAChCK,UAAU,EAAE,IAAI;IAChBC,aAAa,EAAE,IAAI;IACnBC,gBAAgB,EAAE;MAChBC,kBAAkB,EAAE,EAAE;MACtBC,YAAY,EAAE;IAChB;EACF,CAAC;EACDd,OAAO,GAAG,IAAIM,SAAS,CAACE,OAAO,CAAC;EAEhCR,OAAO,CAACe,EAAE,CAAC,QAAQ,EAAEC,WAAW,CAAC;AACnC;AAEO,SAASC,YAAYA,CAAA,EAAG;EAC7Bd,UAAU,GAAG,IAAI;EAEjB,KAAK,MAAMe,GAAG,IAAIjB,UAAU,EAAE;IAC5BD,OAAO,CAACmB,GAAG,CAACD,GAAG,CAAC;EAClB;EACAjB,UAAU,CAACmB,KAAK,CAAC,CAAC;EAElBpB,OAAO,CAACe,EAAE,CAAC,OAAO,EAAE,MAAM;IACxBM,OAAO,CAACC,GAAG,CAAC,uBAAuB,CAAC;EACtC,CAAC,CAAC;AACJ;AAEO,SAASC,KAAKA,CAACC,QAAgB,EAAQ;EAC5C,IAAI,CAACzB,WAAW,EAAE;IAChB,MAAM,IAAI0B,KAAK,CACb,6DACF,CAAC;EACH;EAEA,IAAI,CAACtB,UAAU,EAAE;IACfF,UAAU,CAACkB,GAAG,CAACO,MAAGA,CAAC,CAACC,OAAO,CAACH,QAAQ,CAAC,CAAC;EACxC,CAAC,MAAM;IACLxB,OAAO,CAACmB,GAAG,CAACO,MAAGA,CAAC,CAACC,OAAO,CAACH,QAAQ,CAAC,CAAC;EACrC;AACF;AASO,SAASI,aAAaA,CAC3BC,QAAqE,EAC/D;EACN,IAAI,CAAC9B,WAAW,EAAE;IAChB,MAAM,IAAI0B,KAAK,CACb,qEACF,CAAC;EACH;EAEAzB,OAAO,CAACe,EAAE,CAAC,KAAK,EAAE,CAACe,KAAK,EAAEN,QAAQ,KAAK;IAAA,IAAAO,eAAA;IACrC,IAAID,KAAK,KAAK,QAAQ,IAAIA,KAAK,KAAK,KAAK,EAAE;IAE3C,MAAME,YAAY,GAAGN,MAAGA,CAAC,CAACC,OAAO,CAACH,QAAQ,CAAC;IAC3CK,QAAQ,CACN,CAACG,YAAY,EAAE,KAAAD,eAAA,GAAIjC,UAAU,CAACmC,GAAG,CAACD,YAAY,CAAC,YAAAD,eAAA,GAAI,EAAE,CAAC,CAAC,EACvDD,KAAK,EACLE,YACF,CAAC;EACH,CAAC,CAAC;AACJ;AAEO,SAASE,0BAA0BA,CACxCV,QAAgB,EAChBW,YAAyB,EACzB;EACA,IAAI,CAACpC,WAAW,EAAE;EAGlB,MAAMqC,WAAW,GAAGV,MAAGA,CAAC,CAACC,OAAO,CAACH,QAAQ,CAAC;EAC1C,MAAMa,eAAe,GAAG,IAAInC,GAAG,CAC7BoC,KAAK,CAACC,IAAI,CAACJ,YAAY,EAAEjB,GAAG,IAAIQ,MAAGA,CAAC,CAACC,OAAO,CAACT,GAAG,CAAC,CACnD,CAAC;EAED,MAAMsB,IAAI,GAAG5C,UAAU,CAACqC,GAAG,CAACG,WAAW,CAAC;EACxC,IAAII,IAAI,EAAE;IACR,KAAK,MAAMtB,GAAG,IAAIsB,IAAI,EAAE;MACtB,IAAI,CAACH,eAAe,CAACI,GAAG,CAACvB,GAAG,CAAC,EAAE;QAC7BwB,oBAAoB,CAACN,WAAW,EAAElB,GAAG,CAAC;MACxC;IACF;EACF;EACA,KAAK,MAAMA,GAAG,IAAImB,eAAe,EAAE;IACjC,IAAIG,IAAI,GAAG1C,UAAU,CAACmC,GAAG,CAACf,GAAG,CAAC;IAC9B,IAAI,CAACsB,IAAI,EAAE;MACT1C,UAAU,CAAC6C,GAAG,CAACzB,GAAG,EAAGsB,IAAI,GAAG,IAAItC,GAAG,CAAC,CAAE,CAAC;MAEvC,IAAI,CAACC,UAAU,EAAE;QACfF,UAAU,CAACkB,GAAG,CAACD,GAAG,CAAC;MACrB,CAAC,MAAM;QACLlB,OAAO,CAACmB,GAAG,CAACD,GAAG,CAAC;MAClB;IACF;IAEAsB,IAAI,CAACrB,GAAG,CAACiB,WAAW,CAAC;EACvB;EAEAxC,UAAU,CAAC+C,GAAG,CAACP,WAAW,EAAEC,eAAe,CAAC;AAC9C;AAEA,SAASK,oBAAoBA,CAAClB,QAAgB,EAAEN,GAAW,EAAE;EAC3D,MAAMsB,IAAI,GAAG1C,UAAU,CAACmC,GAAG,CAACf,GAAG,CAAC;EAChCsB,IAAI,CAACI,MAAM,CAACpB,QAAQ,CAAC;EAErB,IAAIgB,IAAI,CAACK,IAAI,KAAK,CAAC,EAAE;IACnB/C,UAAU,CAAC8C,MAAM,CAAC1B,GAAG,CAAC;IAEtB,IAAI,CAACf,UAAU,EAAE;MACfF,UAAU,CAAC2C,MAAM,CAAC1B,GAAG,CAAC;IACxB,CAAC,MAAM;MACLlB,OAAO,CAAC8C,OAAO,CAAC5B,GAAG,CAAC;IACtB;EACF;AACF;AAEA,SAASF,WAAWA,CAACQ,QAAgB,EAAE;EACrC,MAAMgB,IAAI,GAAG5C,UAAU,CAACqC,GAAG,CAACT,QAAQ,CAAC;EACrC,IAAI,CAACgB,IAAI,EAAE;EAEX,KAAK,MAAMtB,GAAG,IAAIsB,IAAI,EAAE;IACtBE,oBAAoB,CAAClB,QAAQ,EAAEN,GAAG,CAAC;EACrC;EACAtB,UAAU,CAACgD,MAAM,CAACpB,QAAQ,CAAC;AAC7B;AAEA,SAASjB,eAAeA,CAAA,EAAQ;EAG9B,IAAI;IACF,OAEIwC,QAAQ,CAACC,OAAO,CAACC,QAAQ,CAACC,IAAI,CAAC,IAAI,CAAC,GAClCvD,OAAO,CAAC,UAAU,CAAC,GACnBA,OAAO,CAAC,4BAA4B,CAAC;EAC7C,CAAC,CAAC,OAAOwD,GAAG,EAAE;IACZ9B,OAAO,CAAC+B,KAAK,CACX,yEAAyE,GACvE,6DACJ,CAAC;IACD,MAAMD,GAAG;EACX;AACF","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/cli/node_modules/.bin/semver b/node_modules/@babel/cli/node_modules/.bin/semver new file mode 120000 index 000000000..317eb293d --- /dev/null +++ b/node_modules/@babel/cli/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver \ No newline at end of file diff --git a/node_modules/@babel/cli/node_modules/convert-source-map/LICENSE b/node_modules/@babel/cli/node_modules/convert-source-map/LICENSE new file mode 100644 index 000000000..41702c504 --- /dev/null +++ b/node_modules/@babel/cli/node_modules/convert-source-map/LICENSE @@ -0,0 +1,23 @@ +Copyright 2013 Thorsten Lorenz. +All rights reserved. + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/cli/node_modules/convert-source-map/README.md b/node_modules/@babel/cli/node_modules/convert-source-map/README.md new file mode 100644 index 000000000..aa4d80482 --- /dev/null +++ b/node_modules/@babel/cli/node_modules/convert-source-map/README.md @@ -0,0 +1,206 @@ +# convert-source-map [![Build Status][ci-image]][ci-url] + +Converts a source-map from/to different formats and allows adding/changing properties. + +```js +var convert = require('convert-source-map'); + +var json = convert + .fromComment('//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVpbGQvZm9vLm1pbi5qcyIsInNvdXJjZXMiOlsic3JjL2Zvby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=') + .toJSON(); + +var modified = convert + .fromComment('//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVpbGQvZm9vLm1pbi5qcyIsInNvdXJjZXMiOlsic3JjL2Zvby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=') + .setProperty('sources', [ 'SRC/FOO.JS' ]) + .toJSON(); + +console.log(json); +console.log(modified); +``` + +```json +{"version":3,"file":"build/foo.min.js","sources":["src/foo.js"],"names":[],"mappings":"AAAA","sourceRoot":"/"} +{"version":3,"file":"build/foo.min.js","sources":["SRC/FOO.JS"],"names":[],"mappings":"AAAA","sourceRoot":"/"} +``` + +## Upgrading + +Prior to v2.0.0, the `fromMapFileComment` and `fromMapFileSource` functions took a String directory path and used that to resolve & read the source map file from the filesystem. However, this made the library limited to nodejs environments and broke on sources with querystrings. + +In v2.0.0, you now need to pass a function that does the file reading. It will receive the source filename as a String that you can resolve to a filesystem path, URL, or anything else. + +If you are using `convert-source-map` in nodejs and want the previous behavior, you'll use a function like such: + +```diff ++ var fs = require('fs'); // Import the fs module to read a file ++ var path = require('path'); // Import the path module to resolve a path against your directory +- var conv = convert.fromMapFileSource(css, '../my-dir'); ++ var conv = convert.fromMapFileSource(css, function (filename) { ++ return fs.readFileSync(path.resolve('../my-dir', filename), 'utf-8'); ++ }); +``` + +## API + +### fromObject(obj) + +Returns source map converter from given object. + +### fromJSON(json) + +Returns source map converter from given json string. + +### fromURI(uri) + +Returns source map converter from given uri encoded json string. + +### fromBase64(base64) + +Returns source map converter from given base64 encoded json string. + +### fromComment(comment) + +Returns source map converter from given base64 or uri encoded json string prefixed with `//# sourceMappingURL=...`. + +### fromMapFileComment(comment, readMap) + +Returns source map converter from given `filename` by parsing `//# sourceMappingURL=filename`. + +`readMap` must be a function which receives the source map filename and returns either a String or Buffer of the source map (if read synchronously), or a `Promise` containing a String or Buffer of the source map (if read asynchronously). + +If `readMap` doesn't return a `Promise`, `fromMapFileComment` will return a source map converter synchronously. + +If `readMap` returns a `Promise`, `fromMapFileComment` will also return `Promise`. The `Promise` will be either resolved with the source map converter or rejected with an error. + +#### Examples + +**Synchronous read in Node.js:** + +```js +var convert = require('convert-source-map'); +var fs = require('fs'); + +function readMap(filename) { + return fs.readFileSync(filename, 'utf8'); +} + +var json = convert + .fromMapFileComment('//# sourceMappingURL=map-file-comment.css.map', readMap) + .toJSON(); +console.log(json); +``` + + +**Asynchronous read in Node.js:** + +```js +var convert = require('convert-source-map'); +var { promises: fs } = require('fs'); // Notice the `promises` import + +function readMap(filename) { + return fs.readFile(filename, 'utf8'); +} + +var converter = await convert.fromMapFileComment('//# sourceMappingURL=map-file-comment.css.map', readMap) +var json = converter.toJSON(); +console.log(json); +``` + +**Asynchronous read in the browser:** + +```js +var convert = require('convert-source-map'); + +async function readMap(url) { + const res = await fetch(url); + return res.text(); +} + +const converter = await convert.fromMapFileComment('//# sourceMappingURL=map-file-comment.css.map', readMap) +var json = converter.toJSON(); +console.log(json); +``` + +### fromSource(source) + +Finds last sourcemap comment in file and returns source map converter or returns `null` if no source map comment was found. + +### fromMapFileSource(source, readMap) + +Finds last sourcemap comment in file and returns source map converter or returns `null` if no source map comment was found. + +`readMap` must be a function which receives the source map filename and returns either a String or Buffer of the source map (if read synchronously), or a `Promise` containing a String or Buffer of the source map (if read asynchronously). + +If `readMap` doesn't return a `Promise`, `fromMapFileSource` will return a source map converter synchronously. + +If `readMap` returns a `Promise`, `fromMapFileSource` will also return `Promise`. The `Promise` will be either resolved with the source map converter or rejected with an error. + +### toObject() + +Returns a copy of the underlying source map. + +### toJSON([space]) + +Converts source map to json string. If `space` is given (optional), this will be passed to +[JSON.stringify](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify) when the +JSON string is generated. + +### toURI() + +Converts source map to uri encoded json string. + +### toBase64() + +Converts source map to base64 encoded json string. + +### toComment([options]) + +Converts source map to an inline comment that can be appended to the source-file. + +By default, the comment is formatted like: `//# sourceMappingURL=...`, which you would +normally see in a JS source file. + +When `options.encoding == 'uri'`, the data will be uri encoded, otherwise they will be base64 encoded. + +When `options.multiline == true`, the comment is formatted like: `/*# sourceMappingURL=... */`, which you would find in a CSS source file. + +### addProperty(key, value) + +Adds given property to the source map. Throws an error if property already exists. + +### setProperty(key, value) + +Sets given property to the source map. If property doesn't exist it is added, otherwise its value is updated. + +### getProperty(key) + +Gets given property of the source map. + +### removeComments(src) + +Returns `src` with all source map comments removed + +### removeMapFileComments(src) + +Returns `src` with all source map comments pointing to map files removed. + +### commentRegex + +Provides __a fresh__ RegExp each time it is accessed. Can be used to find source map comments. + +Breaks down a source map comment into groups: Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data. + +### mapFileCommentRegex + +Provides __a fresh__ RegExp each time it is accessed. Can be used to find source map comments pointing to map files. + +### generateMapFileComment(file, [options]) + +Returns a comment that links to an external source map via `file`. + +By default, the comment is formatted like: `//# sourceMappingURL=...`, which you would normally see in a JS source file. + +When `options.multiline == true`, the comment is formatted like: `/*# sourceMappingURL=... */`, which you would find in a CSS source file. + +[ci-url]: https://github.com/thlorenz/convert-source-map/actions?query=workflow:ci +[ci-image]: https://img.shields.io/github/workflow/status/thlorenz/convert-source-map/CI?style=flat-square diff --git a/node_modules/@babel/cli/node_modules/convert-source-map/index.js b/node_modules/@babel/cli/node_modules/convert-source-map/index.js new file mode 100644 index 000000000..2e8e916e7 --- /dev/null +++ b/node_modules/@babel/cli/node_modules/convert-source-map/index.js @@ -0,0 +1,233 @@ +'use strict'; + +Object.defineProperty(exports, 'commentRegex', { + get: function getCommentRegex () { + // Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data. + return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/mg; + } +}); + + +Object.defineProperty(exports, 'mapFileCommentRegex', { + get: function getMapFileCommentRegex () { + // Matches sourceMappingURL in either // or /* comment styles. + return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/mg; + } +}); + +var decodeBase64; +if (typeof Buffer !== 'undefined') { + if (typeof Buffer.from === 'function') { + decodeBase64 = decodeBase64WithBufferFrom; + } else { + decodeBase64 = decodeBase64WithNewBuffer; + } +} else { + decodeBase64 = decodeBase64WithAtob; +} + +function decodeBase64WithBufferFrom(base64) { + return Buffer.from(base64, 'base64').toString(); +} + +function decodeBase64WithNewBuffer(base64) { + if (typeof value === 'number') { + throw new TypeError('The value to decode must not be of type number.'); + } + return new Buffer(base64, 'base64').toString(); +} + +function decodeBase64WithAtob(base64) { + return decodeURIComponent(escape(atob(base64))); +} + +function stripComment(sm) { + return sm.split(',').pop(); +} + +function readFromFileMap(sm, read) { + var r = exports.mapFileCommentRegex.exec(sm); + // for some odd reason //# .. captures in 1 and /* .. */ in 2 + var filename = r[1] || r[2]; + + try { + var sm = read(filename); + if (sm != null && typeof sm.catch === 'function') { + return sm.catch(throwError); + } else { + return sm; + } + } catch (e) { + throwError(e); + } + + function throwError(e) { + throw new Error('An error occurred while trying to read the map file at ' + filename + '\n' + e.stack); + } +} + +function Converter (sm, opts) { + opts = opts || {}; + + if (opts.hasComment) { + sm = stripComment(sm); + } + + if (opts.encoding === 'base64') { + sm = decodeBase64(sm); + } else if (opts.encoding === 'uri') { + sm = decodeURIComponent(sm); + } + + if (opts.isJSON || opts.encoding) { + sm = JSON.parse(sm); + } + + this.sourcemap = sm; +} + +Converter.prototype.toJSON = function (space) { + return JSON.stringify(this.sourcemap, null, space); +}; + +if (typeof Buffer !== 'undefined') { + if (typeof Buffer.from === 'function') { + Converter.prototype.toBase64 = encodeBase64WithBufferFrom; + } else { + Converter.prototype.toBase64 = encodeBase64WithNewBuffer; + } +} else { + Converter.prototype.toBase64 = encodeBase64WithBtoa; +} + +function encodeBase64WithBufferFrom() { + var json = this.toJSON(); + return Buffer.from(json, 'utf8').toString('base64'); +} + +function encodeBase64WithNewBuffer() { + var json = this.toJSON(); + if (typeof json === 'number') { + throw new TypeError('The json to encode must not be of type number.'); + } + return new Buffer(json, 'utf8').toString('base64'); +} + +function encodeBase64WithBtoa() { + var json = this.toJSON(); + return btoa(unescape(encodeURIComponent(json))); +} + +Converter.prototype.toURI = function () { + var json = this.toJSON(); + return encodeURIComponent(json); +}; + +Converter.prototype.toComment = function (options) { + var encoding, content, data; + if (options != null && options.encoding === 'uri') { + encoding = ''; + content = this.toURI(); + } else { + encoding = ';base64'; + content = this.toBase64(); + } + data = 'sourceMappingURL=data:application/json;charset=utf-8' + encoding + ',' + content; + return options != null && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; +}; + +// returns copy instead of original +Converter.prototype.toObject = function () { + return JSON.parse(this.toJSON()); +}; + +Converter.prototype.addProperty = function (key, value) { + if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead'); + return this.setProperty(key, value); +}; + +Converter.prototype.setProperty = function (key, value) { + this.sourcemap[key] = value; + return this; +}; + +Converter.prototype.getProperty = function (key) { + return this.sourcemap[key]; +}; + +exports.fromObject = function (obj) { + return new Converter(obj); +}; + +exports.fromJSON = function (json) { + return new Converter(json, { isJSON: true }); +}; + +exports.fromURI = function (uri) { + return new Converter(uri, { encoding: 'uri' }); +}; + +exports.fromBase64 = function (base64) { + return new Converter(base64, { encoding: 'base64' }); +}; + +exports.fromComment = function (comment) { + var m, encoding; + comment = comment + .replace(/^\/\*/g, '//') + .replace(/\*\/$/g, ''); + m = exports.commentRegex.exec(comment); + encoding = m && m[4] || 'uri'; + return new Converter(comment, { encoding: encoding, hasComment: true }); +}; + +function makeConverter(sm) { + return new Converter(sm, { isJSON: true }); +} + +exports.fromMapFileComment = function (comment, read) { + if (typeof read === 'string') { + throw new Error( + 'String directory paths are no longer supported with `fromMapFileComment`\n' + + 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading' + ) + } + + var sm = readFromFileMap(comment, read); + if (sm != null && typeof sm.then === 'function') { + return sm.then(makeConverter); + } else { + return makeConverter(sm); + } +}; + +// Finds last sourcemap comment in file or returns null if none was found +exports.fromSource = function (content) { + var m = content.match(exports.commentRegex); + return m ? exports.fromComment(m.pop()) : null; +}; + +// Finds last sourcemap comment in file or returns null if none was found +exports.fromMapFileSource = function (content, read) { + if (typeof read === 'string') { + throw new Error( + 'String directory paths are no longer supported with `fromMapFileSource`\n' + + 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading' + ) + } + var m = content.match(exports.mapFileCommentRegex); + return m ? exports.fromMapFileComment(m.pop(), read) : null; +}; + +exports.removeComments = function (src) { + return src.replace(exports.commentRegex, ''); +}; + +exports.removeMapFileComments = function (src) { + return src.replace(exports.mapFileCommentRegex, ''); +}; + +exports.generateMapFileComment = function (file, options) { + var data = 'sourceMappingURL=' + file; + return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; +}; diff --git a/node_modules/@babel/cli/node_modules/convert-source-map/package.json b/node_modules/@babel/cli/node_modules/convert-source-map/package.json new file mode 100644 index 000000000..c38f29f72 --- /dev/null +++ b/node_modules/@babel/cli/node_modules/convert-source-map/package.json @@ -0,0 +1,38 @@ +{ + "name": "convert-source-map", + "version": "2.0.0", + "description": "Converts a source-map from/to different formats and allows adding/changing properties.", + "main": "index.js", + "scripts": { + "test": "tap test/*.js --color" + }, + "repository": { + "type": "git", + "url": "git://github.com/thlorenz/convert-source-map.git" + }, + "homepage": "https://github.com/thlorenz/convert-source-map", + "devDependencies": { + "inline-source-map": "~0.6.2", + "tap": "~9.0.0" + }, + "keywords": [ + "convert", + "sourcemap", + "source", + "map", + "browser", + "debug" + ], + "author": { + "name": "Thorsten Lorenz", + "email": "thlorenz@gmx.de", + "url": "http://thlorenz.com" + }, + "license": "MIT", + "engine": { + "node": ">=4" + }, + "files": [ + "index.js" + ] +} diff --git a/node_modules/@babel/cli/node_modules/make-dir/index.d.ts b/node_modules/@babel/cli/node_modules/make-dir/index.d.ts new file mode 100644 index 000000000..3e1529c62 --- /dev/null +++ b/node_modules/@babel/cli/node_modules/make-dir/index.d.ts @@ -0,0 +1,39 @@ +/// +import * as fs from 'fs'; + +export interface Options { + /** + * Directory [permissions](https://x-team.com/blog/file-system-permissions-umask-node-js/). + * + * @default 0o777 & (~process.umask()) + */ + readonly mode?: number; + + /** + * Use a custom `fs` implementation. For example [`graceful-fs`](https://github.com/isaacs/node-graceful-fs). + * + * Using a custom `fs` implementation will block the use of the native `recursive` option if `fs.mkdir` or `fs.mkdirSync` is not the native function. + * + * @default require('fs') + */ + readonly fs?: typeof fs; +} + +/** + * Make a directory and its parents if needed - Think `mkdir -p`. + * + * @param path - Directory to create. + * @returns A `Promise` for the path to the created directory. + */ +export default function makeDir( + path: string, + options?: Options +): Promise; + +/** + * Synchronously make a directory and its parents if needed - Think `mkdir -p`. + * + * @param path - Directory to create. + * @returns The path to the created directory. + */ +export function sync(path: string, options?: Options): string; diff --git a/node_modules/@babel/cli/node_modules/make-dir/index.js b/node_modules/@babel/cli/node_modules/make-dir/index.js new file mode 100644 index 000000000..4d95c9164 --- /dev/null +++ b/node_modules/@babel/cli/node_modules/make-dir/index.js @@ -0,0 +1,139 @@ +'use strict'; +const fs = require('fs'); +const path = require('path'); +const pify = require('pify'); +const semver = require('semver'); + +const defaults = { + mode: 0o777 & (~process.umask()), + fs +}; + +const useNativeRecursiveOption = semver.satisfies(process.version, '>=10.12.0'); + +// https://github.com/nodejs/node/issues/8987 +// https://github.com/libuv/libuv/pull/1088 +const checkPath = pth => { + if (process.platform === 'win32') { + const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, '')); + + if (pathHasInvalidWinCharacters) { + const error = new Error(`Path contains invalid characters: ${pth}`); + error.code = 'EINVAL'; + throw error; + } + } +}; + +const permissionError = pth => { + // This replicates the exception of `fs.mkdir` with native the + // `recusive` option when run on an invalid drive under Windows. + const error = new Error(`operation not permitted, mkdir '${pth}'`); + error.code = 'EPERM'; + error.errno = -4048; + error.path = pth; + error.syscall = 'mkdir'; + return error; +}; + +const makeDir = (input, options) => Promise.resolve().then(() => { + checkPath(input); + options = Object.assign({}, defaults, options); + + // TODO: Use util.promisify when targeting Node.js 8 + const mkdir = pify(options.fs.mkdir); + const stat = pify(options.fs.stat); + + if (useNativeRecursiveOption && options.fs.mkdir === fs.mkdir) { + const pth = path.resolve(input); + + return mkdir(pth, { + mode: options.mode, + recursive: true + }).then(() => pth); + } + + const make = pth => { + return mkdir(pth, options.mode) + .then(() => pth) + .catch(error => { + if (error.code === 'EPERM') { + throw error; + } + + if (error.code === 'ENOENT') { + if (path.dirname(pth) === pth) { + throw permissionError(pth); + } + + if (error.message.includes('null bytes')) { + throw error; + } + + return make(path.dirname(pth)).then(() => make(pth)); + } + + return stat(pth) + .then(stats => stats.isDirectory() ? pth : Promise.reject()) + .catch(() => { + throw error; + }); + }); + }; + + return make(path.resolve(input)); +}); + +module.exports = makeDir; +module.exports.default = makeDir; + +module.exports.sync = (input, options) => { + checkPath(input); + options = Object.assign({}, defaults, options); + + if (useNativeRecursiveOption && options.fs.mkdirSync === fs.mkdirSync) { + const pth = path.resolve(input); + + fs.mkdirSync(pth, { + mode: options.mode, + recursive: true + }); + + return pth; + } + + const make = pth => { + try { + options.fs.mkdirSync(pth, options.mode); + } catch (error) { + if (error.code === 'EPERM') { + throw error; + } + + if (error.code === 'ENOENT') { + if (path.dirname(pth) === pth) { + throw permissionError(pth); + } + + if (error.message.includes('null bytes')) { + throw error; + } + + make(path.dirname(pth)); + return make(pth); + } + + try { + if (!options.fs.statSync(pth).isDirectory()) { + throw new Error('The path is not a directory'); + } + } catch (_) { + throw error; + } + } + + return pth; + }; + + return make(path.resolve(input)); +}; diff --git a/node_modules/@babel/cli/node_modules/make-dir/license b/node_modules/@babel/cli/node_modules/make-dir/license new file mode 100644 index 000000000..e7af2f771 --- /dev/null +++ b/node_modules/@babel/cli/node_modules/make-dir/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/cli/node_modules/make-dir/package.json b/node_modules/@babel/cli/node_modules/make-dir/package.json new file mode 100644 index 000000000..1b51bf70f --- /dev/null +++ b/node_modules/@babel/cli/node_modules/make-dir/package.json @@ -0,0 +1,59 @@ +{ + "name": "make-dir", + "version": "2.1.0", + "description": "Make a directory and its parents if needed - Think `mkdir -p`", + "license": "MIT", + "repository": "sindresorhus/make-dir", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && nyc ava && tsd-check" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "mkdir", + "mkdirp", + "make", + "directories", + "dir", + "dirs", + "folders", + "directory", + "folder", + "path", + "parent", + "parents", + "intermediate", + "recursively", + "recursive", + "create", + "fs", + "filesystem", + "file-system" + ], + "dependencies": { + "pify": "^4.0.1", + "semver": "^5.6.0" + }, + "devDependencies": { + "@types/graceful-fs": "^4.1.3", + "@types/node": "^11.10.4", + "ava": "^1.2.0", + "codecov": "^3.0.0", + "graceful-fs": "^4.1.11", + "nyc": "^13.1.0", + "path-type": "^3.0.0", + "tempy": "^0.2.1", + "tsd-check": "^0.3.0", + "xo": "^0.24.0" + } +} diff --git a/node_modules/@babel/cli/node_modules/make-dir/readme.md b/node_modules/@babel/cli/node_modules/make-dir/readme.md new file mode 100644 index 000000000..8c225c1f6 --- /dev/null +++ b/node_modules/@babel/cli/node_modules/make-dir/readme.md @@ -0,0 +1,123 @@ +# make-dir [![Build Status](https://travis-ci.org/sindresorhus/make-dir.svg?branch=master)](https://travis-ci.org/sindresorhus/make-dir) [![codecov](https://codecov.io/gh/sindresorhus/make-dir/branch/master/graph/badge.svg)](https://codecov.io/gh/sindresorhus/make-dir) + +> Make a directory and its parents if needed - Think `mkdir -p` + + +## Advantages over [`mkdirp`](https://github.com/substack/node-mkdirp) + +- Promise API *(Async/await ready!)* +- Fixes many `mkdirp` issues: [#96](https://github.com/substack/node-mkdirp/pull/96) [#70](https://github.com/substack/node-mkdirp/issues/70) [#66](https://github.com/substack/node-mkdirp/issues/66) +- 100% test coverage +- CI-tested on macOS, Linux, and Windows +- Actively maintained +- Doesn't bundle a CLI +- Uses native the `fs.mkdir/mkdirSync` [`recursive` option](https://nodejs.org/dist/latest/docs/api/fs.html#fs_fs_mkdir_path_options_callback) in Node.js >=10.12.0 unless [overridden](#fs) + + +## Install + +``` +$ npm install make-dir +``` + + +## Usage + +``` +$ pwd +/Users/sindresorhus/fun +$ tree +. +``` + +```js +const makeDir = require('make-dir'); + +(async () => { + const path = await makeDir('unicorn/rainbow/cake'); + + console.log(path); + //=> '/Users/sindresorhus/fun/unicorn/rainbow/cake' +})(); +``` + +``` +$ tree +. +└── unicorn + └── rainbow + └── cake +``` + +Multiple directories: + +```js +const makeDir = require('make-dir'); + +(async () => { + const paths = await Promise.all([ + makeDir('unicorn/rainbow'), + makeDir('foo/bar') + ]); + + console.log(paths); + /* + [ + '/Users/sindresorhus/fun/unicorn/rainbow', + '/Users/sindresorhus/fun/foo/bar' + ] + */ +})(); +``` + + +## API + +### makeDir(path, [options]) + +Returns a `Promise` for the path to the created directory. + +### makeDir.sync(path, [options]) + +Returns the path to the created directory. + +#### path + +Type: `string` + +Directory to create. + +#### options + +Type: `Object` + +##### mode + +Type: `integer`
+Default: `0o777 & (~process.umask())` + +Directory [permissions](https://x-team.com/blog/file-system-permissions-umask-node-js/). + +##### fs + +Type: `Object`
+Default: `require('fs')` + +Use a custom `fs` implementation. For example [`graceful-fs`](https://github.com/isaacs/node-graceful-fs). + +Using a custom `fs` implementation will block the use of the native `recursive` option if `fs.mkdir` or `fs.mkdirSync` is not the native function. + + +## Related + +- [make-dir-cli](https://github.com/sindresorhus/make-dir-cli) - CLI for this module +- [del](https://github.com/sindresorhus/del) - Delete files and directories +- [globby](https://github.com/sindresorhus/globby) - User-friendly glob matching +- [cpy](https://github.com/sindresorhus/cpy) - Copy files +- [cpy-cli](https://github.com/sindresorhus/cpy-cli) - Copy files on the command-line +- [move-file](https://github.com/sindresorhus/move-file) - Move a file + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/@babel/cli/node_modules/semver/LICENSE b/node_modules/@babel/cli/node_modules/semver/LICENSE new file mode 100644 index 000000000..19129e315 --- /dev/null +++ b/node_modules/@babel/cli/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@babel/cli/node_modules/semver/README.md b/node_modules/@babel/cli/node_modules/semver/README.md new file mode 100644 index 000000000..f8dfa5a0d --- /dev/null +++ b/node_modules/@babel/cli/node_modules/semver/README.md @@ -0,0 +1,412 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Install + +```bash +npm install --save semver +```` + +## Usage + +As a node module: + +```js +const semver = require('semver') + +semver.valid('1.2.3') // '1.2.3' +semver.valid('a.b.c') // null +semver.clean(' =v1.2.3 ') // '1.2.3' +semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true +semver.gt('1.2.3', '9.8.7') // false +semver.lt('1.2.3', '9.8.7') // true +semver.minVersion('>=1.0.0') // '1.0.0' +semver.valid(semver.coerce('v2')) // '2.0.0' +semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' +``` + +As a command-line utility: + +``` +$ semver -h + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them. +``` + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. + +## Ranges + +A `version range` is a set of `comparators` which specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional, but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. The +version `3.4.5` *would* satisfy the range, because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose for this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range matching +semantics. + +Second, a user who has opted into using a prerelease version has +clearly indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +Note that this behavior can be suppressed (treating all prerelease +versions as if they were normal versions, for the purpose of range +matching) by setting the `includePrerelease` flag on the options +object to any +[functions](https://github.com/npm/node-semver#functions) that do +range matching. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta') +// '1.2.4-beta.0' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```bash +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any version satisfies) +* `1.x` := `>=1.0.0 <2.0.0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero digit in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0` +* `^0.2.3` := `>=0.2.3 <0.3.0` +* `^0.0.3` := `>=0.0.3 <0.0.4` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0` +* `^0.0.x` := `>=0.0.0 <0.1.0` +* `^0.0` := `>=0.0.0 <0.1.0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0` +* `^0.x` := `>=0.0.0 <1.0.0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `options` object argument. All +options in this object are `false` by default. The options supported +are: + +- `loose` Be more forgiving about not-quite-valid semver strings. + (Any resulting output will always be 100% strict compliant, of + course.) For backwards compatibility reasons, if the `options` + argument is a boolean value instead of an object, it is interpreted + to be the `loose` param. +- `includePrerelease` Set to suppress the [default + behavior](https://github.com/npm/node-semver#prerelease-tags) of + excluding prerelease tagged versions from ranges unless they are + explicitly opted into. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, release)`: Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, or `prerelease`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, the `prerelease` will work the + same as `prepatch`. It increments the patch version, then makes a + prerelease. If the input version is already a prerelease it simply + increments it. +* `prerelease(v)`: Returns an array of prerelease components, or null + if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. +* `intersects(r1, r2, loose)`: Return true if the two supplied ranges + or comparators intersect. +* `parse(v)`: Attempt to parse a string as a semantic version, returning either + a `SemVer` object or `null`. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the exact same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `diff(v1, v2)`: Returns difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + +### Comparators + +* `intersects(comparator)`: Return true if the comparators intersect + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `minSatisfying(versions, range)`: Return the lowest version in the list + that satisfies the range, or `null` if none of them do. +* `minVersion(range)`: Return the lowest version that can possibly match + the given range. +* `gtr(version, range)`: Return `true` if version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) +* `intersects(range)`: Return true if any of the ranges comparators intersect + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so the version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. + +### Coercion + +* `coerce(version)`: Coerces a string to semver if possible + +This aims to provide a very forgiving translation of a non-semver string to +semver. It looks for the first digit in a string, and consumes all +remaining characters which satisfy at least a partial semver (e.g., `1`, +`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer +versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All +surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes +`3.4.0`). Only text which lacks digits will fail coercion (`version one` +is not valid). The maximum length for any semver component considered for +coercion is 16 characters; longer components will be ignored +(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any +semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value +components are invalid (`9999999999999999.4.7.4` is likely invalid). diff --git a/node_modules/@babel/cli/node_modules/semver/bin/semver b/node_modules/@babel/cli/node_modules/semver/bin/semver new file mode 100755 index 000000000..801e77f13 --- /dev/null +++ b/node_modules/@babel/cli/node_modules/semver/bin/semver @@ -0,0 +1,160 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +var argv = process.argv.slice(2) + +var versions = [] + +var range = [] + +var inc = null + +var version = require('../package.json').version + +var loose = false + +var includePrerelease = false + +var coerce = false + +var identifier + +var semver = require('../semver') + +var reverse = false + +var options = {} + +main() + +function main () { + if (!argv.length) return help() + while (argv.length) { + var a = argv.shift() + var indexOfEqualSign = a.indexOf('=') + if (indexOfEqualSign !== -1) { + a = a.slice(0, indexOfEqualSign) + argv.unshift(a.slice(indexOfEqualSign + 1)) + } + switch (a) { + case '-rv': case '-rev': case '--rev': case '--reverse': + reverse = true + break + case '-l': case '--loose': + loose = true + break + case '-p': case '--include-prerelease': + includePrerelease = true + break + case '-v': case '--version': + versions.push(argv.shift()) + break + case '-i': case '--inc': case '--increment': + switch (argv[0]) { + case 'major': case 'minor': case 'patch': case 'prerelease': + case 'premajor': case 'preminor': case 'prepatch': + inc = argv.shift() + break + default: + inc = 'patch' + break + } + break + case '--preid': + identifier = argv.shift() + break + case '-r': case '--range': + range.push(argv.shift()) + break + case '-c': case '--coerce': + coerce = true + break + case '-h': case '--help': case '-?': + return help() + default: + versions.push(a) + break + } + } + + var options = { loose: loose, includePrerelease: includePrerelease } + + versions = versions.map(function (v) { + return coerce ? (semver.coerce(v) || { version: v }).version : v + }).filter(function (v) { + return semver.valid(v) + }) + if (!versions.length) return fail() + if (inc && (versions.length !== 1 || range.length)) { return failInc() } + + for (var i = 0, l = range.length; i < l; i++) { + versions = versions.filter(function (v) { + return semver.satisfies(v, range[i], options) + }) + if (!versions.length) return fail() + } + return success(versions) +} + +function failInc () { + console.error('--inc can only be used on a single version with no range') + fail() +} + +function fail () { process.exit(1) } + +function success () { + var compare = reverse ? 'rcompare' : 'compare' + versions.sort(function (a, b) { + return semver[compare](a, b, options) + }).map(function (v) { + return semver.clean(v, options) + }).map(function (v) { + return inc ? semver.inc(v, inc, options, identifier) : v + }).forEach(function (v, i, _) { console.log(v) }) +} + +function help () { + console.log(['SemVer ' + version, + '', + 'A JavaScript implementation of the https://semver.org/ specification', + 'Copyright Isaac Z. Schlueter', + '', + 'Usage: semver [options] [ [...]]', + 'Prints valid versions sorted by SemVer precedence', + '', + 'Options:', + '-r --range ', + ' Print versions that match the specified range.', + '', + '-i --increment []', + ' Increment a version by the specified level. Level can', + ' be one of: major, minor, patch, premajor, preminor,', + " prepatch, or prerelease. Default level is 'patch'.", + ' Only one version may be specified.', + '', + '--preid ', + ' Identifier to be used to prefix premajor, preminor,', + ' prepatch or prerelease version increments.', + '', + '-l --loose', + ' Interpret versions and ranges loosely', + '', + '-p --include-prerelease', + ' Always include prerelease versions in range matching', + '', + '-c --coerce', + ' Coerce a string into SemVer if possible', + ' (does not imply --loose)', + '', + 'Program exits successfully if any valid version satisfies', + 'all supplied ranges, and prints all satisfying versions.', + '', + 'If no satisfying versions are found, then exits failure.', + '', + 'Versions are printed in ascending order, so supplying', + 'multiple versions to the utility will just sort them.' + ].join('\n')) +} diff --git a/node_modules/@babel/cli/node_modules/semver/package.json b/node_modules/@babel/cli/node_modules/semver/package.json new file mode 100644 index 000000000..db035e97d --- /dev/null +++ b/node_modules/@babel/cli/node_modules/semver/package.json @@ -0,0 +1,38 @@ +{ + "name": "semver", + "version": "5.7.2", + "description": "The semantic version parser used by npm.", + "main": "semver.js", + "scripts": { + "test": "tap test/ --100 --timeout=30", + "lint": "echo linting disabled", + "postlint": "template-oss-check", + "template-oss-apply": "template-oss-apply --force", + "lintfix": "npm run lint -- --fix", + "snap": "tap test/ --100 --timeout=30", + "posttest": "npm run lint" + }, + "devDependencies": { + "@npmcli/template-oss": "4.17.0", + "tap": "^12.7.0" + }, + "license": "ISC", + "repository": { + "type": "git", + "url": "https://github.com/npm/node-semver.git" + }, + "bin": { + "semver": "./bin/semver" + }, + "files": [ + "bin", + "range.bnf", + "semver.js" + ], + "author": "GitHub Inc.", + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "content": "./scripts/template-oss", + "version": "4.17.0" + } +} diff --git a/node_modules/@babel/cli/node_modules/semver/range.bnf b/node_modules/@babel/cli/node_modules/semver/range.bnf new file mode 100644 index 000000000..d4c6ae0d7 --- /dev/null +++ b/node_modules/@babel/cli/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | [1-9] ( [0-9] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/node_modules/@babel/cli/node_modules/semver/semver.js b/node_modules/@babel/cli/node_modules/semver/semver.js new file mode 100644 index 000000000..dcb683341 --- /dev/null +++ b/node_modules/@babel/cli/node_modules/semver/semver.js @@ -0,0 +1,1525 @@ +exports = module.exports = SemVer + +var debug +/* istanbul ignore next */ +if (typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG)) { + debug = function () { + var args = Array.prototype.slice.call(arguments, 0) + args.unshift('SEMVER') + console.log.apply(console, args) + } +} else { + debug = function () {} +} + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0' + +var MAX_LENGTH = 256 +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +var MAX_SAFE_COMPONENT_LENGTH = 16 + +var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 + +// The actual regexps go on exports.re +var re = exports.re = [] +var safeRe = exports.safeRe = [] +var src = exports.src = [] +var R = 0 + +var LETTERDASHNUMBER = '[a-zA-Z0-9-]' + +// Replace some greedy regex tokens to prevent regex dos issues. These regex are +// used internally via the safeRe object since all inputs in this library get +// normalized first to trim and collapse all extra whitespace. The original +// regexes are exported for userland consumption and lower level usage. A +// future breaking change could export the safer regex only with a note that +// all input should have extra whitespace removed. +var safeRegexReplacements = [ + ['\\s', 1], + ['\\d', MAX_LENGTH], + [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], +] + +function makeSafeRe (value) { + for (var i = 0; i < safeRegexReplacements.length; i++) { + var token = safeRegexReplacements[i][0] + var max = safeRegexReplacements[i][1] + value = value + .split(token + '*').join(token + '{0,' + max + '}') + .split(token + '+').join(token + '{1,' + max + '}') + } + return value +} + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +var NUMERICIDENTIFIER = R++ +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' +var NUMERICIDENTIFIERLOOSE = R++ +src[NUMERICIDENTIFIERLOOSE] = '\\d+' + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +var NONNUMERICIDENTIFIER = R++ +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-]' + LETTERDASHNUMBER + '*' + +// ## Main Version +// Three dot-separated numeric identifiers. + +var MAINVERSION = R++ +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')' + +var MAINVERSIONLOOSE = R++ +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')' + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +var PRERELEASEIDENTIFIER = R++ +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')' + +var PRERELEASEIDENTIFIERLOOSE = R++ +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')' + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +var PRERELEASE = R++ +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' + +var PRERELEASELOOSE = R++ +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +var BUILDIDENTIFIER = R++ +src[BUILDIDENTIFIER] = LETTERDASHNUMBER + '+' + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +var BUILD = R++ +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +var FULL = R++ +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?' + +src[FULL] = '^' + FULLPLAIN + '$' + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?' + +var LOOSE = R++ +src[LOOSE] = '^' + LOOSEPLAIN + '$' + +var GTLT = R++ +src[GTLT] = '((?:<|>)?=?)' + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +var XRANGEIDENTIFIERLOOSE = R++ +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' +var XRANGEIDENTIFIER = R++ +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' + +var XRANGEPLAIN = R++ +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?' + +var XRANGEPLAINLOOSE = R++ +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?' + +var XRANGE = R++ +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' +var XRANGELOOSE = R++ +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +var COERCE = R++ +src[COERCE] = '(?:^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])' + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++ +src[LONETILDE] = '(?:~>?)' + +var TILDETRIM = R++ +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') +safeRe[TILDETRIM] = new RegExp(makeSafeRe(src[TILDETRIM]), 'g') +var tildeTrimReplace = '$1~' + +var TILDE = R++ +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' +var TILDELOOSE = R++ +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++ +src[LONECARET] = '(?:\\^)' + +var CARETTRIM = R++ +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') +safeRe[CARETTRIM] = new RegExp(makeSafeRe(src[CARETTRIM]), 'g') +var caretTrimReplace = '$1^' + +var CARET = R++ +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' +var CARETLOOSE = R++ +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++ +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' +var COMPARATOR = R++ +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++ +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' + +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') +safeRe[COMPARATORTRIM] = new RegExp(makeSafeRe(src[COMPARATORTRIM]), 'g') +var comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +var HYPHENRANGE = R++ +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$' + +var HYPHENRANGELOOSE = R++ +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$' + +// Star ranges basically just allow anything at all. +var STAR = R++ +src[STAR] = '(<|>)?=?\\s*\\*' + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]) + if (!re[i]) { + re[i] = new RegExp(src[i]) + + // Replace all greedy whitespace to prevent regex dos issues. These regex are + // used internally via the safeRe object since all inputs in this library get + // normalized first to trim and collapse all extra whitespace. The original + // regexes are exported for userland consumption and lower level usage. A + // future breaking change could export the safer regex only with a note that + // all input should have extra whitespace removed. + safeRe[i] = new RegExp(makeSafeRe(src[i])) + } +} + +exports.parse = parse +function parse (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + var r = options.loose ? safeRe[LOOSE] : safeRe[FULL] + if (!r.test(version)) { + return null + } + + try { + return new SemVer(version, options) + } catch (er) { + return null + } +} + +exports.valid = valid +function valid (version, options) { + var v = parse(version, options) + return v ? v.version : null +} + +exports.clean = clean +function clean (version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} + +exports.SemVer = SemVer + +function SemVer (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + } + + if (!(this instanceof SemVer)) { + return new SemVer(version, options) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + + var m = version.trim().match(options.loose ? safeRe[LOOSE] : safeRe[FULL]) + + if (!m) { + throw new TypeError('Invalid Version: ' + version) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map(function (id) { + if (/^[0-9]+$/.test(id)) { + var num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() +} + +SemVer.prototype.format = function () { + this.version = this.major + '.' + this.minor + '.' + this.patch + if (this.prerelease.length) { + this.version += '-' + this.prerelease.join('.') + } + return this.version +} + +SemVer.prototype.toString = function () { + return this.version +} + +SemVer.prototype.compare = function (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return this.compareMain(other) || this.comparePre(other) +} + +SemVer.prototype.compareMain = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) +} + +SemVer.prototype.comparePre = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + var i = 0 + do { + var a = this.prerelease[i] + var b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) +} + +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + var i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break + + default: + throw new Error('invalid increment argument: ' + release) + } + this.format() + this.raw = this.version + return this +} + +exports.inc = inc +function inc (version, release, loose, identifier) { + if (typeof (loose) === 'string') { + identifier = loose + loose = undefined + } + + try { + return new SemVer(version, loose).inc(release, identifier).version + } catch (er) { + return null + } +} + +exports.diff = diff +function diff (version1, version2) { + if (eq(version1, version2)) { + return null + } else { + var v1 = parse(version1) + var v2 = parse(version2) + var prefix = '' + if (v1.prerelease.length || v2.prerelease.length) { + prefix = 'pre' + var defaultResult = 'prerelease' + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } +} + +exports.compareIdentifiers = compareIdentifiers + +var numeric = /^[0-9]+$/ +function compareIdentifiers (a, b) { + var anum = numeric.test(a) + var bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +exports.rcompareIdentifiers = rcompareIdentifiers +function rcompareIdentifiers (a, b) { + return compareIdentifiers(b, a) +} + +exports.major = major +function major (a, loose) { + return new SemVer(a, loose).major +} + +exports.minor = minor +function minor (a, loose) { + return new SemVer(a, loose).minor +} + +exports.patch = patch +function patch (a, loose) { + return new SemVer(a, loose).patch +} + +exports.compare = compare +function compare (a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)) +} + +exports.compareLoose = compareLoose +function compareLoose (a, b) { + return compare(a, b, true) +} + +exports.rcompare = rcompare +function rcompare (a, b, loose) { + return compare(b, a, loose) +} + +exports.sort = sort +function sort (list, loose) { + return list.sort(function (a, b) { + return exports.compare(a, b, loose) + }) +} + +exports.rsort = rsort +function rsort (list, loose) { + return list.sort(function (a, b) { + return exports.rcompare(a, b, loose) + }) +} + +exports.gt = gt +function gt (a, b, loose) { + return compare(a, b, loose) > 0 +} + +exports.lt = lt +function lt (a, b, loose) { + return compare(a, b, loose) < 0 +} + +exports.eq = eq +function eq (a, b, loose) { + return compare(a, b, loose) === 0 +} + +exports.neq = neq +function neq (a, b, loose) { + return compare(a, b, loose) !== 0 +} + +exports.gte = gte +function gte (a, b, loose) { + return compare(a, b, loose) >= 0 +} + +exports.lte = lte +function lte (a, b, loose) { + return compare(a, b, loose) <= 0 +} + +exports.cmp = cmp +function cmp (a, op, b, loose) { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError('Invalid operator: ' + op) + } +} + +exports.Comparator = Comparator +function Comparator (comp, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + if (!(this instanceof Comparator)) { + return new Comparator(comp, options) + } + + comp = comp.trim().split(/\s+/).join(' ') + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) +} + +var ANY = {} +Comparator.prototype.parse = function (comp) { + var r = this.options.loose ? safeRe[COMPARATORLOOSE] : safeRe[COMPARATOR] + var m = comp.match(r) + + if (!m) { + throw new TypeError('Invalid comparator: ' + comp) + } + + this.operator = m[1] + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } +} + +Comparator.prototype.toString = function () { + return this.value +} + +Comparator.prototype.test = function (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY) { + return true + } + + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } + + return cmp(version, this.operator, this.semver, this.options) +} + +Comparator.prototype.intersects = function (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + var rangeTmp + + if (this.operator === '') { + rangeTmp = new Range(comp.value, options) + return satisfies(this.value, rangeTmp, options) + } else if (comp.operator === '') { + rangeTmp = new Range(this.value, options) + return satisfies(comp.semver, rangeTmp, options) + } + + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + var sameSemVer = this.semver.version === comp.semver.version + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')) + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')) + + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan +} + +exports.Range = Range +function Range (range, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (range instanceof Range) { + if (range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + return new Range(range.value, options) + } + + if (!(this instanceof Range)) { + return new Range(range, options) + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First reduce all whitespace as much as possible so we do not have to rely + // on potentially slow regexes like \s*. This is then stored and used for + // future error messages as well. + this.raw = range + .trim() + .split(/\s+/) + .join(' ') + + // First, split based on boolean or || + this.set = this.raw.split('||').map(function (range) { + return this.parseRange(range.trim()) + }, this).filter(function (c) { + // throw out any that are not relevant for whatever reason + return c.length + }) + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + this.raw) + } + + this.format() +} + +Range.prototype.format = function () { + this.range = this.set.map(function (comps) { + return comps.join(' ').trim() + }).join('||').trim() + return this.range +} + +Range.prototype.toString = function () { + return this.range +} + +Range.prototype.parseRange = function (range) { + var loose = this.options.loose + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? safeRe[HYPHENRANGELOOSE] : safeRe[HYPHENRANGE] + range = range.replace(hr, hyphenReplace) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(safeRe[COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range, safeRe[COMPARATORTRIM]) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(safeRe[TILDETRIM], tildeTrimReplace) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(safeRe[CARETTRIM], caretTrimReplace) + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + var compRe = loose ? safeRe[COMPARATORLOOSE] : safeRe[COMPARATOR] + var set = range.split(' ').map(function (comp) { + return parseComparator(comp, this.options) + }, this).join(' ').split(/\s+/) + if (this.options.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function (comp) { + return !!comp.match(compRe) + }) + } + set = set.map(function (comp) { + return new Comparator(comp, this.options) + }, this) + + return set +} + +Range.prototype.intersects = function (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some(function (thisComparators) { + return thisComparators.every(function (thisComparator) { + return range.set.some(function (rangeComparators) { + return rangeComparators.every(function (rangeComparator) { + return thisComparator.intersects(rangeComparator, options) + }) + }) + }) + }) +} + +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators +function toComparators (range, options) { + return new Range(range, options).set.map(function (comp) { + return comp.map(function (c) { + return c.value + }).join(' ').trim().split(' ') + }) +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator (comp, options) { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +function isX (id) { + return !id || id.toLowerCase() === 'x' || id === '*' +} + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceTilde(comp, options) + }).join(' ') +} + +function replaceTilde (comp, options) { + var r = options.loose ? safeRe[TILDELOOSE] : safeRe[TILDE] + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr) + var ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else if (pr) { + debug('replaceTilde pr', pr) + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } else { + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceCaret(comp, options) + }).join(' ') +} + +function replaceCaret (comp, options) { + debug('caret', comp, options) + var r = options.loose ? safeRe[CARETLOOSE] : safeRe[CARET] + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr) + var ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + if (M === '0') { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else { + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + (+M + 1) + '.0.0' + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0' + } + } + + debug('caret return', ret) + return ret + }) +} + +function replaceXRanges (comp, options) { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, options) + }).join(' ') +} + +function replaceXRange (comp, options) { + comp = comp.trim() + var r = options.loose ? safeRe[XRANGELOOSE] : safeRe[XRANGE] + return comp.replace(r, function (ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + var xM = isX(M) + var xm = xM || isX(m) + var xp = xm || isX(p) + var anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + ret = gtlt + M + '.' + m + '.' + p + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars (comp, options) { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(safeRe[STAR], '') +} + +// This function is passed to string.replace(safeRe[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = '>=' + fM + '.0.0' + } else if (isX(fp)) { + from = '>=' + fM + '.' + fm + '.0' + } else { + from = '>=' + from + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = '<' + (+tM + 1) + '.0.0' + } else if (isX(tp)) { + to = '<' + tM + '.' + (+tm + 1) + '.0' + } else if (tpr) { + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr + } else { + to = '<=' + to + } + + return (from + ' ' + to).trim() +} + +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false +} + +function testSet (set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} + +exports.satisfies = satisfies +function satisfies (version, range, options) { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} + +exports.maxSatisfying = maxSatisfying +function maxSatisfying (versions, range, options) { + var max = null + var maxSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} + +exports.minSatisfying = minSatisfying +function minSatisfying (versions, range, options) { + var min = null + var minSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} + +exports.minVersion = minVersion +function minVersion (range, loose) { + range = new Range(range, loose) + + var minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + comparators.forEach(function (comparator) { + // Clone to avoid manipulating the comparator's semver object. + var compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!minver || gt(minver, compver)) { + minver = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error('Unexpected operation: ' + comparator.operator) + } + }) + } + + if (minver && range.test(minver)) { + return minver + } + + return null +} + +exports.validRange = validRange +function validRange (range, options) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} + +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr +function ltr (version, range, options) { + return outside(version, range, '<', options) +} + +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr +function gtr (version, range, options) { + return outside(version, range, '>', options) +} + +exports.outside = outside +function outside (version, range, hilo, options) { + version = new SemVer(version, options) + range = new Range(range, options) + + var gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + var high = null + var low = null + + comparators.forEach(function (comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} + +exports.prerelease = prerelease +function prerelease (version, options) { + var parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} + +exports.intersects = intersects +function intersects (r1, r2, options) { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) +} + +exports.coerce = coerce +function coerce (version) { + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + var match = version.match(safeRe[COERCE]) + + if (match == null) { + return null + } + + return parse(match[1] + + '.' + (match[2] || '0') + + '.' + (match[3] || '0')) +} diff --git a/node_modules/@babel/cli/node_modules/slash/index.js b/node_modules/@babel/cli/node_modules/slash/index.js new file mode 100644 index 000000000..75d72501a --- /dev/null +++ b/node_modules/@babel/cli/node_modules/slash/index.js @@ -0,0 +1,11 @@ +'use strict'; +module.exports = input => { + const isExtendedLengthPath = /^\\\\\?\\/.test(input); + const hasNonAscii = /[^\u0000-\u0080]+/.test(input); // eslint-disable-line no-control-regex + + if (isExtendedLengthPath || hasNonAscii) { + return input; + } + + return input.replace(/\\/g, '/'); +}; diff --git a/node_modules/@babel/cli/node_modules/slash/license b/node_modules/@babel/cli/node_modules/slash/license new file mode 100644 index 000000000..e7af2f771 --- /dev/null +++ b/node_modules/@babel/cli/node_modules/slash/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/cli/node_modules/slash/package.json b/node_modules/@babel/cli/node_modules/slash/package.json new file mode 100644 index 000000000..1e360070d --- /dev/null +++ b/node_modules/@babel/cli/node_modules/slash/package.json @@ -0,0 +1,34 @@ +{ + "name": "slash", + "version": "2.0.0", + "description": "Convert Windows backslash paths to slash paths", + "license": "MIT", + "repository": "sindresorhus/slash", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "path", + "seperator", + "sep", + "slash", + "backslash", + "windows", + "win" + ], + "devDependencies": { + "ava": "*", + "xo": "*" + } +} diff --git a/node_modules/@babel/cli/node_modules/slash/readme.md b/node_modules/@babel/cli/node_modules/slash/readme.md new file mode 100644 index 000000000..5e2fedbc9 --- /dev/null +++ b/node_modules/@babel/cli/node_modules/slash/readme.md @@ -0,0 +1,44 @@ +# slash [![Build Status](https://travis-ci.org/sindresorhus/slash.svg?branch=master)](https://travis-ci.org/sindresorhus/slash) + +> Convert Windows backslash paths to slash paths: `foo\\bar` ➔ `foo/bar` + +[Forward-slash paths can be used in Windows](http://superuser.com/a/176395/6877) as long as they're not extended-length paths and don't contain any non-ascii characters. + +This was created since the `path` methods in Node outputs `\\` paths on Windows. + + +## Install + +``` +$ npm install slash +``` + + +## Usage + +```js +const path = require('path'); +const slash = require('slash'); + +const str = path.join('foo', 'bar'); +// Unix => foo/bar +// Windows => foo\\bar + +slash(str); +// Unix => foo/bar +// Windows => foo/bar +``` + + +## API + +### slash(path) + +Type: `string` + +Accepts a Windows backslash path and returns a slash path. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/@babel/cli/package.json b/node_modules/@babel/cli/package.json new file mode 100644 index 000000000..185e69e5f --- /dev/null +++ b/node_modules/@babel/cli/package.json @@ -0,0 +1,57 @@ +{ + "name": "@babel/cli", + "version": "7.24.1", + "description": "Babel command line.", + "author": "The Babel Team (https://babel.dev/team)", + "homepage": "https://babel.dev/docs/en/next/babel-cli", + "bugs": "https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20cli%22+is%3Aopen", + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "https://github.com/babel/babel.git", + "directory": "packages/babel-cli" + }, + "keywords": [ + "6to5", + "babel", + "es6", + "transpile", + "transpiler", + "babel-cli", + "compiler" + ], + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.25", + "commander": "^4.0.1", + "convert-source-map": "^2.0.0", + "fs-readdir-recursive": "^1.1.0", + "glob": "^7.2.0", + "make-dir": "^2.1.0", + "slash": "^2.0.0" + }, + "optionalDependencies": { + "@nicolo-ribaudo/chokidar-2": "2.1.8-no-fsevents.3", + "chokidar": "^3.4.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + }, + "devDependencies": { + "@babel/core": "^7.24.1", + "@babel/helper-transform-fixture-test-runner": "^7.24.1", + "@types/fs-readdir-recursive": "^1.1.0", + "@types/glob": "^7.2.0", + "semver": "^6.3.1" + }, + "bin": { + "babel": "./bin/babel.js", + "babel-external-helpers": "./bin/babel-external-helpers.js" + }, + "engines": { + "node": ">=6.9.0" + }, + "type": "commonjs" +} \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/LICENSE b/node_modules/@jridgewell/resolve-uri/LICENSE new file mode 100644 index 000000000..0a81b2ade --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/LICENSE @@ -0,0 +1,19 @@ +Copyright 2019 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/README.md b/node_modules/@jridgewell/resolve-uri/README.md new file mode 100644 index 000000000..2fe70df77 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/README.md @@ -0,0 +1,40 @@ +# @jridgewell/resolve-uri + +> Resolve a URI relative to an optional base URI + +Resolve any combination of absolute URIs, protocol-realtive URIs, absolute paths, or relative paths. + +## Installation + +```sh +npm install @jridgewell/resolve-uri +``` + +## Usage + +```typescript +function resolve(input: string, base?: string): string; +``` + +```js +import resolve from '@jridgewell/resolve-uri'; + +resolve('foo', 'https://example.com'); // => 'https://example.com/foo' +``` + +| Input | Base | Resolution | Explanation | +|-----------------------|-------------------------|--------------------------------|--------------------------------------------------------------| +| `https://example.com` | _any_ | `https://example.com/` | Input is normalized only | +| `//example.com` | `https://base.com/` | `https://example.com/` | Input inherits the base's protocol | +| `//example.com` | _rest_ | `//example.com/` | Input is normalized only | +| `/example` | `https://base.com/` | `https://base.com/example` | Input inherits the base's origin | +| `/example` | `//base.com/` | `//base.com/example` | Input inherits the base's host and remains protocol relative | +| `/example` | _rest_ | `/example` | Input is normalized only | +| `example` | `https://base.com/dir/` | `https://base.com/dir/example` | Input is joined with the base | +| `example` | `https://base.com/file` | `https://base.com/example` | Input is joined with the base without its file | +| `example` | `//base.com/dir/` | `//base.com/dir/example` | Input is joined with the base's last directory | +| `example` | `//base.com/file` | `//base.com/example` | Input is joined with the base without its file | +| `example` | `/base/dir/` | `/base/dir/example` | Input is joined with the base's last directory | +| `example` | `/base/file` | `/base/example` | Input is joined with the base without its file | +| `example` | `base/dir/` | `base/dir/example` | Input is joined with the base's last directory | +| `example` | `base/file` | `base/example` | Input is joined with the base without its file | diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs new file mode 100644 index 000000000..e958e8817 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs @@ -0,0 +1,232 @@ +// Matches the scheme of a URL, eg "http://" +const schemeRegex = /^[\w+.-]+:\/\//; +/** + * Matches the parts of a URL: + * 1. Scheme, including ":", guaranteed. + * 2. User/password, including "@", optional. + * 3. Host, guaranteed. + * 4. Port, including ":", optional. + * 5. Path, including "/", optional. + * 6. Query, including "?", optional. + * 7. Hash, including "#", optional. + */ +const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; +/** + * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start + * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). + * + * 1. Host, optional. + * 2. Path, which may include "/", guaranteed. + * 3. Query, including "?", optional. + * 4. Hash, including "#", optional. + */ +const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; +function isAbsoluteUrl(input) { + return schemeRegex.test(input); +} +function isSchemeRelativeUrl(input) { + return input.startsWith('//'); +} +function isAbsolutePath(input) { + return input.startsWith('/'); +} +function isFileUrl(input) { + return input.startsWith('file:'); +} +function isRelative(input) { + return /^[.?#]/.test(input); +} +function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); +} +function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); +} +function makeUrl(scheme, user, host, port, path, query, hash) { + return { + scheme, + user, + host, + port, + path, + query, + hash, + type: 7 /* Absolute */, + }; +} +function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = 6 /* SchemeRelative */; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = 5 /* AbsolutePath */; + return url; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl('http://foo.com/' + input); + url.scheme = ''; + url.host = ''; + url.type = input + ? input.startsWith('?') + ? 3 /* Query */ + : input.startsWith('#') + ? 2 /* Hash */ + : 4 /* RelativePath */ + : 1 /* Empty */; + return url; +} +function stripPathFilename(path) { + // If a path ends with a parent directory "..", then it's a relative path with excess parent + // paths. It's not a file, so we can't strip it. + if (path.endsWith('/..')) + return path; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} +function mergePaths(url, base) { + normalizePath(base, base.type); + // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative + // path). + if (url.path === '/') { + url.path = base.path; + } + else { + // Resolution happens relative to the base path's directory, not the file. + url.path = stripPathFilename(base.path) + url.path; + } +} +/** + * The path can have empty directories "//", unneeded parents "foo/..", or current directory + * "foo/.". We need to normalize to a standard representation. + */ +function normalizePath(url, type) { + const rel = type <= 4 /* RelativePath */; + const pieces = url.path.split('/'); + // We need to preserve the first piece always, so that we output a leading slash. The item at + // pieces[0] is an empty string. + let pointer = 1; + // Positive is the number of real directories we've output, used for popping a parent directory. + // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". + let positive = 0; + // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will + // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a + // real directory, we won't need to append, unless the other conditions happen again. + let addTrailingSlash = false; + for (let i = 1; i < pieces.length; i++) { + const piece = pieces[i]; + // An empty directory, could be a trailing slash, or just a double "//" in the path. + if (!piece) { + addTrailingSlash = true; + continue; + } + // If we encounter a real directory, then we don't need to append anymore. + addTrailingSlash = false; + // A current directory, which we can always drop. + if (piece === '.') + continue; + // A parent directory, we need to see if there are any real directories we can pop. Else, we + // have an excess of parents, and we'll need to keep the "..". + if (piece === '..') { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } + else if (rel) { + // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute + // URL, protocol relative URL, or an absolute path, we don't need to keep excess. + pieces[pointer++] = piece; + } + continue; + } + // We've encountered a real directory. Move it to the next insertion pointer, which accounts for + // any popped or dropped directories. + pieces[pointer++] = piece; + positive++; + } + let path = ''; + for (let i = 1; i < pointer; i++) { + path += '/' + pieces[i]; + } + if (!path || (addTrailingSlash && !path.endsWith('/..'))) { + path += '/'; + } + url.path = path; +} +/** + * Attempts to resolve `input` URL/path relative to `base`. + */ +function resolve(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== 7 /* Absolute */) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case 1 /* Empty */: + url.hash = baseUrl.hash; + // fall through + case 2 /* Hash */: + url.query = baseUrl.query; + // fall through + case 3 /* Query */: + case 4 /* RelativePath */: + mergePaths(url, baseUrl); + // fall through + case 5 /* AbsolutePath */: + // The host, user, and port are joined, you can't copy one without the others. + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case 6 /* SchemeRelative */: + // The input doesn't have a schema at least, so we need to copy at least that over. + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case 2 /* Hash */: + case 3 /* Query */: + return queryHash; + case 4 /* RelativePath */: { + // The first char is always a "/", and we need it to be relative. + const path = url.path.slice(1); + if (!path) + return queryHash || '.'; + if (isRelative(base || input) && !isRelative(path)) { + // If base started with a leading ".", or there is no base and input started with a ".", + // then we need to ensure that the relative path starts with a ".". We don't know if + // relative starts with a "..", though, so check before prepending. + return './' + path + queryHash; + } + return path + queryHash; + } + case 5 /* AbsolutePath */: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } +} + +export { resolve as default }; +//# sourceMappingURL=resolve-uri.mjs.map diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map new file mode 100644 index 000000000..1de97d011 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-uri.mjs","sources":["../src/resolve-uri.ts"],"sourcesContent":["// Matches the scheme of a URL, eg \"http://\"\nconst schemeRegex = /^[\\w+.-]+:\\/\\//;\n\n/**\n * Matches the parts of a URL:\n * 1. Scheme, including \":\", guaranteed.\n * 2. User/password, including \"@\", optional.\n * 3. Host, guaranteed.\n * 4. Port, including \":\", optional.\n * 5. Path, including \"/\", optional.\n * 6. Query, including \"?\", optional.\n * 7. Hash, including \"#\", optional.\n */\nconst urlRegex = /^([\\w+.-]+:)\\/\\/([^@/#?]*@)?([^:/#?]*)(:\\d+)?(\\/[^#?]*)?(\\?[^#]*)?(#.*)?/;\n\n/**\n * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start\n * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).\n *\n * 1. Host, optional.\n * 2. Path, which may include \"/\", guaranteed.\n * 3. Query, including \"?\", optional.\n * 4. Hash, including \"#\", optional.\n */\nconst fileRegex = /^file:(?:\\/\\/((?![a-z]:)[^/#?]*)?)?(\\/?[^#?]*)(\\?[^#]*)?(#.*)?/i;\n\ntype Url = {\n scheme: string;\n user: string;\n host: string;\n port: string;\n path: string;\n query: string;\n hash: string;\n type: UrlType;\n};\n\nconst enum UrlType {\n Empty = 1,\n Hash = 2,\n Query = 3,\n RelativePath = 4,\n AbsolutePath = 5,\n SchemeRelative = 6,\n Absolute = 7,\n}\n\nfunction isAbsoluteUrl(input: string): boolean {\n return schemeRegex.test(input);\n}\n\nfunction isSchemeRelativeUrl(input: string): boolean {\n return input.startsWith('//');\n}\n\nfunction isAbsolutePath(input: string): boolean {\n return input.startsWith('/');\n}\n\nfunction isFileUrl(input: string): boolean {\n return input.startsWith('file:');\n}\n\nfunction isRelative(input: string): boolean {\n return /^[.?#]/.test(input);\n}\n\nfunction parseAbsoluteUrl(input: string): Url {\n const match = urlRegex.exec(input)!;\n return makeUrl(\n match[1],\n match[2] || '',\n match[3],\n match[4] || '',\n match[5] || '/',\n match[6] || '',\n match[7] || '',\n );\n}\n\nfunction parseFileUrl(input: string): Url {\n const match = fileRegex.exec(input)!;\n const path = match[2];\n return makeUrl(\n 'file:',\n '',\n match[1] || '',\n '',\n isAbsolutePath(path) ? path : '/' + path,\n match[3] || '',\n match[4] || '',\n );\n}\n\nfunction makeUrl(\n scheme: string,\n user: string,\n host: string,\n port: string,\n path: string,\n query: string,\n hash: string,\n): Url {\n return {\n scheme,\n user,\n host,\n port,\n path,\n query,\n hash,\n type: UrlType.Absolute,\n };\n}\n\nfunction parseUrl(input: string): Url {\n if (isSchemeRelativeUrl(input)) {\n const url = parseAbsoluteUrl('http:' + input);\n url.scheme = '';\n url.type = UrlType.SchemeRelative;\n return url;\n }\n\n if (isAbsolutePath(input)) {\n const url = parseAbsoluteUrl('http://foo.com' + input);\n url.scheme = '';\n url.host = '';\n url.type = UrlType.AbsolutePath;\n return url;\n }\n\n if (isFileUrl(input)) return parseFileUrl(input);\n\n if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);\n\n const url = parseAbsoluteUrl('http://foo.com/' + input);\n url.scheme = '';\n url.host = '';\n url.type = input\n ? input.startsWith('?')\n ? UrlType.Query\n : input.startsWith('#')\n ? UrlType.Hash\n : UrlType.RelativePath\n : UrlType.Empty;\n return url;\n}\n\nfunction stripPathFilename(path: string): string {\n // If a path ends with a parent directory \"..\", then it's a relative path with excess parent\n // paths. It's not a file, so we can't strip it.\n if (path.endsWith('/..')) return path;\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n\nfunction mergePaths(url: Url, base: Url) {\n normalizePath(base, base.type);\n\n // If the path is just a \"/\", then it was an empty path to begin with (remember, we're a relative\n // path).\n if (url.path === '/') {\n url.path = base.path;\n } else {\n // Resolution happens relative to the base path's directory, not the file.\n url.path = stripPathFilename(base.path) + url.path;\n }\n}\n\n/**\n * The path can have empty directories \"//\", unneeded parents \"foo/..\", or current directory\n * \"foo/.\". We need to normalize to a standard representation.\n */\nfunction normalizePath(url: Url, type: UrlType) {\n const rel = type <= UrlType.RelativePath;\n const pieces = url.path.split('/');\n\n // We need to preserve the first piece always, so that we output a leading slash. The item at\n // pieces[0] is an empty string.\n let pointer = 1;\n\n // Positive is the number of real directories we've output, used for popping a parent directory.\n // Eg, \"foo/bar/..\" will have a positive 2, and we can decrement to be left with just \"foo\".\n let positive = 0;\n\n // We need to keep a trailing slash if we encounter an empty directory (eg, splitting \"foo/\" will\n // generate `[\"foo\", \"\"]` pieces). And, if we pop a parent directory. But once we encounter a\n // real directory, we won't need to append, unless the other conditions happen again.\n let addTrailingSlash = false;\n\n for (let i = 1; i < pieces.length; i++) {\n const piece = pieces[i];\n\n // An empty directory, could be a trailing slash, or just a double \"//\" in the path.\n if (!piece) {\n addTrailingSlash = true;\n continue;\n }\n\n // If we encounter a real directory, then we don't need to append anymore.\n addTrailingSlash = false;\n\n // A current directory, which we can always drop.\n if (piece === '.') continue;\n\n // A parent directory, we need to see if there are any real directories we can pop. Else, we\n // have an excess of parents, and we'll need to keep the \"..\".\n if (piece === '..') {\n if (positive) {\n addTrailingSlash = true;\n positive--;\n pointer--;\n } else if (rel) {\n // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute\n // URL, protocol relative URL, or an absolute path, we don't need to keep excess.\n pieces[pointer++] = piece;\n }\n continue;\n }\n\n // We've encountered a real directory. Move it to the next insertion pointer, which accounts for\n // any popped or dropped directories.\n pieces[pointer++] = piece;\n positive++;\n }\n\n let path = '';\n for (let i = 1; i < pointer; i++) {\n path += '/' + pieces[i];\n }\n if (!path || (addTrailingSlash && !path.endsWith('/..'))) {\n path += '/';\n }\n url.path = path;\n}\n\n/**\n * Attempts to resolve `input` URL/path relative to `base`.\n */\nexport default function resolve(input: string, base: string | undefined): string {\n if (!input && !base) return '';\n\n const url = parseUrl(input);\n let inputType = url.type;\n\n if (base && inputType !== UrlType.Absolute) {\n const baseUrl = parseUrl(base);\n const baseType = baseUrl.type;\n\n switch (inputType) {\n case UrlType.Empty:\n url.hash = baseUrl.hash;\n // fall through\n\n case UrlType.Hash:\n url.query = baseUrl.query;\n // fall through\n\n case UrlType.Query:\n case UrlType.RelativePath:\n mergePaths(url, baseUrl);\n // fall through\n\n case UrlType.AbsolutePath:\n // The host, user, and port are joined, you can't copy one without the others.\n url.user = baseUrl.user;\n url.host = baseUrl.host;\n url.port = baseUrl.port;\n // fall through\n\n case UrlType.SchemeRelative:\n // The input doesn't have a schema at least, so we need to copy at least that over.\n url.scheme = baseUrl.scheme;\n }\n if (baseType > inputType) inputType = baseType;\n }\n\n normalizePath(url, inputType);\n\n const queryHash = url.query + url.hash;\n switch (inputType) {\n // This is impossible, because of the empty checks at the start of the function.\n // case UrlType.Empty:\n\n case UrlType.Hash:\n case UrlType.Query:\n return queryHash;\n\n case UrlType.RelativePath: {\n // The first char is always a \"/\", and we need it to be relative.\n const path = url.path.slice(1);\n\n if (!path) return queryHash || '.';\n\n if (isRelative(base || input) && !isRelative(path)) {\n // If base started with a leading \".\", or there is no base and input started with a \".\",\n // then we need to ensure that the relative path starts with a \".\". We don't know if\n // relative starts with a \"..\", though, so check before prepending.\n return './' + path + queryHash;\n }\n\n return path + queryHash;\n }\n\n case UrlType.AbsolutePath:\n return url.path + queryHash;\n\n default:\n return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;\n }\n}\n"],"names":[],"mappings":"AAAA;AACA,MAAM,WAAW,GAAG,gBAAgB,CAAC;AAErC;;;;;;;;;;AAUA,MAAM,QAAQ,GAAG,0EAA0E,CAAC;AAE5F;;;;;;;;;AASA,MAAM,SAAS,GAAG,iEAAiE,CAAC;AAuBpF,SAAS,aAAa,CAAC,KAAa;IAClC,OAAO,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACjC,CAAC;AAED,SAAS,mBAAmB,CAAC,KAAa;IACxC,OAAO,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;AAChC,CAAC;AAED,SAAS,cAAc,CAAC,KAAa;IACnC,OAAO,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;AAC/B,CAAC;AAED,SAAS,SAAS,CAAC,KAAa;IAC9B,OAAO,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;AACnC,CAAC;AAED,SAAS,UAAU,CAAC,KAAa;IAC/B,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC9B,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAa;IACrC,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAE,CAAC;IACpC,OAAO,OAAO,CACZ,KAAK,CAAC,CAAC,CAAC,EACR,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,CAAC,CAAC,CAAC,EACR,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,CAAC,CAAC,CAAC,IAAI,GAAG,EACf,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CACf,CAAC;AACJ,CAAC;AAED,SAAS,YAAY,CAAC,KAAa;IACjC,MAAM,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,KAAK,CAAE,CAAC;IACrC,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IACtB,OAAO,OAAO,CACZ,OAAO,EACP,EAAE,EACF,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,EAAE,EACF,cAAc,CAAC,IAAI,CAAC,GAAG,IAAI,GAAG,GAAG,GAAG,IAAI,EACxC,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CACf,CAAC;AACJ,CAAC;AAED,SAAS,OAAO,CACd,MAAc,EACd,IAAY,EACZ,IAAY,EACZ,IAAY,EACZ,IAAY,EACZ,KAAa,EACb,IAAY;IAEZ,OAAO;QACL,MAAM;QACN,IAAI;QACJ,IAAI;QACJ,IAAI;QACJ,IAAI;QACJ,KAAK;QACL,IAAI;QACJ,IAAI;KACL,CAAC;AACJ,CAAC;AAED,SAAS,QAAQ,CAAC,KAAa;IAC7B,IAAI,mBAAmB,CAAC,KAAK,CAAC,EAAE;QAC9B,MAAM,GAAG,GAAG,gBAAgB,CAAC,OAAO,GAAG,KAAK,CAAC,CAAC;QAC9C,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC;QAChB,GAAG,CAAC,IAAI,0BAA0B;QAClC,OAAO,GAAG,CAAC;KACZ;IAED,IAAI,cAAc,CAAC,KAAK,CAAC,EAAE;QACzB,MAAM,GAAG,GAAG,gBAAgB,CAAC,gBAAgB,GAAG,KAAK,CAAC,CAAC;QACvD,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC;QAChB,GAAG,CAAC,IAAI,GAAG,EAAE,CAAC;QACd,GAAG,CAAC,IAAI,wBAAwB;QAChC,OAAO,GAAG,CAAC;KACZ;IAED,IAAI,SAAS,CAAC,KAAK,CAAC;QAAE,OAAO,YAAY,CAAC,KAAK,CAAC,CAAC;IAEjD,IAAI,aAAa,CAAC,KAAK,CAAC;QAAE,OAAO,gBAAgB,CAAC,KAAK,CAAC,CAAC;IAEzD,MAAM,GAAG,GAAG,gBAAgB,CAAC,iBAAiB,GAAG,KAAK,CAAC,CAAC;IACxD,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC;IAChB,GAAG,CAAC,IAAI,GAAG,EAAE,CAAC;IACd,GAAG,CAAC,IAAI,GAAG,KAAK;UACZ,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC;;cAEnB,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC;;;wBAGT;IAClB,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,iBAAiB,CAAC,IAAY;;;IAGrC,IAAI,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACtC,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;IACpC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;AAClC,CAAC;AAED,SAAS,UAAU,CAAC,GAAQ,EAAE,IAAS;IACrC,aAAa,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;;;IAI/B,IAAI,GAAG,CAAC,IAAI,KAAK,GAAG,EAAE;QACpB,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;KACtB;SAAM;;QAEL,GAAG,CAAC,IAAI,GAAG,iBAAiB,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC,IAAI,CAAC;KACpD;AACH,CAAC;AAED;;;;AAIA,SAAS,aAAa,CAAC,GAAQ,EAAE,IAAa;IAC5C,MAAM,GAAG,GAAG,IAAI,yBAAyB;IACzC,MAAM,MAAM,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;;;IAInC,IAAI,OAAO,GAAG,CAAC,CAAC;;;IAIhB,IAAI,QAAQ,GAAG,CAAC,CAAC;;;;IAKjB,IAAI,gBAAgB,GAAG,KAAK,CAAC;IAE7B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACtC,MAAM,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;;QAGxB,IAAI,CAAC,KAAK,EAAE;YACV,gBAAgB,GAAG,IAAI,CAAC;YACxB,SAAS;SACV;;QAGD,gBAAgB,GAAG,KAAK,CAAC;;QAGzB,IAAI,KAAK,KAAK,GAAG;YAAE,SAAS;;;QAI5B,IAAI,KAAK,KAAK,IAAI,EAAE;YAClB,IAAI,QAAQ,EAAE;gBACZ,gBAAgB,GAAG,IAAI,CAAC;gBACxB,QAAQ,EAAE,CAAC;gBACX,OAAO,EAAE,CAAC;aACX;iBAAM,IAAI,GAAG,EAAE;;;gBAGd,MAAM,CAAC,OAAO,EAAE,CAAC,GAAG,KAAK,CAAC;aAC3B;YACD,SAAS;SACV;;;QAID,MAAM,CAAC,OAAO,EAAE,CAAC,GAAG,KAAK,CAAC;QAC1B,QAAQ,EAAE,CAAC;KACZ;IAED,IAAI,IAAI,GAAG,EAAE,CAAC;IACd,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,EAAE,CAAC,EAAE,EAAE;QAChC,IAAI,IAAI,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;KACzB;IACD,IAAI,CAAC,IAAI,KAAK,gBAAgB,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE;QACxD,IAAI,IAAI,GAAG,CAAC;KACb;IACD,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC;AAClB,CAAC;AAED;;;SAGwB,OAAO,CAAC,KAAa,EAAE,IAAwB;IACrE,IAAI,CAAC,KAAK,IAAI,CAAC,IAAI;QAAE,OAAO,EAAE,CAAC;IAE/B,MAAM,GAAG,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC5B,IAAI,SAAS,GAAG,GAAG,CAAC,IAAI,CAAC;IAEzB,IAAI,IAAI,IAAI,SAAS,uBAAuB;QAC1C,MAAM,OAAO,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;QAC/B,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;QAE9B,QAAQ,SAAS;YACf;gBACE,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;;YAG1B;gBACE,GAAG,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;;YAG5B,mBAAmB;YACnB;gBACE,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;;YAG3B;;gBAEE,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;gBACxB,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;gBACxB,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;;YAG1B;;gBAEE,GAAG,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;SAC/B;QACD,IAAI,QAAQ,GAAG,SAAS;YAAE,SAAS,GAAG,QAAQ,CAAC;KAChD;IAED,aAAa,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;IAE9B,MAAM,SAAS,GAAG,GAAG,CAAC,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC;IACvC,QAAQ,SAAS;;;QAIf,kBAAkB;QAClB;YACE,OAAO,SAAS,CAAC;QAEnB,2BAA2B;;YAEzB,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAE/B,IAAI,CAAC,IAAI;gBAAE,OAAO,SAAS,IAAI,GAAG,CAAC;YAEnC,IAAI,UAAU,CAAC,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;;;;gBAIlD,OAAO,IAAI,GAAG,IAAI,GAAG,SAAS,CAAC;aAChC;YAED,OAAO,IAAI,GAAG,SAAS,CAAC;SACzB;QAED;YACE,OAAO,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;QAE9B;YACE,OAAO,GAAG,CAAC,MAAM,GAAG,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;KACpF;AACH;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js new file mode 100644 index 000000000..a783049b0 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js @@ -0,0 +1,240 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.resolveURI = factory()); +})(this, (function () { 'use strict'; + + // Matches the scheme of a URL, eg "http://" + const schemeRegex = /^[\w+.-]+:\/\//; + /** + * Matches the parts of a URL: + * 1. Scheme, including ":", guaranteed. + * 2. User/password, including "@", optional. + * 3. Host, guaranteed. + * 4. Port, including ":", optional. + * 5. Path, including "/", optional. + * 6. Query, including "?", optional. + * 7. Hash, including "#", optional. + */ + const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; + /** + * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start + * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). + * + * 1. Host, optional. + * 2. Path, which may include "/", guaranteed. + * 3. Query, including "?", optional. + * 4. Hash, including "#", optional. + */ + const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; + function isAbsoluteUrl(input) { + return schemeRegex.test(input); + } + function isSchemeRelativeUrl(input) { + return input.startsWith('//'); + } + function isAbsolutePath(input) { + return input.startsWith('/'); + } + function isFileUrl(input) { + return input.startsWith('file:'); + } + function isRelative(input) { + return /^[.?#]/.test(input); + } + function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); + } + function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); + } + function makeUrl(scheme, user, host, port, path, query, hash) { + return { + scheme, + user, + host, + port, + path, + query, + hash, + type: 7 /* Absolute */, + }; + } + function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = 6 /* SchemeRelative */; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = 5 /* AbsolutePath */; + return url; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl('http://foo.com/' + input); + url.scheme = ''; + url.host = ''; + url.type = input + ? input.startsWith('?') + ? 3 /* Query */ + : input.startsWith('#') + ? 2 /* Hash */ + : 4 /* RelativePath */ + : 1 /* Empty */; + return url; + } + function stripPathFilename(path) { + // If a path ends with a parent directory "..", then it's a relative path with excess parent + // paths. It's not a file, so we can't strip it. + if (path.endsWith('/..')) + return path; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); + } + function mergePaths(url, base) { + normalizePath(base, base.type); + // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative + // path). + if (url.path === '/') { + url.path = base.path; + } + else { + // Resolution happens relative to the base path's directory, not the file. + url.path = stripPathFilename(base.path) + url.path; + } + } + /** + * The path can have empty directories "//", unneeded parents "foo/..", or current directory + * "foo/.". We need to normalize to a standard representation. + */ + function normalizePath(url, type) { + const rel = type <= 4 /* RelativePath */; + const pieces = url.path.split('/'); + // We need to preserve the first piece always, so that we output a leading slash. The item at + // pieces[0] is an empty string. + let pointer = 1; + // Positive is the number of real directories we've output, used for popping a parent directory. + // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". + let positive = 0; + // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will + // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a + // real directory, we won't need to append, unless the other conditions happen again. + let addTrailingSlash = false; + for (let i = 1; i < pieces.length; i++) { + const piece = pieces[i]; + // An empty directory, could be a trailing slash, or just a double "//" in the path. + if (!piece) { + addTrailingSlash = true; + continue; + } + // If we encounter a real directory, then we don't need to append anymore. + addTrailingSlash = false; + // A current directory, which we can always drop. + if (piece === '.') + continue; + // A parent directory, we need to see if there are any real directories we can pop. Else, we + // have an excess of parents, and we'll need to keep the "..". + if (piece === '..') { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } + else if (rel) { + // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute + // URL, protocol relative URL, or an absolute path, we don't need to keep excess. + pieces[pointer++] = piece; + } + continue; + } + // We've encountered a real directory. Move it to the next insertion pointer, which accounts for + // any popped or dropped directories. + pieces[pointer++] = piece; + positive++; + } + let path = ''; + for (let i = 1; i < pointer; i++) { + path += '/' + pieces[i]; + } + if (!path || (addTrailingSlash && !path.endsWith('/..'))) { + path += '/'; + } + url.path = path; + } + /** + * Attempts to resolve `input` URL/path relative to `base`. + */ + function resolve(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== 7 /* Absolute */) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case 1 /* Empty */: + url.hash = baseUrl.hash; + // fall through + case 2 /* Hash */: + url.query = baseUrl.query; + // fall through + case 3 /* Query */: + case 4 /* RelativePath */: + mergePaths(url, baseUrl); + // fall through + case 5 /* AbsolutePath */: + // The host, user, and port are joined, you can't copy one without the others. + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case 6 /* SchemeRelative */: + // The input doesn't have a schema at least, so we need to copy at least that over. + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case 2 /* Hash */: + case 3 /* Query */: + return queryHash; + case 4 /* RelativePath */: { + // The first char is always a "/", and we need it to be relative. + const path = url.path.slice(1); + if (!path) + return queryHash || '.'; + if (isRelative(base || input) && !isRelative(path)) { + // If base started with a leading ".", or there is no base and input started with a ".", + // then we need to ensure that the relative path starts with a ".". We don't know if + // relative starts with a "..", though, so check before prepending. + return './' + path + queryHash; + } + return path + queryHash; + } + case 5 /* AbsolutePath */: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } + } + + return resolve; + +})); +//# sourceMappingURL=resolve-uri.umd.js.map diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map new file mode 100644 index 000000000..70a37f21d --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-uri.umd.js","sources":["../src/resolve-uri.ts"],"sourcesContent":["// Matches the scheme of a URL, eg \"http://\"\nconst schemeRegex = /^[\\w+.-]+:\\/\\//;\n\n/**\n * Matches the parts of a URL:\n * 1. Scheme, including \":\", guaranteed.\n * 2. User/password, including \"@\", optional.\n * 3. Host, guaranteed.\n * 4. Port, including \":\", optional.\n * 5. Path, including \"/\", optional.\n * 6. Query, including \"?\", optional.\n * 7. Hash, including \"#\", optional.\n */\nconst urlRegex = /^([\\w+.-]+:)\\/\\/([^@/#?]*@)?([^:/#?]*)(:\\d+)?(\\/[^#?]*)?(\\?[^#]*)?(#.*)?/;\n\n/**\n * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start\n * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).\n *\n * 1. Host, optional.\n * 2. Path, which may include \"/\", guaranteed.\n * 3. Query, including \"?\", optional.\n * 4. Hash, including \"#\", optional.\n */\nconst fileRegex = /^file:(?:\\/\\/((?![a-z]:)[^/#?]*)?)?(\\/?[^#?]*)(\\?[^#]*)?(#.*)?/i;\n\ntype Url = {\n scheme: string;\n user: string;\n host: string;\n port: string;\n path: string;\n query: string;\n hash: string;\n type: UrlType;\n};\n\nconst enum UrlType {\n Empty = 1,\n Hash = 2,\n Query = 3,\n RelativePath = 4,\n AbsolutePath = 5,\n SchemeRelative = 6,\n Absolute = 7,\n}\n\nfunction isAbsoluteUrl(input: string): boolean {\n return schemeRegex.test(input);\n}\n\nfunction isSchemeRelativeUrl(input: string): boolean {\n return input.startsWith('//');\n}\n\nfunction isAbsolutePath(input: string): boolean {\n return input.startsWith('/');\n}\n\nfunction isFileUrl(input: string): boolean {\n return input.startsWith('file:');\n}\n\nfunction isRelative(input: string): boolean {\n return /^[.?#]/.test(input);\n}\n\nfunction parseAbsoluteUrl(input: string): Url {\n const match = urlRegex.exec(input)!;\n return makeUrl(\n match[1],\n match[2] || '',\n match[3],\n match[4] || '',\n match[5] || '/',\n match[6] || '',\n match[7] || '',\n );\n}\n\nfunction parseFileUrl(input: string): Url {\n const match = fileRegex.exec(input)!;\n const path = match[2];\n return makeUrl(\n 'file:',\n '',\n match[1] || '',\n '',\n isAbsolutePath(path) ? path : '/' + path,\n match[3] || '',\n match[4] || '',\n );\n}\n\nfunction makeUrl(\n scheme: string,\n user: string,\n host: string,\n port: string,\n path: string,\n query: string,\n hash: string,\n): Url {\n return {\n scheme,\n user,\n host,\n port,\n path,\n query,\n hash,\n type: UrlType.Absolute,\n };\n}\n\nfunction parseUrl(input: string): Url {\n if (isSchemeRelativeUrl(input)) {\n const url = parseAbsoluteUrl('http:' + input);\n url.scheme = '';\n url.type = UrlType.SchemeRelative;\n return url;\n }\n\n if (isAbsolutePath(input)) {\n const url = parseAbsoluteUrl('http://foo.com' + input);\n url.scheme = '';\n url.host = '';\n url.type = UrlType.AbsolutePath;\n return url;\n }\n\n if (isFileUrl(input)) return parseFileUrl(input);\n\n if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);\n\n const url = parseAbsoluteUrl('http://foo.com/' + input);\n url.scheme = '';\n url.host = '';\n url.type = input\n ? input.startsWith('?')\n ? UrlType.Query\n : input.startsWith('#')\n ? UrlType.Hash\n : UrlType.RelativePath\n : UrlType.Empty;\n return url;\n}\n\nfunction stripPathFilename(path: string): string {\n // If a path ends with a parent directory \"..\", then it's a relative path with excess parent\n // paths. It's not a file, so we can't strip it.\n if (path.endsWith('/..')) return path;\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n\nfunction mergePaths(url: Url, base: Url) {\n normalizePath(base, base.type);\n\n // If the path is just a \"/\", then it was an empty path to begin with (remember, we're a relative\n // path).\n if (url.path === '/') {\n url.path = base.path;\n } else {\n // Resolution happens relative to the base path's directory, not the file.\n url.path = stripPathFilename(base.path) + url.path;\n }\n}\n\n/**\n * The path can have empty directories \"//\", unneeded parents \"foo/..\", or current directory\n * \"foo/.\". We need to normalize to a standard representation.\n */\nfunction normalizePath(url: Url, type: UrlType) {\n const rel = type <= UrlType.RelativePath;\n const pieces = url.path.split('/');\n\n // We need to preserve the first piece always, so that we output a leading slash. The item at\n // pieces[0] is an empty string.\n let pointer = 1;\n\n // Positive is the number of real directories we've output, used for popping a parent directory.\n // Eg, \"foo/bar/..\" will have a positive 2, and we can decrement to be left with just \"foo\".\n let positive = 0;\n\n // We need to keep a trailing slash if we encounter an empty directory (eg, splitting \"foo/\" will\n // generate `[\"foo\", \"\"]` pieces). And, if we pop a parent directory. But once we encounter a\n // real directory, we won't need to append, unless the other conditions happen again.\n let addTrailingSlash = false;\n\n for (let i = 1; i < pieces.length; i++) {\n const piece = pieces[i];\n\n // An empty directory, could be a trailing slash, or just a double \"//\" in the path.\n if (!piece) {\n addTrailingSlash = true;\n continue;\n }\n\n // If we encounter a real directory, then we don't need to append anymore.\n addTrailingSlash = false;\n\n // A current directory, which we can always drop.\n if (piece === '.') continue;\n\n // A parent directory, we need to see if there are any real directories we can pop. Else, we\n // have an excess of parents, and we'll need to keep the \"..\".\n if (piece === '..') {\n if (positive) {\n addTrailingSlash = true;\n positive--;\n pointer--;\n } else if (rel) {\n // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute\n // URL, protocol relative URL, or an absolute path, we don't need to keep excess.\n pieces[pointer++] = piece;\n }\n continue;\n }\n\n // We've encountered a real directory. Move it to the next insertion pointer, which accounts for\n // any popped or dropped directories.\n pieces[pointer++] = piece;\n positive++;\n }\n\n let path = '';\n for (let i = 1; i < pointer; i++) {\n path += '/' + pieces[i];\n }\n if (!path || (addTrailingSlash && !path.endsWith('/..'))) {\n path += '/';\n }\n url.path = path;\n}\n\n/**\n * Attempts to resolve `input` URL/path relative to `base`.\n */\nexport default function resolve(input: string, base: string | undefined): string {\n if (!input && !base) return '';\n\n const url = parseUrl(input);\n let inputType = url.type;\n\n if (base && inputType !== UrlType.Absolute) {\n const baseUrl = parseUrl(base);\n const baseType = baseUrl.type;\n\n switch (inputType) {\n case UrlType.Empty:\n url.hash = baseUrl.hash;\n // fall through\n\n case UrlType.Hash:\n url.query = baseUrl.query;\n // fall through\n\n case UrlType.Query:\n case UrlType.RelativePath:\n mergePaths(url, baseUrl);\n // fall through\n\n case UrlType.AbsolutePath:\n // The host, user, and port are joined, you can't copy one without the others.\n url.user = baseUrl.user;\n url.host = baseUrl.host;\n url.port = baseUrl.port;\n // fall through\n\n case UrlType.SchemeRelative:\n // The input doesn't have a schema at least, so we need to copy at least that over.\n url.scheme = baseUrl.scheme;\n }\n if (baseType > inputType) inputType = baseType;\n }\n\n normalizePath(url, inputType);\n\n const queryHash = url.query + url.hash;\n switch (inputType) {\n // This is impossible, because of the empty checks at the start of the function.\n // case UrlType.Empty:\n\n case UrlType.Hash:\n case UrlType.Query:\n return queryHash;\n\n case UrlType.RelativePath: {\n // The first char is always a \"/\", and we need it to be relative.\n const path = url.path.slice(1);\n\n if (!path) return queryHash || '.';\n\n if (isRelative(base || input) && !isRelative(path)) {\n // If base started with a leading \".\", or there is no base and input started with a \".\",\n // then we need to ensure that the relative path starts with a \".\". We don't know if\n // relative starts with a \"..\", though, so check before prepending.\n return './' + path + queryHash;\n }\n\n return path + queryHash;\n }\n\n case UrlType.AbsolutePath:\n return url.path + queryHash;\n\n default:\n return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;\n }\n}\n"],"names":[],"mappings":";;;;;;IAAA;IACA,MAAM,WAAW,GAAG,gBAAgB,CAAC;IAErC;;;;;;;;;;IAUA,MAAM,QAAQ,GAAG,0EAA0E,CAAC;IAE5F;;;;;;;;;IASA,MAAM,SAAS,GAAG,iEAAiE,CAAC;IAuBpF,SAAS,aAAa,CAAC,KAAa;QAClC,OAAO,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;IAED,SAAS,mBAAmB,CAAC,KAAa;QACxC,OAAO,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IAChC,CAAC;IAED,SAAS,cAAc,CAAC,KAAa;QACnC,OAAO,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;IAC/B,CAAC;IAED,SAAS,SAAS,CAAC,KAAa;QAC9B,OAAO,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IACnC,CAAC;IAED,SAAS,UAAU,CAAC,KAAa;QAC/B,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;IAED,SAAS,gBAAgB,CAAC,KAAa;QACrC,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAE,CAAC;QACpC,OAAO,OAAO,CACZ,KAAK,CAAC,CAAC,CAAC,EACR,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,CAAC,CAAC,CAAC,EACR,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,CAAC,CAAC,CAAC,IAAI,GAAG,EACf,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CACf,CAAC;IACJ,CAAC;IAED,SAAS,YAAY,CAAC,KAAa;QACjC,MAAM,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,KAAK,CAAE,CAAC;QACrC,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QACtB,OAAO,OAAO,CACZ,OAAO,EACP,EAAE,EACF,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,EAAE,EACF,cAAc,CAAC,IAAI,CAAC,GAAG,IAAI,GAAG,GAAG,GAAG,IAAI,EACxC,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CACf,CAAC;IACJ,CAAC;IAED,SAAS,OAAO,CACd,MAAc,EACd,IAAY,EACZ,IAAY,EACZ,IAAY,EACZ,IAAY,EACZ,KAAa,EACb,IAAY;QAEZ,OAAO;YACL,MAAM;YACN,IAAI;YACJ,IAAI;YACJ,IAAI;YACJ,IAAI;YACJ,KAAK;YACL,IAAI;YACJ,IAAI;SACL,CAAC;IACJ,CAAC;IAED,SAAS,QAAQ,CAAC,KAAa;QAC7B,IAAI,mBAAmB,CAAC,KAAK,CAAC,EAAE;YAC9B,MAAM,GAAG,GAAG,gBAAgB,CAAC,OAAO,GAAG,KAAK,CAAC,CAAC;YAC9C,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC;YAChB,GAAG,CAAC,IAAI,0BAA0B;YAClC,OAAO,GAAG,CAAC;SACZ;QAED,IAAI,cAAc,CAAC,KAAK,CAAC,EAAE;YACzB,MAAM,GAAG,GAAG,gBAAgB,CAAC,gBAAgB,GAAG,KAAK,CAAC,CAAC;YACvD,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC;YAChB,GAAG,CAAC,IAAI,GAAG,EAAE,CAAC;YACd,GAAG,CAAC,IAAI,wBAAwB;YAChC,OAAO,GAAG,CAAC;SACZ;QAED,IAAI,SAAS,CAAC,KAAK,CAAC;YAAE,OAAO,YAAY,CAAC,KAAK,CAAC,CAAC;QAEjD,IAAI,aAAa,CAAC,KAAK,CAAC;YAAE,OAAO,gBAAgB,CAAC,KAAK,CAAC,CAAC;QAEzD,MAAM,GAAG,GAAG,gBAAgB,CAAC,iBAAiB,GAAG,KAAK,CAAC,CAAC;QACxD,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC;QAChB,GAAG,CAAC,IAAI,GAAG,EAAE,CAAC;QACd,GAAG,CAAC,IAAI,GAAG,KAAK;cACZ,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC;;kBAEnB,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC;;;4BAGT;QAClB,OAAO,GAAG,CAAC;IACb,CAAC;IAED,SAAS,iBAAiB,CAAC,IAAY;;;QAGrC,IAAI,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QACtC,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;QACpC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;IAClC,CAAC;IAED,SAAS,UAAU,CAAC,GAAQ,EAAE,IAAS;QACrC,aAAa,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;;;QAI/B,IAAI,GAAG,CAAC,IAAI,KAAK,GAAG,EAAE;YACpB,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;SACtB;aAAM;;YAEL,GAAG,CAAC,IAAI,GAAG,iBAAiB,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC,IAAI,CAAC;SACpD;IACH,CAAC;IAED;;;;IAIA,SAAS,aAAa,CAAC,GAAQ,EAAE,IAAa;QAC5C,MAAM,GAAG,GAAG,IAAI,yBAAyB;QACzC,MAAM,MAAM,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;;;QAInC,IAAI,OAAO,GAAG,CAAC,CAAC;;;QAIhB,IAAI,QAAQ,GAAG,CAAC,CAAC;;;;QAKjB,IAAI,gBAAgB,GAAG,KAAK,CAAC;QAE7B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACtC,MAAM,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;;YAGxB,IAAI,CAAC,KAAK,EAAE;gBACV,gBAAgB,GAAG,IAAI,CAAC;gBACxB,SAAS;aACV;;YAGD,gBAAgB,GAAG,KAAK,CAAC;;YAGzB,IAAI,KAAK,KAAK,GAAG;gBAAE,SAAS;;;YAI5B,IAAI,KAAK,KAAK,IAAI,EAAE;gBAClB,IAAI,QAAQ,EAAE;oBACZ,gBAAgB,GAAG,IAAI,CAAC;oBACxB,QAAQ,EAAE,CAAC;oBACX,OAAO,EAAE,CAAC;iBACX;qBAAM,IAAI,GAAG,EAAE;;;oBAGd,MAAM,CAAC,OAAO,EAAE,CAAC,GAAG,KAAK,CAAC;iBAC3B;gBACD,SAAS;aACV;;;YAID,MAAM,CAAC,OAAO,EAAE,CAAC,GAAG,KAAK,CAAC;YAC1B,QAAQ,EAAE,CAAC;SACZ;QAED,IAAI,IAAI,GAAG,EAAE,CAAC;QACd,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,EAAE,CAAC,EAAE,EAAE;YAChC,IAAI,IAAI,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;SACzB;QACD,IAAI,CAAC,IAAI,KAAK,gBAAgB,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE;YACxD,IAAI,IAAI,GAAG,CAAC;SACb;QACD,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC;IAClB,CAAC;IAED;;;aAGwB,OAAO,CAAC,KAAa,EAAE,IAAwB;QACrE,IAAI,CAAC,KAAK,IAAI,CAAC,IAAI;YAAE,OAAO,EAAE,CAAC;QAE/B,MAAM,GAAG,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;QAC5B,IAAI,SAAS,GAAG,GAAG,CAAC,IAAI,CAAC;QAEzB,IAAI,IAAI,IAAI,SAAS,uBAAuB;YAC1C,MAAM,OAAO,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;YAC/B,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;YAE9B,QAAQ,SAAS;gBACf;oBACE,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;;gBAG1B;oBACE,GAAG,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;;gBAG5B,mBAAmB;gBACnB;oBACE,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;;gBAG3B;;oBAEE,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;oBACxB,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;oBACxB,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;;gBAG1B;;oBAEE,GAAG,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;aAC/B;YACD,IAAI,QAAQ,GAAG,SAAS;gBAAE,SAAS,GAAG,QAAQ,CAAC;SAChD;QAED,aAAa,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;QAE9B,MAAM,SAAS,GAAG,GAAG,CAAC,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC;QACvC,QAAQ,SAAS;;;YAIf,kBAAkB;YAClB;gBACE,OAAO,SAAS,CAAC;YAEnB,2BAA2B;;gBAEzB,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;gBAE/B,IAAI,CAAC,IAAI;oBAAE,OAAO,SAAS,IAAI,GAAG,CAAC;gBAEnC,IAAI,UAAU,CAAC,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;;;;oBAIlD,OAAO,IAAI,GAAG,IAAI,GAAG,SAAS,CAAC;iBAChC;gBAED,OAAO,IAAI,GAAG,SAAS,CAAC;aACzB;YAED;gBACE,OAAO,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;YAE9B;gBACE,OAAO,GAAG,CAAC,MAAM,GAAG,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;SACpF;IACH;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts b/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts new file mode 100644 index 000000000..b7f0b3b2d --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts @@ -0,0 +1,4 @@ +/** + * Attempts to resolve `input` URL/path relative to `base`. + */ +export default function resolve(input: string, base: string | undefined): string; diff --git a/node_modules/@jridgewell/resolve-uri/package.json b/node_modules/@jridgewell/resolve-uri/package.json new file mode 100644 index 000000000..02a4c5187 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/package.json @@ -0,0 +1,69 @@ +{ + "name": "@jridgewell/resolve-uri", + "version": "3.1.2", + "description": "Resolve a URI relative to an optional base URI", + "keywords": [ + "resolve", + "uri", + "url", + "path" + ], + "author": "Justin Ridgewell ", + "license": "MIT", + "repository": "https://github.com/jridgewell/resolve-uri", + "main": "dist/resolve-uri.umd.js", + "module": "dist/resolve-uri.mjs", + "types": "dist/types/resolve-uri.d.ts", + "exports": { + ".": [ + { + "types": "./dist/types/resolve-uri.d.ts", + "browser": "./dist/resolve-uri.umd.js", + "require": "./dist/resolve-uri.umd.js", + "import": "./dist/resolve-uri.mjs" + }, + "./dist/resolve-uri.umd.js" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "engines": { + "node": ">=6.0.0" + }, + "scripts": { + "prebuild": "rm -rf dist", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "pretest": "run-s build:rollup", + "test": "run-s -n test:lint test:only", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:coverage": "c8 mocha", + "test:watch": "mocha --watch", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build" + }, + "devDependencies": { + "@jridgewell/resolve-uri-latest": "npm:@jridgewell/resolve-uri@*", + "@rollup/plugin-typescript": "8.3.0", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "c8": "7.11.0", + "eslint": "8.7.0", + "eslint-config-prettier": "8.3.0", + "mocha": "9.2.0", + "npm-run-all": "4.1.5", + "prettier": "2.5.1", + "rollup": "2.66.0", + "typescript": "4.5.5" + } +} diff --git a/node_modules/@jridgewell/sourcemap-codec/LICENSE b/node_modules/@jridgewell/sourcemap-codec/LICENSE new file mode 100644 index 000000000..a331065a4 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2015 Rich Harris + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/@jridgewell/sourcemap-codec/README.md b/node_modules/@jridgewell/sourcemap-codec/README.md new file mode 100644 index 000000000..5cbb31525 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/README.md @@ -0,0 +1,200 @@ +# @jridgewell/sourcemap-codec + +Encode/decode the `mappings` property of a [sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit). + + +## Why? + +Sourcemaps are difficult to generate and manipulate, because the `mappings` property – the part that actually links the generated code back to the original source – is encoded using an obscure method called [Variable-length quantity](https://en.wikipedia.org/wiki/Variable-length_quantity). On top of that, each segment in the mapping contains offsets rather than absolute indices, which means that you can't look at a segment in isolation – you have to understand the whole sourcemap. + +This package makes the process slightly easier. + + +## Installation + +```bash +npm install @jridgewell/sourcemap-codec +``` + + +## Usage + +```js +import { encode, decode } from '@jridgewell/sourcemap-codec'; + +var decoded = decode( ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); + +assert.deepEqual( decoded, [ + // the first line (of the generated code) has no mappings, + // as shown by the starting semi-colon (which separates lines) + [], + + // the second line contains four (comma-separated) segments + [ + // segments are encoded as you'd expect: + // [ generatedCodeColumn, sourceIndex, sourceCodeLine, sourceCodeColumn, nameIndex ] + + // i.e. the first segment begins at column 2, and maps back to the second column + // of the second line (both zero-based) of the 0th source, and uses the 0th + // name in the `map.names` array + [ 2, 0, 2, 2, 0 ], + + // the remaining segments are 4-length rather than 5-length, + // because they don't map a name + [ 4, 0, 2, 4 ], + [ 6, 0, 2, 5 ], + [ 7, 0, 2, 7 ] + ], + + // the final line contains two segments + [ + [ 2, 1, 10, 19 ], + [ 12, 1, 11, 20 ] + ] +]); + +var encoded = encode( decoded ); +assert.equal( encoded, ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); +``` + +## Benchmarks + +``` +node v18.0.0 + +amp.js.map - 45120 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 5479160 bytes +sourcemap-codec 5659336 bytes +source-map-0.6.1 17144440 bytes +source-map-0.8.0 6867424 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 502 ops/sec ±1.03% (90 runs sampled) +decode: sourcemap-codec x 445 ops/sec ±0.97% (92 runs sampled) +decode: source-map-0.6.1 x 36.01 ops/sec ±1.64% (49 runs sampled) +decode: source-map-0.8.0 x 367 ops/sec ±0.04% (95 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec + +Encode Memory Usage: +@jridgewell/sourcemap-codec 1261620 bytes +sourcemap-codec 9119248 bytes +source-map-0.6.1 8968560 bytes +source-map-0.8.0 8952952 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 738 ops/sec ±0.42% (98 runs sampled) +encode: sourcemap-codec x 238 ops/sec ±0.73% (88 runs sampled) +encode: source-map-0.6.1 x 162 ops/sec ±0.43% (84 runs sampled) +encode: source-map-0.8.0 x 191 ops/sec ±0.34% (90 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec + + +*** + + +babel.min.js.map - 347793 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 35338184 bytes +sourcemap-codec 35922736 bytes +source-map-0.6.1 62366360 bytes +source-map-0.8.0 44337416 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 40.35 ops/sec ±4.47% (54 runs sampled) +decode: sourcemap-codec x 36.76 ops/sec ±3.67% (51 runs sampled) +decode: source-map-0.6.1 x 4.44 ops/sec ±2.15% (16 runs sampled) +decode: source-map-0.8.0 x 59.35 ops/sec ±0.05% (78 runs sampled) +Fastest is decode: source-map-0.8.0 + +Encode Memory Usage: +@jridgewell/sourcemap-codec 7212604 bytes +sourcemap-codec 21421456 bytes +source-map-0.6.1 25286888 bytes +source-map-0.8.0 25498744 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 112 ops/sec ±0.13% (84 runs sampled) +encode: sourcemap-codec x 30.23 ops/sec ±2.76% (53 runs sampled) +encode: source-map-0.6.1 x 19.43 ops/sec ±3.70% (37 runs sampled) +encode: source-map-0.8.0 x 19.40 ops/sec ±3.26% (37 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec + + +*** + + +preact.js.map - 1992 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 500272 bytes +sourcemap-codec 516864 bytes +source-map-0.6.1 1596672 bytes +source-map-0.8.0 517272 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 16,137 ops/sec ±0.17% (99 runs sampled) +decode: sourcemap-codec x 12,139 ops/sec ±0.13% (99 runs sampled) +decode: source-map-0.6.1 x 1,264 ops/sec ±0.12% (100 runs sampled) +decode: source-map-0.8.0 x 9,894 ops/sec ±0.08% (101 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec + +Encode Memory Usage: +@jridgewell/sourcemap-codec 321026 bytes +sourcemap-codec 830832 bytes +source-map-0.6.1 586608 bytes +source-map-0.8.0 586680 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 19,876 ops/sec ±0.78% (95 runs sampled) +encode: sourcemap-codec x 6,983 ops/sec ±0.15% (100 runs sampled) +encode: source-map-0.6.1 x 5,070 ops/sec ±0.12% (102 runs sampled) +encode: source-map-0.8.0 x 5,641 ops/sec ±0.17% (100 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec + + +*** + + +react.js.map - 5726 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 734848 bytes +sourcemap-codec 954200 bytes +source-map-0.6.1 2276432 bytes +source-map-0.8.0 955488 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 5,723 ops/sec ±0.12% (98 runs sampled) +decode: sourcemap-codec x 4,555 ops/sec ±0.09% (101 runs sampled) +decode: source-map-0.6.1 x 437 ops/sec ±0.11% (93 runs sampled) +decode: source-map-0.8.0 x 3,441 ops/sec ±0.15% (100 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec + +Encode Memory Usage: +@jridgewell/sourcemap-codec 638672 bytes +sourcemap-codec 1109840 bytes +source-map-0.6.1 1321224 bytes +source-map-0.8.0 1324448 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 6,801 ops/sec ±0.48% (98 runs sampled) +encode: sourcemap-codec x 2,533 ops/sec ±0.13% (101 runs sampled) +encode: source-map-0.6.1 x 2,248 ops/sec ±0.08% (100 runs sampled) +encode: source-map-0.8.0 x 2,303 ops/sec ±0.15% (100 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec +``` + +# License + +MIT diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs new file mode 100644 index 000000000..3dff37217 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs @@ -0,0 +1,164 @@ +const comma = ','.charCodeAt(0); +const semicolon = ';'.charCodeAt(0); +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +const intToChar = new Uint8Array(64); // 64 possible chars. +const charToInt = new Uint8Array(128); // z is 122 in ASCII +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +// Provide a fallback for older environments. +const td = typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf) { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; +function decode(mappings) { + const state = new Int32Array(5); + const decoded = []; + let index = 0; + do { + const semi = indexOf(mappings, index); + const line = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + for (let i = index; i < semi; i++) { + let seg; + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) + sorted = false; + lastCol = col; + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } + else { + seg = [col, state[1], state[2], state[3]]; + } + } + else { + seg = [col]; + } + line.push(seg); + } + if (!sorted) + sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + return decoded; +} +function indexOf(mappings, index) { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; +} +function decodeInteger(mappings, pos, state, j) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + state[j] += value; + return pos; +} +function hasMoreVlq(mappings, i, length) { + if (i >= length) + return false; + return mappings.charCodeAt(i) !== comma; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} +function encode(decoded) { + const state = new Int32Array(5); + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) + continue; + state[0] = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) + buf[pos++] = comma; + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + if (segment.length === 1) + continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + if (segment.length === 4) + continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + return out + td.decode(buf.subarray(0, pos)); +} +function encodeInteger(buf, pos, state, segment, j) { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) + clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + return pos; +} + +export { decode, encode }; +//# sourceMappingURL=sourcemap-codec.mjs.map diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map new file mode 100644 index 000000000..236fd120a --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.mjs","sources":["../src/sourcemap-codec.ts"],"sourcesContent":["export type SourceMapSegment =\n | [number]\n | [number, number, number, number]\n | [number, number, number, number, number];\nexport type SourceMapLine = SourceMapSegment[];\nexport type SourceMapMappings = SourceMapLine[];\n\nconst comma = ','.charCodeAt(0);\nconst semicolon = ';'.charCodeAt(0);\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nconst intToChar = new Uint8Array(64); // 64 possible chars.\nconst charToInt = new Uint8Array(128); // z is 122 in ASCII\n\nfor (let i = 0; i < chars.length; i++) {\n const c = chars.charCodeAt(i);\n intToChar[i] = c;\n charToInt[c] = i;\n}\n\n// Provide a fallback for older environments.\nconst td =\n typeof TextDecoder !== 'undefined'\n ? /* #__PURE__ */ new TextDecoder()\n : typeof Buffer !== 'undefined'\n ? {\n decode(buf: Uint8Array) {\n const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);\n return out.toString();\n },\n }\n : {\n decode(buf: Uint8Array) {\n let out = '';\n for (let i = 0; i < buf.length; i++) {\n out += String.fromCharCode(buf[i]);\n }\n return out;\n },\n };\n\nexport function decode(mappings: string): SourceMapMappings {\n const state: [number, number, number, number, number] = new Int32Array(5) as any;\n const decoded: SourceMapMappings = [];\n\n let index = 0;\n do {\n const semi = indexOf(mappings, index);\n const line: SourceMapLine = [];\n let sorted = true;\n let lastCol = 0;\n state[0] = 0;\n\n for (let i = index; i < semi; i++) {\n let seg: SourceMapSegment;\n\n i = decodeInteger(mappings, i, state, 0); // genColumn\n const col = state[0];\n if (col < lastCol) sorted = false;\n lastCol = col;\n\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 1); // sourcesIndex\n i = decodeInteger(mappings, i, state, 2); // sourceLine\n i = decodeInteger(mappings, i, state, 3); // sourceColumn\n\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 4); // namesIndex\n seg = [col, state[1], state[2], state[3], state[4]];\n } else {\n seg = [col, state[1], state[2], state[3]];\n }\n } else {\n seg = [col];\n }\n\n line.push(seg);\n }\n\n if (!sorted) sort(line);\n decoded.push(line);\n index = semi + 1;\n } while (index <= mappings.length);\n\n return decoded;\n}\n\nfunction indexOf(mappings: string, index: number): number {\n const idx = mappings.indexOf(';', index);\n return idx === -1 ? mappings.length : idx;\n}\n\nfunction decodeInteger(mappings: string, pos: number, state: SourceMapSegment, j: number): number {\n let value = 0;\n let shift = 0;\n let integer = 0;\n\n do {\n const c = mappings.charCodeAt(pos++);\n integer = charToInt[c];\n value |= (integer & 31) << shift;\n shift += 5;\n } while (integer & 32);\n\n const shouldNegate = value & 1;\n value >>>= 1;\n\n if (shouldNegate) {\n value = -0x80000000 | -value;\n }\n\n state[j] += value;\n return pos;\n}\n\nfunction hasMoreVlq(mappings: string, i: number, length: number): boolean {\n if (i >= length) return false;\n return mappings.charCodeAt(i) !== comma;\n}\n\nfunction sort(line: SourceMapSegment[]) {\n line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[0] - b[0];\n}\n\nexport function encode(decoded: SourceMapMappings): string;\nexport function encode(decoded: Readonly): string;\nexport function encode(decoded: Readonly): string {\n const state: [number, number, number, number, number] = new Int32Array(5) as any;\n const bufLength = 1024 * 16;\n const subLength = bufLength - 36;\n const buf = new Uint8Array(bufLength);\n const sub = buf.subarray(0, subLength);\n let pos = 0;\n let out = '';\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n if (i > 0) {\n if (pos === bufLength) {\n out += td.decode(buf);\n pos = 0;\n }\n buf[pos++] = semicolon;\n }\n if (line.length === 0) continue;\n\n state[0] = 0;\n\n for (let j = 0; j < line.length; j++) {\n const segment = line[j];\n // We can push up to 5 ints, each int can take at most 7 chars, and we\n // may push a comma.\n if (pos > subLength) {\n out += td.decode(sub);\n buf.copyWithin(0, subLength, pos);\n pos -= subLength;\n }\n if (j > 0) buf[pos++] = comma;\n\n pos = encodeInteger(buf, pos, state, segment, 0); // genColumn\n\n if (segment.length === 1) continue;\n pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex\n pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine\n pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn\n\n if (segment.length === 4) continue;\n pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex\n }\n }\n\n return out + td.decode(buf.subarray(0, pos));\n}\n\nfunction encodeInteger(\n buf: Uint8Array,\n pos: number,\n state: SourceMapSegment,\n segment: SourceMapSegment,\n j: number,\n): number {\n const next = segment[j];\n let num = next - state[j];\n state[j] = next;\n\n num = num < 0 ? (-num << 1) | 1 : num << 1;\n do {\n let clamped = num & 0b011111;\n num >>>= 5;\n if (num > 0) clamped |= 0b100000;\n buf[pos++] = intToChar[clamped];\n } while (num > 0);\n\n return pos;\n}\n"],"names":[],"mappings":"AAOA,MAAM,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AAChC,MAAM,SAAS,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AACpC,MAAM,KAAK,GAAG,kEAAkE,CAAC;AACjF,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;AACrC,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;AAEtC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IACrC,MAAM,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAC9B,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IACjB,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;CAClB;AAED;AACA,MAAM,EAAE,GACN,OAAO,WAAW,KAAK,WAAW;sBACd,IAAI,WAAW,EAAE;MACjC,OAAO,MAAM,KAAK,WAAW;UAC7B;YACE,MAAM,CAAC,GAAe;gBACpB,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;gBACpE,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAC;aACvB;SACF;UACD;YACE,MAAM,CAAC,GAAe;gBACpB,IAAI,GAAG,GAAG,EAAE,CAAC;gBACb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;oBACnC,GAAG,IAAI,MAAM,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;iBACpC;gBACD,OAAO,GAAG,CAAC;aACZ;SACF,CAAC;SAEQ,MAAM,CAAC,QAAgB;IACrC,MAAM,KAAK,GAA6C,IAAI,UAAU,CAAC,CAAC,CAAQ,CAAC;IACjF,MAAM,OAAO,GAAsB,EAAE,CAAC;IAEtC,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,GAAG;QACD,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;QACtC,MAAM,IAAI,GAAkB,EAAE,CAAC;QAC/B,IAAI,MAAM,GAAG,IAAI,CAAC;QAClB,IAAI,OAAO,GAAG,CAAC,CAAC;QAChB,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QAEb,KAAK,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,EAAE,EAAE;YACjC,IAAI,GAAqB,CAAC;YAE1B,CAAC,GAAG,aAAa,CAAC,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;YACzC,MAAM,GAAG,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;YACrB,IAAI,GAAG,GAAG,OAAO;gBAAE,MAAM,GAAG,KAAK,CAAC;YAClC,OAAO,GAAG,GAAG,CAAC;YAEd,IAAI,UAAU,CAAC,QAAQ,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE;gBACjC,CAAC,GAAG,aAAa,CAAC,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;gBACzC,CAAC,GAAG,aAAa,CAAC,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;gBACzC,CAAC,GAAG,aAAa,CAAC,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;gBAEzC,IAAI,UAAU,CAAC,QAAQ,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE;oBACjC,CAAC,GAAG,aAAa,CAAC,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;oBACzC,GAAG,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;iBACrD;qBAAM;oBACL,GAAG,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;iBAC3C;aACF;iBAAM;gBACL,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;aACb;YAED,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;SAChB;QAED,IAAI,CAAC,MAAM;YAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QACxB,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACnB,KAAK,GAAG,IAAI,GAAG,CAAC,CAAC;KAClB,QAAQ,KAAK,IAAI,QAAQ,CAAC,MAAM,EAAE;IAEnC,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,SAAS,OAAO,CAAC,QAAgB,EAAE,KAAa;IAC9C,MAAM,GAAG,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACzC,OAAO,GAAG,KAAK,CAAC,CAAC,GAAG,QAAQ,CAAC,MAAM,GAAG,GAAG,CAAC;AAC5C,CAAC;AAED,SAAS,aAAa,CAAC,QAAgB,EAAE,GAAW,EAAE,KAAuB,EAAE,CAAS;IACtF,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,IAAI,OAAO,GAAG,CAAC,CAAC;IAEhB,GAAG;QACD,MAAM,CAAC,GAAG,QAAQ,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC,CAAC;QACrC,OAAO,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;QACvB,KAAK,IAAI,CAAC,OAAO,GAAG,EAAE,KAAK,KAAK,CAAC;QACjC,KAAK,IAAI,CAAC,CAAC;KACZ,QAAQ,OAAO,GAAG,EAAE,EAAE;IAEvB,MAAM,YAAY,GAAG,KAAK,GAAG,CAAC,CAAC;IAC/B,KAAK,MAAM,CAAC,CAAC;IAEb,IAAI,YAAY,EAAE;QAChB,KAAK,GAAG,CAAC,UAAU,GAAG,CAAC,KAAK,CAAC;KAC9B;IAED,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC;IAClB,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,UAAU,CAAC,QAAgB,EAAE,CAAS,EAAE,MAAc;IAC7D,IAAI,CAAC,IAAI,MAAM;QAAE,OAAO,KAAK,CAAC;IAC9B,OAAO,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,KAAK,CAAC;AAC1C,CAAC;AAED,SAAS,IAAI,CAAC,IAAwB;IACpC,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;AAC5B,CAAC;AAED,SAAS,cAAc,CAAC,CAAmB,EAAE,CAAmB;IAC9D,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AACrB,CAAC;SAIe,MAAM,CAAC,OAAoC;IACzD,MAAM,KAAK,GAA6C,IAAI,UAAU,CAAC,CAAC,CAAQ,CAAC;IACjF,MAAM,SAAS,GAAG,IAAI,GAAG,EAAE,CAAC;IAC5B,MAAM,SAAS,GAAG,SAAS,GAAG,EAAE,CAAC;IACjC,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,SAAS,CAAC,CAAC;IACtC,MAAM,GAAG,GAAG,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;IACvC,IAAI,GAAG,GAAG,CAAC,CAAC;IACZ,IAAI,GAAG,GAAG,EAAE,CAAC;IAEb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACvC,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;QACxB,IAAI,CAAC,GAAG,CAAC,EAAE;YACT,IAAI,GAAG,KAAK,SAAS,EAAE;gBACrB,GAAG,IAAI,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBACtB,GAAG,GAAG,CAAC,CAAC;aACT;YACD,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC;SACxB;QACD,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;YAAE,SAAS;QAEhC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QAEb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACpC,MAAM,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;;;YAGxB,IAAI,GAAG,GAAG,SAAS,EAAE;gBACnB,GAAG,IAAI,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBACtB,GAAG,CAAC,UAAU,CAAC,CAAC,EAAE,SAAS,EAAE,GAAG,CAAC,CAAC;gBAClC,GAAG,IAAI,SAAS,CAAC;aAClB;YACD,IAAI,CAAC,GAAG,CAAC;gBAAE,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,KAAK,CAAC;YAE9B,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;YAEjD,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;gBAAE,SAAS;YACnC,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;YACjD,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;YACjD,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;YAEjD,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;gBAAE,SAAS;YACnC,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;SAClD;KACF;IAED,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;AAC/C,CAAC;AAED,SAAS,aAAa,CACpB,GAAe,EACf,GAAW,EACX,KAAuB,EACvB,OAAyB,EACzB,CAAS;IAET,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IACxB,IAAI,GAAG,GAAG,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IAC1B,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;IAEhB,GAAG,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC;IAC3C,GAAG;QACD,IAAI,OAAO,GAAG,GAAG,GAAG,QAAQ,CAAC;QAC7B,GAAG,MAAM,CAAC,CAAC;QACX,IAAI,GAAG,GAAG,CAAC;YAAE,OAAO,IAAI,QAAQ,CAAC;QACjC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;KACjC,QAAQ,GAAG,GAAG,CAAC,EAAE;IAElB,OAAO,GAAG,CAAC;AACb;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js new file mode 100644 index 000000000..bec92a9c6 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js @@ -0,0 +1,175 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.sourcemapCodec = {})); +})(this, (function (exports) { 'use strict'; + + const comma = ','.charCodeAt(0); + const semicolon = ';'.charCodeAt(0); + const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + const intToChar = new Uint8Array(64); // 64 possible chars. + const charToInt = new Uint8Array(128); // z is 122 in ASCII + for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; + } + // Provide a fallback for older environments. + const td = typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf) { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; + function decode(mappings) { + const state = new Int32Array(5); + const decoded = []; + let index = 0; + do { + const semi = indexOf(mappings, index); + const line = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + for (let i = index; i < semi; i++) { + let seg; + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) + sorted = false; + lastCol = col; + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } + else { + seg = [col, state[1], state[2], state[3]]; + } + } + else { + seg = [col]; + } + line.push(seg); + } + if (!sorted) + sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + return decoded; + } + function indexOf(mappings, index) { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; + } + function decodeInteger(mappings, pos, state, j) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + state[j] += value; + return pos; + } + function hasMoreVlq(mappings, i, length) { + if (i >= length) + return false; + return mappings.charCodeAt(i) !== comma; + } + function sort(line) { + line.sort(sortComparator); + } + function sortComparator(a, b) { + return a[0] - b[0]; + } + function encode(decoded) { + const state = new Int32Array(5); + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) + continue; + state[0] = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) + buf[pos++] = comma; + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + if (segment.length === 1) + continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + if (segment.length === 4) + continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + return out + td.decode(buf.subarray(0, pos)); + } + function encodeInteger(buf, pos, state, segment, j) { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) + clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + return pos; + } + + exports.decode = decode; + exports.encode = encode; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=sourcemap-codec.umd.js.map diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map new file mode 100644 index 000000000..b6b2003c2 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.umd.js","sources":["../src/sourcemap-codec.ts"],"sourcesContent":["export type SourceMapSegment =\n | [number]\n | [number, number, number, number]\n | [number, number, number, number, number];\nexport type SourceMapLine = SourceMapSegment[];\nexport type SourceMapMappings = SourceMapLine[];\n\nconst comma = ','.charCodeAt(0);\nconst semicolon = ';'.charCodeAt(0);\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nconst intToChar = new Uint8Array(64); // 64 possible chars.\nconst charToInt = new Uint8Array(128); // z is 122 in ASCII\n\nfor (let i = 0; i < chars.length; i++) {\n const c = chars.charCodeAt(i);\n intToChar[i] = c;\n charToInt[c] = i;\n}\n\n// Provide a fallback for older environments.\nconst td =\n typeof TextDecoder !== 'undefined'\n ? /* #__PURE__ */ new TextDecoder()\n : typeof Buffer !== 'undefined'\n ? {\n decode(buf: Uint8Array) {\n const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);\n return out.toString();\n },\n }\n : {\n decode(buf: Uint8Array) {\n let out = '';\n for (let i = 0; i < buf.length; i++) {\n out += String.fromCharCode(buf[i]);\n }\n return out;\n },\n };\n\nexport function decode(mappings: string): SourceMapMappings {\n const state: [number, number, number, number, number] = new Int32Array(5) as any;\n const decoded: SourceMapMappings = [];\n\n let index = 0;\n do {\n const semi = indexOf(mappings, index);\n const line: SourceMapLine = [];\n let sorted = true;\n let lastCol = 0;\n state[0] = 0;\n\n for (let i = index; i < semi; i++) {\n let seg: SourceMapSegment;\n\n i = decodeInteger(mappings, i, state, 0); // genColumn\n const col = state[0];\n if (col < lastCol) sorted = false;\n lastCol = col;\n\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 1); // sourcesIndex\n i = decodeInteger(mappings, i, state, 2); // sourceLine\n i = decodeInteger(mappings, i, state, 3); // sourceColumn\n\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 4); // namesIndex\n seg = [col, state[1], state[2], state[3], state[4]];\n } else {\n seg = [col, state[1], state[2], state[3]];\n }\n } else {\n seg = [col];\n }\n\n line.push(seg);\n }\n\n if (!sorted) sort(line);\n decoded.push(line);\n index = semi + 1;\n } while (index <= mappings.length);\n\n return decoded;\n}\n\nfunction indexOf(mappings: string, index: number): number {\n const idx = mappings.indexOf(';', index);\n return idx === -1 ? mappings.length : idx;\n}\n\nfunction decodeInteger(mappings: string, pos: number, state: SourceMapSegment, j: number): number {\n let value = 0;\n let shift = 0;\n let integer = 0;\n\n do {\n const c = mappings.charCodeAt(pos++);\n integer = charToInt[c];\n value |= (integer & 31) << shift;\n shift += 5;\n } while (integer & 32);\n\n const shouldNegate = value & 1;\n value >>>= 1;\n\n if (shouldNegate) {\n value = -0x80000000 | -value;\n }\n\n state[j] += value;\n return pos;\n}\n\nfunction hasMoreVlq(mappings: string, i: number, length: number): boolean {\n if (i >= length) return false;\n return mappings.charCodeAt(i) !== comma;\n}\n\nfunction sort(line: SourceMapSegment[]) {\n line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[0] - b[0];\n}\n\nexport function encode(decoded: SourceMapMappings): string;\nexport function encode(decoded: Readonly): string;\nexport function encode(decoded: Readonly): string {\n const state: [number, number, number, number, number] = new Int32Array(5) as any;\n const bufLength = 1024 * 16;\n const subLength = bufLength - 36;\n const buf = new Uint8Array(bufLength);\n const sub = buf.subarray(0, subLength);\n let pos = 0;\n let out = '';\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n if (i > 0) {\n if (pos === bufLength) {\n out += td.decode(buf);\n pos = 0;\n }\n buf[pos++] = semicolon;\n }\n if (line.length === 0) continue;\n\n state[0] = 0;\n\n for (let j = 0; j < line.length; j++) {\n const segment = line[j];\n // We can push up to 5 ints, each int can take at most 7 chars, and we\n // may push a comma.\n if (pos > subLength) {\n out += td.decode(sub);\n buf.copyWithin(0, subLength, pos);\n pos -= subLength;\n }\n if (j > 0) buf[pos++] = comma;\n\n pos = encodeInteger(buf, pos, state, segment, 0); // genColumn\n\n if (segment.length === 1) continue;\n pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex\n pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine\n pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn\n\n if (segment.length === 4) continue;\n pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex\n }\n }\n\n return out + td.decode(buf.subarray(0, pos));\n}\n\nfunction encodeInteger(\n buf: Uint8Array,\n pos: number,\n state: SourceMapSegment,\n segment: SourceMapSegment,\n j: number,\n): number {\n const next = segment[j];\n let num = next - state[j];\n state[j] = next;\n\n num = num < 0 ? (-num << 1) | 1 : num << 1;\n do {\n let clamped = num & 0b011111;\n num >>>= 5;\n if (num > 0) clamped |= 0b100000;\n buf[pos++] = intToChar[clamped];\n } while (num > 0);\n\n return pos;\n}\n"],"names":[],"mappings":";;;;;;IAOA,MAAM,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAChC,MAAM,SAAS,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IACpC,MAAM,KAAK,GAAG,kEAAkE,CAAC;IACjF,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;IACrC,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;IAEtC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACrC,MAAM,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC9B,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACjB,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;KAClB;IAED;IACA,MAAM,EAAE,GACN,OAAO,WAAW,KAAK,WAAW;0BACd,IAAI,WAAW,EAAE;UACjC,OAAO,MAAM,KAAK,WAAW;cAC7B;gBACE,MAAM,CAAC,GAAe;oBACpB,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;oBACpE,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAC;iBACvB;aACF;cACD;gBACE,MAAM,CAAC,GAAe;oBACpB,IAAI,GAAG,GAAG,EAAE,CAAC;oBACb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;wBACnC,GAAG,IAAI,MAAM,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;qBACpC;oBACD,OAAO,GAAG,CAAC;iBACZ;aACF,CAAC;aAEQ,MAAM,CAAC,QAAgB;QACrC,MAAM,KAAK,GAA6C,IAAI,UAAU,CAAC,CAAC,CAAQ,CAAC;QACjF,MAAM,OAAO,GAAsB,EAAE,CAAC;QAEtC,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,GAAG;YACD,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;YACtC,MAAM,IAAI,GAAkB,EAAE,CAAC;YAC/B,IAAI,MAAM,GAAG,IAAI,CAAC;YAClB,IAAI,OAAO,GAAG,CAAC,CAAC;YAChB,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;YAEb,KAAK,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,EAAE,EAAE;gBACjC,IAAI,GAAqB,CAAC;gBAE1B,CAAC,GAAG,aAAa,CAAC,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;gBACzC,MAAM,GAAG,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;gBACrB,IAAI,GAAG,GAAG,OAAO;oBAAE,MAAM,GAAG,KAAK,CAAC;gBAClC,OAAO,GAAG,GAAG,CAAC;gBAEd,IAAI,UAAU,CAAC,QAAQ,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE;oBACjC,CAAC,GAAG,aAAa,CAAC,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;oBACzC,CAAC,GAAG,aAAa,CAAC,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;oBACzC,CAAC,GAAG,aAAa,CAAC,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;oBAEzC,IAAI,UAAU,CAAC,QAAQ,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE;wBACjC,CAAC,GAAG,aAAa,CAAC,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;wBACzC,GAAG,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;qBACrD;yBAAM;wBACL,GAAG,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;qBAC3C;iBACF;qBAAM;oBACL,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;iBACb;gBAED,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;aAChB;YAED,IAAI,CAAC,MAAM;gBAAE,IAAI,CAAC,IAAI,CAAC,CAAC;YACxB,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACnB,KAAK,GAAG,IAAI,GAAG,CAAC,CAAC;SAClB,QAAQ,KAAK,IAAI,QAAQ,CAAC,MAAM,EAAE;QAEnC,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,SAAS,OAAO,CAAC,QAAgB,EAAE,KAAa;QAC9C,MAAM,GAAG,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACzC,OAAO,GAAG,KAAK,CAAC,CAAC,GAAG,QAAQ,CAAC,MAAM,GAAG,GAAG,CAAC;IAC5C,CAAC;IAED,SAAS,aAAa,CAAC,QAAgB,EAAE,GAAW,EAAE,KAAuB,EAAE,CAAS;QACtF,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,IAAI,OAAO,GAAG,CAAC,CAAC;QAEhB,GAAG;YACD,MAAM,CAAC,GAAG,QAAQ,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC,CAAC;YACrC,OAAO,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;YACvB,KAAK,IAAI,CAAC,OAAO,GAAG,EAAE,KAAK,KAAK,CAAC;YACjC,KAAK,IAAI,CAAC,CAAC;SACZ,QAAQ,OAAO,GAAG,EAAE,EAAE;QAEvB,MAAM,YAAY,GAAG,KAAK,GAAG,CAAC,CAAC;QAC/B,KAAK,MAAM,CAAC,CAAC;QAEb,IAAI,YAAY,EAAE;YAChB,KAAK,GAAG,CAAC,UAAU,GAAG,CAAC,KAAK,CAAC;SAC9B;QAED,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC;QAClB,OAAO,GAAG,CAAC;IACb,CAAC;IAED,SAAS,UAAU,CAAC,QAAgB,EAAE,CAAS,EAAE,MAAc;QAC7D,IAAI,CAAC,IAAI,MAAM;YAAE,OAAO,KAAK,CAAC;QAC9B,OAAO,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,KAAK,CAAC;IAC1C,CAAC;IAED,SAAS,IAAI,CAAC,IAAwB;QACpC,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;IAC5B,CAAC;IAED,SAAS,cAAc,CAAC,CAAmB,EAAE,CAAmB;QAC9D,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IACrB,CAAC;aAIe,MAAM,CAAC,OAAoC;QACzD,MAAM,KAAK,GAA6C,IAAI,UAAU,CAAC,CAAC,CAAQ,CAAC;QACjF,MAAM,SAAS,GAAG,IAAI,GAAG,EAAE,CAAC;QAC5B,MAAM,SAAS,GAAG,SAAS,GAAG,EAAE,CAAC;QACjC,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,SAAS,CAAC,CAAC;QACtC,MAAM,GAAG,GAAG,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;QACvC,IAAI,GAAG,GAAG,CAAC,CAAC;QACZ,IAAI,GAAG,GAAG,EAAE,CAAC;QAEb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACvC,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;YACxB,IAAI,CAAC,GAAG,CAAC,EAAE;gBACT,IAAI,GAAG,KAAK,SAAS,EAAE;oBACrB,GAAG,IAAI,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;oBACtB,GAAG,GAAG,CAAC,CAAC;iBACT;gBACD,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC;aACxB;YACD,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;gBAAE,SAAS;YAEhC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;YAEb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;gBACpC,MAAM,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;;;gBAGxB,IAAI,GAAG,GAAG,SAAS,EAAE;oBACnB,GAAG,IAAI,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;oBACtB,GAAG,CAAC,UAAU,CAAC,CAAC,EAAE,SAAS,EAAE,GAAG,CAAC,CAAC;oBAClC,GAAG,IAAI,SAAS,CAAC;iBAClB;gBACD,IAAI,CAAC,GAAG,CAAC;oBAAE,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,KAAK,CAAC;gBAE9B,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;gBAEjD,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;oBAAE,SAAS;gBACnC,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;gBACjD,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;gBACjD,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;gBAEjD,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;oBAAE,SAAS;gBACnC,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;aAClD;SACF;QAED,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;IAC/C,CAAC;IAED,SAAS,aAAa,CACpB,GAAe,EACf,GAAW,EACX,KAAuB,EACvB,OAAyB,EACzB,CAAS;QAET,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;QACxB,IAAI,GAAG,GAAG,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QAC1B,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;QAEhB,GAAG,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC;QAC3C,GAAG;YACD,IAAI,OAAO,GAAG,GAAG,GAAG,QAAQ,CAAC;YAC7B,GAAG,MAAM,CAAC,CAAC;YACX,IAAI,GAAG,GAAG,CAAC;gBAAE,OAAO,IAAI,QAAQ,CAAC;YACjC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;SACjC,QAAQ,GAAG,GAAG,CAAC,EAAE;QAElB,OAAO,GAAG,CAAC;IACb;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts b/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts new file mode 100644 index 000000000..410d3202f --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts @@ -0,0 +1,6 @@ +export declare type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number]; +export declare type SourceMapLine = SourceMapSegment[]; +export declare type SourceMapMappings = SourceMapLine[]; +export declare function decode(mappings: string): SourceMapMappings; +export declare function encode(decoded: SourceMapMappings): string; +export declare function encode(decoded: Readonly): string; diff --git a/node_modules/@jridgewell/sourcemap-codec/package.json b/node_modules/@jridgewell/sourcemap-codec/package.json new file mode 100644 index 000000000..578448f1c --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/package.json @@ -0,0 +1,74 @@ +{ + "name": "@jridgewell/sourcemap-codec", + "version": "1.4.15", + "description": "Encode/decode sourcemap mappings", + "keywords": [ + "sourcemap", + "vlq" + ], + "main": "dist/sourcemap-codec.umd.js", + "module": "dist/sourcemap-codec.mjs", + "types": "dist/types/sourcemap-codec.d.ts", + "files": [ + "dist" + ], + "exports": { + ".": [ + { + "types": "./dist/types/sourcemap-codec.d.ts", + "browser": "./dist/sourcemap-codec.umd.js", + "require": "./dist/sourcemap-codec.umd.js", + "import": "./dist/sourcemap-codec.mjs" + }, + "./dist/sourcemap-codec.umd.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "benchmark": "run-s build:rollup benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.js", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "prebuild": "rm -rf dist", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build", + "pretest": "run-s build:rollup", + "test": "run-s -n test:lint test:only", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:coverage": "c8 mocha", + "test:watch": "mocha --watch" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/sourcemap-codec.git" + }, + "author": "Rich Harris", + "license": "MIT", + "devDependencies": { + "@rollup/plugin-typescript": "8.3.0", + "@types/node": "17.0.15", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "benchmark": "2.1.4", + "c8": "7.11.2", + "eslint": "8.7.0", + "eslint-config-prettier": "8.3.0", + "mocha": "9.2.0", + "npm-run-all": "4.1.5", + "prettier": "2.5.1", + "rollup": "2.64.0", + "source-map": "0.6.1", + "source-map-js": "1.0.2", + "sourcemap-codec": "1.4.8", + "typescript": "4.5.4" + } +} diff --git a/node_modules/@jridgewell/trace-mapping/LICENSE b/node_modules/@jridgewell/trace-mapping/LICENSE new file mode 100644 index 000000000..37bb488f0 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/LICENSE @@ -0,0 +1,19 @@ +Copyright 2022 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@jridgewell/trace-mapping/README.md b/node_modules/@jridgewell/trace-mapping/README.md new file mode 100644 index 000000000..969558d7f --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/README.md @@ -0,0 +1,257 @@ +# @jridgewell/trace-mapping + +> Trace the original position through a source map + +`trace-mapping` allows you to take the line and column of an output file and trace it to the +original location in the source file through a source map. + +You may already be familiar with the [`source-map`][source-map] package's `SourceMapConsumer`. This +provides the same `originalPositionFor` and `generatedPositionFor` API, without requiring WASM. + +## Installation + +```sh +npm install @jridgewell/trace-mapping +``` + +## Usage + +```typescript +import { + TraceMap, + originalPositionFor, + generatedPositionFor, + sourceContentFor, + isIgnored, +} from '@jridgewell/trace-mapping'; + +const tracer = new TraceMap({ + version: 3, + sources: ['input.js'], + sourcesContent: ['content of input.js'], + names: ['foo'], + mappings: 'KAyCIA', + ignoreList: [], +}); + +// Lines start at line 1, columns at column 0. +const traced = originalPositionFor(tracer, { line: 1, column: 5 }); +assert.deepEqual(traced, { + source: 'input.js', + line: 42, + column: 4, + name: 'foo', +}); + +const content = sourceContentFor(tracer, traced.source); +assert.strictEqual(content, 'content for input.js'); + +const generated = generatedPositionFor(tracer, { + source: 'input.js', + line: 42, + column: 4, +}); +assert.deepEqual(generated, { + line: 1, + column: 5, +}); + +const ignored = isIgnored(tracer, 'input.js'); +assert.equal(ignored, false); +``` + +We also provide a lower level API to get the actual segment that matches our line and column. Unlike +`originalPositionFor`, `traceSegment` uses a 0-base for `line`: + +```typescript +import { traceSegment } from '@jridgewell/trace-mapping'; + +// line is 0-base. +const traced = traceSegment(tracer, /* line */ 0, /* column */ 5); + +// Segments are [outputColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] +// Again, line is 0-base and so is sourceLine +assert.deepEqual(traced, [5, 0, 41, 4, 0]); +``` + +### SectionedSourceMaps + +The sourcemap spec defines a special `sections` field that's designed to handle concatenation of +output code with associated sourcemaps. This type of sourcemap is rarely used (no major build tool +produces it), but if you are hand coding a concatenation you may need it. We provide an `AnyMap` +helper that can receive either a regular sourcemap or a `SectionedSourceMap` and returns a +`TraceMap` instance: + +```typescript +import { AnyMap } from '@jridgewell/trace-mapping'; +const fooOutput = 'foo'; +const barOutput = 'bar'; +const output = [fooOutput, barOutput].join('\n'); + +const sectioned = new AnyMap({ + version: 3, + sections: [ + { + // 0-base line and column + offset: { line: 0, column: 0 }, + // fooOutput's sourcemap + map: { + version: 3, + sources: ['foo.js'], + names: ['foo'], + mappings: 'AAAAA', + }, + }, + { + // barOutput's sourcemap will not affect the first line, only the second + offset: { line: 1, column: 0 }, + map: { + version: 3, + sources: ['bar.js'], + names: ['bar'], + mappings: 'AAAAA', + }, + }, + ], +}); + +const traced = originalPositionFor(sectioned, { + line: 2, + column: 0, +}); + +assert.deepEqual(traced, { + source: 'bar.js', + line: 1, + column: 0, + name: 'bar', +}); +``` + +## Benchmarks + +``` +node v18.0.0 + +amp.js.map - 45120 segments + +Memory Usage: +trace-mapping decoded 562400 bytes +trace-mapping encoded 5706544 bytes +source-map-js 10717664 bytes +source-map-0.6.1 17446384 bytes +source-map-0.8.0 9701757 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 180 ops/sec ±0.34% (85 runs sampled) +trace-mapping: encoded JSON input x 364 ops/sec ±1.77% (89 runs sampled) +trace-mapping: decoded Object input x 3,116 ops/sec ±0.50% (96 runs sampled) +trace-mapping: encoded Object input x 410 ops/sec ±2.62% (85 runs sampled) +source-map-js: encoded Object input x 84.23 ops/sec ±0.91% (73 runs sampled) +source-map-0.6.1: encoded Object input x 37.21 ops/sec ±2.08% (51 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed: +trace-mapping: decoded originalPositionFor x 3,952,212 ops/sec ±0.17% (98 runs sampled) +trace-mapping: encoded originalPositionFor x 3,487,468 ops/sec ±1.58% (90 runs sampled) +source-map-js: encoded originalPositionFor x 827,730 ops/sec ±0.78% (97 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 748,991 ops/sec ±0.53% (94 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 2,532,894 ops/sec ±0.57% (95 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +babel.min.js.map - 347793 segments + +Memory Usage: +trace-mapping decoded 89832 bytes +trace-mapping encoded 35474640 bytes +source-map-js 51257176 bytes +source-map-0.6.1 63515664 bytes +source-map-0.8.0 42933752 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 15.41 ops/sec ±8.65% (34 runs sampled) +trace-mapping: encoded JSON input x 28.20 ops/sec ±12.87% (42 runs sampled) +trace-mapping: decoded Object input x 964 ops/sec ±0.36% (99 runs sampled) +trace-mapping: encoded Object input x 31.77 ops/sec ±13.79% (45 runs sampled) +source-map-js: encoded Object input x 6.45 ops/sec ±5.16% (21 runs sampled) +source-map-0.6.1: encoded Object input x 4.07 ops/sec ±5.24% (15 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed: +trace-mapping: decoded originalPositionFor x 7,183,038 ops/sec ±0.58% (95 runs sampled) +trace-mapping: encoded originalPositionFor x 5,192,185 ops/sec ±0.41% (100 runs sampled) +source-map-js: encoded originalPositionFor x 4,259,489 ops/sec ±0.79% (94 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 3,742,629 ops/sec ±0.71% (95 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 6,270,211 ops/sec ±0.64% (94 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +preact.js.map - 1992 segments + +Memory Usage: +trace-mapping decoded 37128 bytes +trace-mapping encoded 247280 bytes +source-map-js 1143536 bytes +source-map-0.6.1 1290992 bytes +source-map-0.8.0 96544 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 3,483 ops/sec ±0.30% (98 runs sampled) +trace-mapping: encoded JSON input x 6,092 ops/sec ±0.18% (97 runs sampled) +trace-mapping: decoded Object input x 249,076 ops/sec ±0.24% (98 runs sampled) +trace-mapping: encoded Object input x 14,555 ops/sec ±0.48% (100 runs sampled) +source-map-js: encoded Object input x 2,447 ops/sec ±0.36% (99 runs sampled) +source-map-0.6.1: encoded Object input x 1,201 ops/sec ±0.57% (96 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed: +trace-mapping: decoded originalPositionFor x 7,620,192 ops/sec ±0.09% (99 runs sampled) +trace-mapping: encoded originalPositionFor x 6,872,554 ops/sec ±0.30% (97 runs sampled) +source-map-js: encoded originalPositionFor x 2,489,570 ops/sec ±0.35% (94 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 1,698,633 ops/sec ±0.28% (98 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 4,015,644 ops/sec ±0.22% (98 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +react.js.map - 5726 segments + +Memory Usage: +trace-mapping decoded 16176 bytes +trace-mapping encoded 681552 bytes +source-map-js 2418352 bytes +source-map-0.6.1 2443672 bytes +source-map-0.8.0 111768 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 1,720 ops/sec ±0.34% (98 runs sampled) +trace-mapping: encoded JSON input x 4,406 ops/sec ±0.35% (100 runs sampled) +trace-mapping: decoded Object input x 92,122 ops/sec ±0.10% (99 runs sampled) +trace-mapping: encoded Object input x 5,385 ops/sec ±0.37% (99 runs sampled) +source-map-js: encoded Object input x 794 ops/sec ±0.40% (98 runs sampled) +source-map-0.6.1: encoded Object input x 416 ops/sec ±0.54% (91 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed: +trace-mapping: decoded originalPositionFor x 32,759,519 ops/sec ±0.33% (100 runs sampled) +trace-mapping: encoded originalPositionFor x 31,116,306 ops/sec ±0.33% (97 runs sampled) +source-map-js: encoded originalPositionFor x 17,458,435 ops/sec ±0.44% (97 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 12,687,097 ops/sec ±0.43% (95 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 23,538,275 ops/sec ±0.38% (95 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor +``` + +[source-map]: https://www.npmjs.com/package/source-map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs new file mode 100644 index 000000000..8238e0ae7 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs @@ -0,0 +1,580 @@ +import { encode, decode } from '@jridgewell/sourcemap-codec'; +import resolveUri from '@jridgewell/resolve-uri'; + +function resolve(input, base) { + // The base is always treated as a directory, if it's not empty. + // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 + // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 + if (base && !base.endsWith('/')) + base += '/'; + return resolveUri(input, base); +} + +/** + * Removes everything after the last "/", but leaves the slash. + */ +function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} + +const COLUMN = 0; +const SOURCES_INDEX = 1; +const SOURCE_LINE = 2; +const SOURCE_COLUMN = 3; +const NAMES_INDEX = 4; +const REV_GENERATED_LINE = 1; +const REV_GENERATED_COLUMN = 2; + +function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) + return mappings; + // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If + // not, we do not want to modify the consumer's input array. + if (!owned) + mappings = mappings.slice(); + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; +} +function nextUnsortedSegmentLine(mappings, start) { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) + return i; + } + return mappings.length; +} +function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; +} +function sortSegments(line, owned) { + if (!owned) + line = line.slice(); + return line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[COLUMN] - b[COLUMN]; +} + +let found = false; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + found = false; + return low - 1; +} +function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; +} +function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; +} +function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1, + }; +} +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + // lastIndex may be -1 if the previous needle was not found. + low = lastIndex === -1 ? 0 : lastIndex; + } + else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return (state.lastIndex = binarySearch(haystack, needle, low, high)); +} + +// Rebuilds the original source files, with mappings that are ordered by source line/column instead +// of generated line/column. +function buildBySources(decoded, memos) { + const sources = memos.map(buildNullArray); + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) + continue; + const sourceIndex = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const originalSource = sources[sourceIndex]; + const originalLine = (originalSource[sourceLine] || (originalSource[sourceLine] = [])); + const memo = memos[sourceIndex]; + // The binary search either found a match, or it found the left-index just before where the + // segment should go. Either way, we want to insert after that. And there may be multiple + // generated segments associated with an original location, so there may need to move several + // indexes before we find where we need to insert. + let index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine)); + memo.lastIndex = ++index; + insert(originalLine, index, [sourceColumn, i, seg[COLUMN]]); + } + } + return sources; +} +function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} +// Null arrays allow us to use ordered index keys without actually allocating contiguous memory like +// a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations. +// Numeric properties on objects are magically sorted in ascending order by the engine regardless of +// the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending +// order when iterating with for-in. +function buildNullArray() { + return { __proto__: null }; +} + +const AnyMap = function (map, mapUrl) { + const parsed = parse(map); + if (!('sections' in parsed)) { + return new TraceMap(parsed, mapUrl); + } + const mappings = []; + const sources = []; + const sourcesContent = []; + const names = []; + const ignoreList = []; + recurse(parsed, mapUrl, mappings, sources, sourcesContent, names, ignoreList, 0, 0, Infinity, Infinity); + const joined = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + ignoreList, + }; + return presortedDecodedMap(joined); +}; +function parse(map) { + return typeof map === 'string' ? JSON.parse(map) : map; +} +function recurse(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) { + const { sections } = input; + for (let i = 0; i < sections.length; i++) { + const { map, offset } = sections[i]; + let sl = stopLine; + let sc = stopColumn; + if (i + 1 < sections.length) { + const nextOffset = sections[i + 1].offset; + sl = Math.min(stopLine, lineOffset + nextOffset.line); + if (sl === stopLine) { + sc = Math.min(stopColumn, columnOffset + nextOffset.column); + } + else if (sl < stopLine) { + sc = columnOffset + nextOffset.column; + } + } + addSection(map, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset + offset.line, columnOffset + offset.column, sl, sc); + } +} +function addSection(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) { + const parsed = parse(input); + if ('sections' in parsed) + return recurse(...arguments); + const map = new TraceMap(parsed, mapUrl); + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = decodedMappings(map); + const { resolvedSources, sourcesContent: contents, ignoreList: ignores } = map; + append(sources, resolvedSources); + append(names, map.names); + if (contents) + append(sourcesContent, contents); + else + for (let i = 0; i < resolvedSources.length; i++) + sourcesContent.push(null); + if (ignores) + for (let i = 0; i < ignores.length; i++) + ignoreList.push(ignores[i] + sourcesOffset); + for (let i = 0; i < decoded.length; i++) { + const lineI = lineOffset + i; + // We can only add so many lines before we step into the range that the next section's map + // controls. When we get to the last line, then we'll start checking the segments to see if + // they've crossed into the column range. But it may not have any columns that overstep, so we + // still need to check that we don't overstep lines, too. + if (lineI > stopLine) + return; + // The out line may already exist in mappings (if we're continuing the line started by a + // previous section). Or, we may have jumped ahead several lines to start this section. + const out = getLine(mappings, lineI); + // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the + // map can be multiple lines), it doesn't. + const cOffset = i === 0 ? columnOffset : 0; + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + // If this segment steps into the column range that the next section's map controls, we need + // to stop early. + if (lineI === stopLine && column >= stopColumn) + return; + if (seg.length === 1) { + out.push([column]); + continue; + } + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + out.push(seg.length === 4 + ? [column, sourcesIndex, sourceLine, sourceColumn] + : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]); + } + } +} +function append(arr, other) { + for (let i = 0; i < other.length; i++) + arr.push(other[i]); +} +function getLine(arr, index) { + for (let i = arr.length; i <= index; i++) + arr[i] = []; + return arr[index]; +} + +const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; +const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; +const LEAST_UPPER_BOUND = -1; +const GREATEST_LOWER_BOUND = 1; +class TraceMap { + constructor(map, mapUrl) { + const isString = typeof map === 'string'; + if (!isString && map._decodedMemo) + return map; + const parsed = (isString ? JSON.parse(map) : map); + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names || []; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || undefined; + const from = resolve(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve(s || '', from)); + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + } +} +/** + * Typescript doesn't allow friend access to private fields, so this just casts the map into a type + * with public access modifiers. + */ +function cast(map) { + return map; +} +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +function encodedMappings(map) { + var _a; + var _b; + return ((_a = (_b = cast(map))._encoded) !== null && _a !== void 0 ? _a : (_b._encoded = encode(cast(map)._decoded))); +} +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +function decodedMappings(map) { + var _a; + return ((_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded))); +} +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +function traceSegment(map, line, column) { + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return null; + const segments = decoded[line]; + const index = traceSegmentInternal(segments, cast(map)._decodedMemo, line, column, GREATEST_LOWER_BOUND); + return index === -1 ? null : segments[index]; +} +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +function originalPositionFor(map, needle) { + let { line, column, bias } = needle; + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return OMapping(null, null, null, null); + const segments = decoded[line]; + const index = traceSegmentInternal(segments, cast(map)._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND); + if (index === -1) + return OMapping(null, null, null, null); + const segment = segments[index]; + if (segment.length === 1) + return OMapping(null, null, null, null); + const { names, resolvedSources } = map; + return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null); +} +/** + * Finds the generated line/column position of the provided source/line/column source position. + */ +function generatedPositionFor(map, needle) { + const { source, line, column, bias } = needle; + return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false); +} +/** + * Finds all generated line/column positions of the provided source/line/column source position. + */ +function allGeneratedPositionsFor(map, needle) { + const { source, line, column, bias } = needle; + // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit. + return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true); +} +/** + * Iterates each mapping in generated position order. + */ +function eachMapping(map, cb) { + const decoded = decodedMappings(map); + const { names, resolvedSources } = map; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) + name = names[seg[4]]; + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name, + }); + } + } +} +function sourceIndex(map, source) { + const { sources, resolvedSources } = map; + let index = sources.indexOf(source); + if (index === -1) + index = resolvedSources.indexOf(source); + return index; +} +/** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ +function sourceContentFor(map, source) { + const { sourcesContent } = map; + if (sourcesContent == null) + return null; + const index = sourceIndex(map, source); + return index === -1 ? null : sourcesContent[index]; +} +/** + * Determines if the source is marked to ignore by the source map. + */ +function isIgnored(map, source) { + const { ignoreList } = map; + if (ignoreList == null) + return false; + const index = sourceIndex(map, source); + return index === -1 ? false : ignoreList.includes(index); +} +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +function presortedDecodedMap(map, mapUrl) { + const tracer = new TraceMap(clone(map, []), mapUrl); + cast(tracer)._decoded = map.mappings; + return tracer; +} +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +function decodedMap(map) { + return clone(map, decodedMappings(map)); +} +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +function encodedMap(map) { + return clone(map, encodedMappings(map)); +} +function clone(map, mappings) { + return { + version: map.version, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings, + ignoreList: map.ignoreList || map.x_google_ignoreList, + }; +} +function OMapping(source, line, column, name) { + return { source, line, column, name }; +} +function GMapping(line, column) { + return { line, column }; +} +function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } + else if (bias === LEAST_UPPER_BOUND) + index++; + if (index === -1 || index === segments.length) + return -1; + return index; +} +function sliceGeneratedPositions(segments, memo, line, column, bias) { + let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND); + // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in + // insertion order) segment that matched. Even if we did respect the bias when tracing, we would + // still need to call `lowerBound()` to find the first segment, which is slower than just looking + // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the + // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to + // match LEAST_UPPER_BOUND. + if (!found && bias === LEAST_UPPER_BOUND) + min++; + if (min === -1 || min === segments.length) + return []; + // We may have found the segment that started at an earlier column. If this is the case, then we + // need to slice all generated segments that match _that_ column, because all such segments span + // to our desired column. + const matchedColumn = found ? column : segments[min][COLUMN]; + // The binary search is not guaranteed to find the lower bound when a match wasn't found. + if (!found) + min = lowerBound(segments, matchedColumn, min); + const max = upperBound(segments, matchedColumn, min); + const result = []; + for (; min <= max; min++) { + const segment = segments[min]; + result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN])); + } + return result; +} +function generatedPosition(map, source, line, column, bias, all) { + var _a; + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const { sources, resolvedSources } = map; + let sourceIndex = sources.indexOf(source); + if (sourceIndex === -1) + sourceIndex = resolvedSources.indexOf(source); + if (sourceIndex === -1) + return all ? [] : GMapping(null, null); + const generated = ((_a = cast(map))._bySources || (_a._bySources = buildBySources(decodedMappings(map), (cast(map)._bySourceMemos = sources.map(memoizedState))))); + const segments = generated[sourceIndex][line]; + if (segments == null) + return all ? [] : GMapping(null, null); + const memo = cast(map)._bySourceMemos[sourceIndex]; + if (all) + return sliceGeneratedPositions(segments, memo, line, column, bias); + const index = traceSegmentInternal(segments, memo, line, column, bias); + if (index === -1) + return GMapping(null, null); + const segment = segments[index]; + return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]); +} + +export { AnyMap, GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap, allGeneratedPositionsFor, decodedMap, decodedMappings, eachMapping, encodedMap, encodedMappings, generatedPositionFor, isIgnored, originalPositionFor, presortedDecodedMap, sourceContentFor, traceSegment }; +//# sourceMappingURL=trace-mapping.mjs.map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map new file mode 100644 index 000000000..016e4ee4c --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.mjs","sources":["../src/resolve.ts","../src/strip-filename.ts","../src/sourcemap-segment.ts","../src/sort.ts","../src/binary-search.ts","../src/by-source.ts","../src/any-map.ts","../src/trace-mapping.ts"],"sourcesContent":["import resolveUri from '@jridgewell/resolve-uri';\n\nexport default function resolve(input: string, base: string | undefined): string {\n // The base is always treated as a directory, if it's not empty.\n // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327\n // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401\n if (base && !base.endsWith('/')) base += '/';\n\n return resolveUri(input, base);\n}\n","/**\n * Removes everything after the last \"/\", but leaves the slash.\n */\nexport default function stripFilename(path: string | undefined | null): string {\n if (!path) return '';\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n","type GeneratedColumn = number;\ntype SourcesIndex = number;\ntype SourceLine = number;\ntype SourceColumn = number;\ntype NamesIndex = number;\n\ntype GeneratedLine = number;\n\nexport type SourceMapSegment =\n | [GeneratedColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex];\n\nexport type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn];\n\nexport const COLUMN = 0;\nexport const SOURCES_INDEX = 1;\nexport const SOURCE_LINE = 2;\nexport const SOURCE_COLUMN = 3;\nexport const NAMES_INDEX = 4;\n\nexport const REV_GENERATED_LINE = 1;\nexport const REV_GENERATED_COLUMN = 2;\n","import { COLUMN } from './sourcemap-segment';\n\nimport type { SourceMapSegment } from './sourcemap-segment';\n\nexport default function maybeSort(\n mappings: SourceMapSegment[][],\n owned: boolean,\n): SourceMapSegment[][] {\n const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);\n if (unsortedIndex === mappings.length) return mappings;\n\n // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If\n // not, we do not want to modify the consumer's input array.\n if (!owned) mappings = mappings.slice();\n\n for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {\n mappings[i] = sortSegments(mappings[i], owned);\n }\n return mappings;\n}\n\nfunction nextUnsortedSegmentLine(mappings: SourceMapSegment[][], start: number): number {\n for (let i = start; i < mappings.length; i++) {\n if (!isSorted(mappings[i])) return i;\n }\n return mappings.length;\n}\n\nfunction isSorted(line: SourceMapSegment[]): boolean {\n for (let j = 1; j < line.length; j++) {\n if (line[j][COLUMN] < line[j - 1][COLUMN]) {\n return false;\n }\n }\n return true;\n}\n\nfunction sortSegments(line: SourceMapSegment[], owned: boolean): SourceMapSegment[] {\n if (!owned) line = line.slice();\n return line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[COLUMN] - b[COLUMN];\n}\n","import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';\nimport { COLUMN } from './sourcemap-segment';\n\nexport type MemoState = {\n lastKey: number;\n lastNeedle: number;\n lastIndex: number;\n};\n\nexport let found = false;\n\n/**\n * A binary search implementation that returns the index if a match is found.\n * If no match is found, then the left-index (the index associated with the item that comes just\n * before the desired index) is returned. To maintain proper sort order, a splice would happen at\n * the next index:\n *\n * ```js\n * const array = [1, 3];\n * const needle = 2;\n * const index = binarySearch(array, needle, (item, needle) => item - needle);\n *\n * assert.equal(index, 0);\n * array.splice(index + 1, 0, needle);\n * assert.deepEqual(array, [1, 2, 3]);\n * ```\n */\nexport function binarySearch(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n low: number,\n high: number,\n): number {\n while (low <= high) {\n const mid = low + ((high - low) >> 1);\n const cmp = haystack[mid][COLUMN] - needle;\n\n if (cmp === 0) {\n found = true;\n return mid;\n }\n\n if (cmp < 0) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n\n found = false;\n return low - 1;\n}\n\nexport function upperBound(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n index: number,\n): number {\n for (let i = index + 1; i < haystack.length; index = i++) {\n if (haystack[i][COLUMN] !== needle) break;\n }\n return index;\n}\n\nexport function lowerBound(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n index: number,\n): number {\n for (let i = index - 1; i >= 0; index = i--) {\n if (haystack[i][COLUMN] !== needle) break;\n }\n return index;\n}\n\nexport function memoizedState(): MemoState {\n return {\n lastKey: -1,\n lastNeedle: -1,\n lastIndex: -1,\n };\n}\n\n/**\n * This overly complicated beast is just to record the last tested line/column and the resulting\n * index, allowing us to skip a few tests if mappings are monotonically increasing.\n */\nexport function memoizedBinarySearch(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n state: MemoState,\n key: number,\n): number {\n const { lastKey, lastNeedle, lastIndex } = state;\n\n let low = 0;\n let high = haystack.length - 1;\n if (key === lastKey) {\n if (needle === lastNeedle) {\n found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;\n return lastIndex;\n }\n\n if (needle >= lastNeedle) {\n // lastIndex may be -1 if the previous needle was not found.\n low = lastIndex === -1 ? 0 : lastIndex;\n } else {\n high = lastIndex;\n }\n }\n state.lastKey = key;\n state.lastNeedle = needle;\n\n return (state.lastIndex = binarySearch(haystack, needle, low, high));\n}\n","import { COLUMN, SOURCES_INDEX, SOURCE_LINE, SOURCE_COLUMN } from './sourcemap-segment';\nimport { memoizedBinarySearch, upperBound } from './binary-search';\n\nimport type { ReverseSegment, SourceMapSegment } from './sourcemap-segment';\nimport type { MemoState } from './binary-search';\n\nexport type Source = {\n __proto__: null;\n [line: number]: Exclude[];\n};\n\n// Rebuilds the original source files, with mappings that are ordered by source line/column instead\n// of generated line/column.\nexport default function buildBySources(\n decoded: readonly SourceMapSegment[][],\n memos: MemoState[],\n): Source[] {\n const sources: Source[] = memos.map(buildNullArray);\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n if (seg.length === 1) continue;\n\n const sourceIndex = seg[SOURCES_INDEX];\n const sourceLine = seg[SOURCE_LINE];\n const sourceColumn = seg[SOURCE_COLUMN];\n const originalSource = sources[sourceIndex];\n const originalLine = (originalSource[sourceLine] ||= []);\n const memo = memos[sourceIndex];\n\n // The binary search either found a match, or it found the left-index just before where the\n // segment should go. Either way, we want to insert after that. And there may be multiple\n // generated segments associated with an original location, so there may need to move several\n // indexes before we find where we need to insert.\n let index = upperBound(\n originalLine,\n sourceColumn,\n memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine),\n );\n\n memo.lastIndex = ++index;\n insert(originalLine, index, [sourceColumn, i, seg[COLUMN]]);\n }\n }\n\n return sources;\n}\n\nfunction insert(array: T[], index: number, value: T) {\n for (let i = array.length; i > index; i--) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n}\n\n// Null arrays allow us to use ordered index keys without actually allocating contiguous memory like\n// a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations.\n// Numeric properties on objects are magically sorted in ascending order by the engine regardless of\n// the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending\n// order when iterating with for-in.\nfunction buildNullArray(): T {\n return { __proto__: null } as T;\n}\n","import { TraceMap, presortedDecodedMap, decodedMappings } from './trace-mapping';\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n} from './sourcemap-segment';\n\nimport type {\n DecodedSourceMap,\n DecodedSourceMapXInput,\n EncodedSourceMapXInput,\n SectionedSourceMapXInput,\n SectionedSourceMapInput,\n SectionXInput,\n} from './types';\nimport type { SourceMapSegment } from './sourcemap-segment';\n\ntype AnyMap = {\n new (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap;\n (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap;\n};\n\nexport const AnyMap: AnyMap = function (map, mapUrl) {\n const parsed = parse(map);\n\n if (!('sections' in parsed)) {\n return new TraceMap(parsed as DecodedSourceMapXInput | EncodedSourceMapXInput, mapUrl);\n }\n\n const mappings: SourceMapSegment[][] = [];\n const sources: string[] = [];\n const sourcesContent: (string | null)[] = [];\n const names: string[] = [];\n const ignoreList: number[] = [];\n\n recurse(\n parsed,\n mapUrl,\n mappings,\n sources,\n sourcesContent,\n names,\n ignoreList,\n 0,\n 0,\n Infinity,\n Infinity,\n );\n\n const joined: DecodedSourceMap = {\n version: 3,\n file: parsed.file,\n names,\n sources,\n sourcesContent,\n mappings,\n ignoreList,\n };\n\n return presortedDecodedMap(joined);\n} as AnyMap;\n\nfunction parse(map: T): Exclude {\n return typeof map === 'string' ? JSON.parse(map) : map;\n}\n\nfunction recurse(\n input: SectionedSourceMapXInput,\n mapUrl: string | null | undefined,\n mappings: SourceMapSegment[][],\n sources: string[],\n sourcesContent: (string | null)[],\n names: string[],\n ignoreList: number[],\n lineOffset: number,\n columnOffset: number,\n stopLine: number,\n stopColumn: number,\n) {\n const { sections } = input;\n for (let i = 0; i < sections.length; i++) {\n const { map, offset } = sections[i];\n\n let sl = stopLine;\n let sc = stopColumn;\n if (i + 1 < sections.length) {\n const nextOffset = sections[i + 1].offset;\n sl = Math.min(stopLine, lineOffset + nextOffset.line);\n\n if (sl === stopLine) {\n sc = Math.min(stopColumn, columnOffset + nextOffset.column);\n } else if (sl < stopLine) {\n sc = columnOffset + nextOffset.column;\n }\n }\n\n addSection(\n map,\n mapUrl,\n mappings,\n sources,\n sourcesContent,\n names,\n ignoreList,\n lineOffset + offset.line,\n columnOffset + offset.column,\n sl,\n sc,\n );\n }\n}\n\nfunction addSection(\n input: SectionXInput['map'],\n mapUrl: string | null | undefined,\n mappings: SourceMapSegment[][],\n sources: string[],\n sourcesContent: (string | null)[],\n names: string[],\n ignoreList: number[],\n lineOffset: number,\n columnOffset: number,\n stopLine: number,\n stopColumn: number,\n) {\n const parsed = parse(input);\n if ('sections' in parsed) return recurse(...(arguments as unknown as Parameters));\n\n const map = new TraceMap(parsed, mapUrl);\n const sourcesOffset = sources.length;\n const namesOffset = names.length;\n const decoded = decodedMappings(map);\n const { resolvedSources, sourcesContent: contents, ignoreList: ignores } = map;\n\n append(sources, resolvedSources);\n append(names, map.names);\n\n if (contents) append(sourcesContent, contents);\n else for (let i = 0; i < resolvedSources.length; i++) sourcesContent.push(null);\n\n if (ignores) for (let i = 0; i < ignores.length; i++) ignoreList.push(ignores[i] + sourcesOffset);\n\n for (let i = 0; i < decoded.length; i++) {\n const lineI = lineOffset + i;\n\n // We can only add so many lines before we step into the range that the next section's map\n // controls. When we get to the last line, then we'll start checking the segments to see if\n // they've crossed into the column range. But it may not have any columns that overstep, so we\n // still need to check that we don't overstep lines, too.\n if (lineI > stopLine) return;\n\n // The out line may already exist in mappings (if we're continuing the line started by a\n // previous section). Or, we may have jumped ahead several lines to start this section.\n const out = getLine(mappings, lineI);\n // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the\n // map can be multiple lines), it doesn't.\n const cOffset = i === 0 ? columnOffset : 0;\n\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n const column = cOffset + seg[COLUMN];\n\n // If this segment steps into the column range that the next section's map controls, we need\n // to stop early.\n if (lineI === stopLine && column >= stopColumn) return;\n\n if (seg.length === 1) {\n out.push([column]);\n continue;\n }\n\n const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX];\n const sourceLine = seg[SOURCE_LINE];\n const sourceColumn = seg[SOURCE_COLUMN];\n out.push(\n seg.length === 4\n ? [column, sourcesIndex, sourceLine, sourceColumn]\n : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]],\n );\n }\n }\n}\n\nfunction append(arr: T[], other: T[]) {\n for (let i = 0; i < other.length; i++) arr.push(other[i]);\n}\n\nfunction getLine(arr: T[][], index: number): T[] {\n for (let i = arr.length; i <= index; i++) arr[i] = [];\n return arr[index];\n}\n","import { encode, decode } from '@jridgewell/sourcemap-codec';\n\nimport resolve from './resolve';\nimport stripFilename from './strip-filename';\nimport maybeSort from './sort';\nimport buildBySources from './by-source';\nimport {\n memoizedState,\n memoizedBinarySearch,\n upperBound,\n lowerBound,\n found as bsFound,\n} from './binary-search';\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n REV_GENERATED_LINE,\n REV_GENERATED_COLUMN,\n} from './sourcemap-segment';\n\nimport type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';\nimport type {\n SourceMapV3,\n DecodedSourceMap,\n EncodedSourceMap,\n InvalidOriginalMapping,\n OriginalMapping,\n InvalidGeneratedMapping,\n GeneratedMapping,\n SourceMapInput,\n Needle,\n SourceNeedle,\n SourceMap,\n EachMapping,\n Bias,\n XInput,\n} from './types';\nimport type { Source } from './by-source';\nimport type { MemoState } from './binary-search';\n\nexport type { SourceMapSegment } from './sourcemap-segment';\nexport type {\n SourceMap,\n DecodedSourceMap,\n EncodedSourceMap,\n Section,\n SectionedSourceMap,\n SourceMapV3,\n Bias,\n EachMapping,\n GeneratedMapping,\n InvalidGeneratedMapping,\n InvalidOriginalMapping,\n Needle,\n OriginalMapping,\n OriginalMapping as Mapping,\n SectionedSourceMapInput,\n SourceMapInput,\n SourceNeedle,\n XInput,\n EncodedSourceMapXInput,\n DecodedSourceMapXInput,\n SectionedSourceMapXInput,\n SectionXInput,\n} from './types';\n\ninterface PublicMap {\n _encoded: TraceMap['_encoded'];\n _decoded: TraceMap['_decoded'];\n _decodedMemo: TraceMap['_decodedMemo'];\n _bySources: TraceMap['_bySources'];\n _bySourceMemos: TraceMap['_bySourceMemos'];\n}\n\nconst LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';\nconst COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';\n\nexport const LEAST_UPPER_BOUND = -1;\nexport const GREATEST_LOWER_BOUND = 1;\n\nexport { AnyMap } from './any-map';\n\nexport class TraceMap implements SourceMap {\n declare version: SourceMapV3['version'];\n declare file: SourceMapV3['file'];\n declare names: SourceMapV3['names'];\n declare sourceRoot: SourceMapV3['sourceRoot'];\n declare sources: SourceMapV3['sources'];\n declare sourcesContent: SourceMapV3['sourcesContent'];\n declare ignoreList: SourceMapV3['ignoreList'];\n\n declare resolvedSources: string[];\n private declare _encoded: string | undefined;\n\n private declare _decoded: SourceMapSegment[][] | undefined;\n private declare _decodedMemo: MemoState;\n\n private declare _bySources: Source[] | undefined;\n private declare _bySourceMemos: MemoState[] | undefined;\n\n constructor(map: SourceMapInput, mapUrl?: string | null) {\n const isString = typeof map === 'string';\n\n if (!isString && (map as unknown as { _decodedMemo: any })._decodedMemo) return map as TraceMap;\n\n const parsed = (isString ? JSON.parse(map) : map) as DecodedSourceMap | EncodedSourceMap;\n\n const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;\n this.version = version;\n this.file = file;\n this.names = names || [];\n this.sourceRoot = sourceRoot;\n this.sources = sources;\n this.sourcesContent = sourcesContent;\n this.ignoreList = parsed.ignoreList || (parsed as XInput).x_google_ignoreList || undefined;\n\n const from = resolve(sourceRoot || '', stripFilename(mapUrl));\n this.resolvedSources = sources.map((s) => resolve(s || '', from));\n\n const { mappings } = parsed;\n if (typeof mappings === 'string') {\n this._encoded = mappings;\n this._decoded = undefined;\n } else {\n this._encoded = undefined;\n this._decoded = maybeSort(mappings, isString);\n }\n\n this._decodedMemo = memoizedState();\n this._bySources = undefined;\n this._bySourceMemos = undefined;\n }\n}\n\n/**\n * Typescript doesn't allow friend access to private fields, so this just casts the map into a type\n * with public access modifiers.\n */\nfunction cast(map: unknown): PublicMap {\n return map as any;\n}\n\n/**\n * Returns the encoded (VLQ string) form of the SourceMap's mappings field.\n */\nexport function encodedMappings(map: TraceMap): EncodedSourceMap['mappings'] {\n return (cast(map)._encoded ??= encode(cast(map)._decoded!));\n}\n\n/**\n * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.\n */\nexport function decodedMappings(map: TraceMap): Readonly {\n return (cast(map)._decoded ||= decode(cast(map)._encoded!));\n}\n\n/**\n * A low-level API to find the segment associated with a generated line/column (think, from a\n * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.\n */\nexport function traceSegment(\n map: TraceMap,\n line: number,\n column: number,\n): Readonly | null {\n const decoded = decodedMappings(map);\n\n // It's common for parent source maps to have pointers to lines that have no\n // mapping (like a \"//# sourceMappingURL=\") at the end of the child file.\n if (line >= decoded.length) return null;\n\n const segments = decoded[line];\n const index = traceSegmentInternal(\n segments,\n cast(map)._decodedMemo,\n line,\n column,\n GREATEST_LOWER_BOUND,\n );\n\n return index === -1 ? null : segments[index];\n}\n\n/**\n * A higher-level API to find the source/line/column associated with a generated line/column\n * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in\n * `source-map` library.\n */\nexport function originalPositionFor(\n map: TraceMap,\n needle: Needle,\n): OriginalMapping | InvalidOriginalMapping {\n let { line, column, bias } = needle;\n line--;\n if (line < 0) throw new Error(LINE_GTR_ZERO);\n if (column < 0) throw new Error(COL_GTR_EQ_ZERO);\n\n const decoded = decodedMappings(map);\n\n // It's common for parent source maps to have pointers to lines that have no\n // mapping (like a \"//# sourceMappingURL=\") at the end of the child file.\n if (line >= decoded.length) return OMapping(null, null, null, null);\n\n const segments = decoded[line];\n const index = traceSegmentInternal(\n segments,\n cast(map)._decodedMemo,\n line,\n column,\n bias || GREATEST_LOWER_BOUND,\n );\n\n if (index === -1) return OMapping(null, null, null, null);\n\n const segment = segments[index];\n if (segment.length === 1) return OMapping(null, null, null, null);\n\n const { names, resolvedSources } = map;\n return OMapping(\n resolvedSources[segment[SOURCES_INDEX]],\n segment[SOURCE_LINE] + 1,\n segment[SOURCE_COLUMN],\n segment.length === 5 ? names[segment[NAMES_INDEX]] : null,\n );\n}\n\n/**\n * Finds the generated line/column position of the provided source/line/column source position.\n */\nexport function generatedPositionFor(\n map: TraceMap,\n needle: SourceNeedle,\n): GeneratedMapping | InvalidGeneratedMapping {\n const { source, line, column, bias } = needle;\n return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false);\n}\n\n/**\n * Finds all generated line/column positions of the provided source/line/column source position.\n */\nexport function allGeneratedPositionsFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping[] {\n const { source, line, column, bias } = needle;\n // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit.\n return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true);\n}\n\n/**\n * Iterates each mapping in generated position order.\n */\nexport function eachMapping(map: TraceMap, cb: (mapping: EachMapping) => void): void {\n const decoded = decodedMappings(map);\n const { names, resolvedSources } = map;\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n\n const generatedLine = i + 1;\n const generatedColumn = seg[0];\n let source = null;\n let originalLine = null;\n let originalColumn = null;\n let name = null;\n if (seg.length !== 1) {\n source = resolvedSources[seg[1]];\n originalLine = seg[2] + 1;\n originalColumn = seg[3];\n }\n if (seg.length === 5) name = names[seg[4]];\n\n cb({\n generatedLine,\n generatedColumn,\n source,\n originalLine,\n originalColumn,\n name,\n } as EachMapping);\n }\n }\n}\n\nfunction sourceIndex(map: TraceMap, source: string): number {\n const { sources, resolvedSources } = map;\n let index = sources.indexOf(source);\n if (index === -1) index = resolvedSources.indexOf(source);\n return index;\n}\n\n/**\n * Retrieves the source content for a particular source, if its found. Returns null if not.\n */\nexport function sourceContentFor(map: TraceMap, source: string): string | null {\n const { sourcesContent } = map;\n if (sourcesContent == null) return null;\n const index = sourceIndex(map, source);\n return index === -1 ? null : sourcesContent[index];\n}\n\n/**\n * Determines if the source is marked to ignore by the source map.\n */\nexport function isIgnored(map: TraceMap, source: string): boolean {\n const { ignoreList } = map;\n if (ignoreList == null) return false;\n const index = sourceIndex(map, source);\n return index === -1 ? false : ignoreList.includes(index);\n}\n\n/**\n * A helper that skips sorting of the input map's mappings array, which can be expensive for larger\n * maps.\n */\nexport function presortedDecodedMap(map: DecodedSourceMap, mapUrl?: string): TraceMap {\n const tracer = new TraceMap(clone(map, []), mapUrl);\n cast(tracer)._decoded = map.mappings;\n return tracer;\n}\n\n/**\n * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport function decodedMap(\n map: TraceMap,\n): Omit & { mappings: readonly SourceMapSegment[][] } {\n return clone(map, decodedMappings(map));\n}\n\n/**\n * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport function encodedMap(map: TraceMap): EncodedSourceMap {\n return clone(map, encodedMappings(map));\n}\n\nfunction clone(\n map: TraceMap | DecodedSourceMap,\n mappings: T,\n): T extends string ? EncodedSourceMap : DecodedSourceMap {\n return {\n version: map.version,\n file: map.file,\n names: map.names,\n sourceRoot: map.sourceRoot,\n sources: map.sources,\n sourcesContent: map.sourcesContent,\n mappings,\n ignoreList: map.ignoreList || (map as XInput).x_google_ignoreList,\n } as any;\n}\n\nfunction OMapping(source: null, line: null, column: null, name: null): InvalidOriginalMapping;\nfunction OMapping(\n source: string,\n line: number,\n column: number,\n name: string | null,\n): OriginalMapping;\nfunction OMapping(\n source: string | null,\n line: number | null,\n column: number | null,\n name: string | null,\n): OriginalMapping | InvalidOriginalMapping {\n return { source, line, column, name } as any;\n}\n\nfunction GMapping(line: null, column: null): InvalidGeneratedMapping;\nfunction GMapping(line: number, column: number): GeneratedMapping;\nfunction GMapping(\n line: number | null,\n column: number | null,\n): GeneratedMapping | InvalidGeneratedMapping {\n return { line, column } as any;\n}\n\nfunction traceSegmentInternal(\n segments: SourceMapSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number;\nfunction traceSegmentInternal(\n segments: ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number;\nfunction traceSegmentInternal(\n segments: SourceMapSegment[] | ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number {\n let index = memoizedBinarySearch(segments, column, memo, line);\n if (bsFound) {\n index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);\n } else if (bias === LEAST_UPPER_BOUND) index++;\n\n if (index === -1 || index === segments.length) return -1;\n return index;\n}\n\nfunction sliceGeneratedPositions(\n segments: ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): GeneratedMapping[] {\n let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND);\n\n // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in\n // insertion order) segment that matched. Even if we did respect the bias when tracing, we would\n // still need to call `lowerBound()` to find the first segment, which is slower than just looking\n // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the\n // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to\n // match LEAST_UPPER_BOUND.\n if (!bsFound && bias === LEAST_UPPER_BOUND) min++;\n\n if (min === -1 || min === segments.length) return [];\n\n // We may have found the segment that started at an earlier column. If this is the case, then we\n // need to slice all generated segments that match _that_ column, because all such segments span\n // to our desired column.\n const matchedColumn = bsFound ? column : segments[min][COLUMN];\n\n // The binary search is not guaranteed to find the lower bound when a match wasn't found.\n if (!bsFound) min = lowerBound(segments, matchedColumn, min);\n const max = upperBound(segments, matchedColumn, min);\n\n const result = [];\n for (; min <= max; min++) {\n const segment = segments[min];\n result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]));\n }\n return result;\n}\n\nfunction generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: false,\n): GeneratedMapping | InvalidGeneratedMapping;\nfunction generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: true,\n): GeneratedMapping[];\nfunction generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: boolean,\n): GeneratedMapping | InvalidGeneratedMapping | GeneratedMapping[] {\n line--;\n if (line < 0) throw new Error(LINE_GTR_ZERO);\n if (column < 0) throw new Error(COL_GTR_EQ_ZERO);\n\n const { sources, resolvedSources } = map;\n let sourceIndex = sources.indexOf(source);\n if (sourceIndex === -1) sourceIndex = resolvedSources.indexOf(source);\n if (sourceIndex === -1) return all ? [] : GMapping(null, null);\n\n const generated = (cast(map)._bySources ||= buildBySources(\n decodedMappings(map),\n (cast(map)._bySourceMemos = sources.map(memoizedState)),\n ));\n\n const segments = generated[sourceIndex][line];\n if (segments == null) return all ? [] : GMapping(null, null);\n\n const memo = cast(map)._bySourceMemos![sourceIndex];\n\n if (all) return sliceGeneratedPositions(segments, memo, line, column, bias);\n\n const index = traceSegmentInternal(segments, memo, line, column, bias);\n if (index === -1) return GMapping(null, null);\n\n const segment = segments[index];\n return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]);\n}\n"],"names":["bsFound"],"mappings":";;;AAEc,SAAU,OAAO,CAAC,KAAa,EAAE,IAAwB,EAAA;;;;IAIrE,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,IAAI,IAAI,GAAG,CAAC;AAE7C,IAAA,OAAO,UAAU,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;AACjC;;ACTA;;AAEG;AACqB,SAAA,aAAa,CAAC,IAA+B,EAAA;AACnE,IAAA,IAAI,CAAC,IAAI;AAAE,QAAA,OAAO,EAAE,CAAC;IACrB,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;IACpC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;AAClC;;ACQO,MAAM,MAAM,GAAG,CAAC,CAAC;AACjB,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,WAAW,GAAG,CAAC,CAAC;AACtB,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,WAAW,GAAG,CAAC,CAAC;AAEtB,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAC7B,MAAM,oBAAoB,GAAG,CAAC;;AClBvB,SAAU,SAAS,CAC/B,QAA8B,EAC9B,KAAc,EAAA;IAEd,MAAM,aAAa,GAAG,uBAAuB,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;AAC3D,IAAA,IAAI,aAAa,KAAK,QAAQ,CAAC,MAAM;AAAE,QAAA,OAAO,QAAQ,CAAC;;;AAIvD,IAAA,IAAI,CAAC,KAAK;AAAE,QAAA,QAAQ,GAAG,QAAQ,CAAC,KAAK,EAAE,CAAC;IAExC,KAAK,IAAI,CAAC,GAAG,aAAa,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,GAAG,uBAAuB,CAAC,QAAQ,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE;AAC7F,QAAA,QAAQ,CAAC,CAAC,CAAC,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;KAChD;AACD,IAAA,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,SAAS,uBAAuB,CAAC,QAA8B,EAAE,KAAa,EAAA;AAC5E,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AAC5C,QAAA,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;AAAE,YAAA,OAAO,CAAC,CAAC;KACtC;IACD,OAAO,QAAQ,CAAC,MAAM,CAAC;AACzB,CAAC;AAED,SAAS,QAAQ,CAAC,IAAwB,EAAA;AACxC,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACpC,QAAA,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE;AACzC,YAAA,OAAO,KAAK,CAAC;SACd;KACF;AACD,IAAA,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,YAAY,CAAC,IAAwB,EAAE,KAAc,EAAA;AAC5D,IAAA,IAAI,CAAC,KAAK;AAAE,QAAA,IAAI,GAAG,IAAI,CAAC,KAAK,EAAE,CAAC;AAChC,IAAA,OAAO,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;AACnC,CAAC;AAED,SAAS,cAAc,CAAC,CAAmB,EAAE,CAAmB,EAAA;IAC9D,OAAO,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC;AAC/B;;ACnCO,IAAI,KAAK,GAAG,KAAK,CAAC;AAEzB;;;;;;;;;;;;;;;AAeG;AACG,SAAU,YAAY,CAC1B,QAA+C,EAC/C,MAAc,EACd,GAAW,EACX,IAAY,EAAA;AAEZ,IAAA,OAAO,GAAG,IAAI,IAAI,EAAE;AAClB,QAAA,MAAM,GAAG,GAAG,GAAG,IAAI,CAAC,IAAI,GAAG,GAAG,KAAK,CAAC,CAAC,CAAC;QACtC,MAAM,GAAG,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;AAE3C,QAAA,IAAI,GAAG,KAAK,CAAC,EAAE;YACb,KAAK,GAAG,IAAI,CAAC;AACb,YAAA,OAAO,GAAG,CAAC;SACZ;AAED,QAAA,IAAI,GAAG,GAAG,CAAC,EAAE;AACX,YAAA,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC;SACf;aAAM;AACL,YAAA,IAAI,GAAG,GAAG,GAAG,CAAC,CAAC;SAChB;KACF;IAED,KAAK,GAAG,KAAK,CAAC;IACd,OAAO,GAAG,GAAG,CAAC,CAAC;AACjB,CAAC;SAEe,UAAU,CACxB,QAA+C,EAC/C,MAAc,EACd,KAAa,EAAA;AAEb,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,KAAK,GAAG,CAAC,EAAE,EAAE;QACxD,IAAI,QAAQ,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,MAAM;YAAE,MAAM;KAC3C;AACD,IAAA,OAAO,KAAK,CAAC;AACf,CAAC;SAEe,UAAU,CACxB,QAA+C,EAC/C,MAAc,EACd,KAAa,EAAA;AAEb,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,EAAE;QAC3C,IAAI,QAAQ,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,MAAM;YAAE,MAAM;KAC3C;AACD,IAAA,OAAO,KAAK,CAAC;AACf,CAAC;SAEe,aAAa,GAAA;IAC3B,OAAO;QACL,OAAO,EAAE,CAAC,CAAC;QACX,UAAU,EAAE,CAAC,CAAC;QACd,SAAS,EAAE,CAAC,CAAC;KACd,CAAC;AACJ,CAAC;AAED;;;AAGG;AACG,SAAU,oBAAoB,CAClC,QAA+C,EAC/C,MAAc,EACd,KAAgB,EAChB,GAAW,EAAA;IAEX,MAAM,EAAE,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,GAAG,KAAK,CAAC;IAEjD,IAAI,GAAG,GAAG,CAAC,CAAC;AACZ,IAAA,IAAI,IAAI,GAAG,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;AAC/B,IAAA,IAAI,GAAG,KAAK,OAAO,EAAE;AACnB,QAAA,IAAI,MAAM,KAAK,UAAU,EAAE;AACzB,YAAA,KAAK,GAAG,SAAS,KAAK,CAAC,CAAC,IAAI,QAAQ,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,KAAK,MAAM,CAAC;AACnE,YAAA,OAAO,SAAS,CAAC;SAClB;AAED,QAAA,IAAI,MAAM,IAAI,UAAU,EAAE;;AAExB,YAAA,GAAG,GAAG,SAAS,KAAK,CAAC,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC;SACxC;aAAM;YACL,IAAI,GAAG,SAAS,CAAC;SAClB;KACF;AACD,IAAA,KAAK,CAAC,OAAO,GAAG,GAAG,CAAC;AACpB,IAAA,KAAK,CAAC,UAAU,GAAG,MAAM,CAAC;AAE1B,IAAA,QAAQ,KAAK,CAAC,SAAS,GAAG,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE;AACvE;;ACvGA;AACA;AACc,SAAU,cAAc,CACpC,OAAsC,EACtC,KAAkB,EAAA;IAElB,MAAM,OAAO,GAAa,KAAK,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;AAEpD,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACvC,QAAA,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AACxB,QAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACpC,YAAA,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,YAAA,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC;gBAAE,SAAS;AAE/B,YAAA,MAAM,WAAW,GAAG,GAAG,CAAC,aAAa,CAAC,CAAC;AACvC,YAAA,MAAM,UAAU,GAAG,GAAG,CAAC,WAAW,CAAC,CAAC;AACpC,YAAA,MAAM,YAAY,GAAG,GAAG,CAAC,aAAa,CAAC,CAAC;AACxC,YAAA,MAAM,cAAc,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;AAC5C,YAAA,MAAM,YAAY,IAAI,cAAc,CAAC,UAAU,CAAzB,KAAA,cAAc,CAAC,UAAU,CAAM,GAAA,EAAE,EAAC,CAAC;AACzD,YAAA,MAAM,IAAI,GAAG,KAAK,CAAC,WAAW,CAAC,CAAC;;;;;AAMhC,YAAA,IAAI,KAAK,GAAG,UAAU,CACpB,YAAY,EACZ,YAAY,EACZ,oBAAoB,CAAC,YAAY,EAAE,YAAY,EAAE,IAAI,EAAE,UAAU,CAAC,CACnE,CAAC;AAEF,YAAA,IAAI,CAAC,SAAS,GAAG,EAAE,KAAK,CAAC;AACzB,YAAA,MAAM,CAAC,YAAY,EAAE,KAAK,EAAE,CAAC,YAAY,EAAE,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;SAC7D;KACF;AAED,IAAA,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,SAAS,MAAM,CAAI,KAAU,EAAE,KAAa,EAAE,KAAQ,EAAA;AACpD,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE;QACzC,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;KACzB;AACD,IAAA,KAAK,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;AACvB,CAAC;AAED;AACA;AACA;AACA;AACA;AACA,SAAS,cAAc,GAAA;AACrB,IAAA,OAAO,EAAE,SAAS,EAAE,IAAI,EAAO,CAAC;AAClC;;ACxCa,MAAA,MAAM,GAAW,UAAU,GAAG,EAAE,MAAM,EAAA;AACjD,IAAA,MAAM,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC;AAE1B,IAAA,IAAI,EAAE,UAAU,IAAI,MAAM,CAAC,EAAE;AAC3B,QAAA,OAAO,IAAI,QAAQ,CAAC,MAAyD,EAAE,MAAM,CAAC,CAAC;KACxF;IAED,MAAM,QAAQ,GAAyB,EAAE,CAAC;IAC1C,MAAM,OAAO,GAAa,EAAE,CAAC;IAC7B,MAAM,cAAc,GAAsB,EAAE,CAAC;IAC7C,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,MAAM,UAAU,GAAa,EAAE,CAAC;IAEhC,OAAO,CACL,MAAM,EACN,MAAM,EACN,QAAQ,EACR,OAAO,EACP,cAAc,EACd,KAAK,EACL,UAAU,EACV,CAAC,EACD,CAAC,EACD,QAAQ,EACR,QAAQ,CACT,CAAC;AAEF,IAAA,MAAM,MAAM,GAAqB;AAC/B,QAAA,OAAO,EAAE,CAAC;QACV,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,KAAK;QACL,OAAO;QACP,cAAc;QACd,QAAQ;QACR,UAAU;KACX,CAAC;AAEF,IAAA,OAAO,mBAAmB,CAAC,MAAM,CAAC,CAAC;AACrC,EAAY;AAEZ,SAAS,KAAK,CAAI,GAAM,EAAA;AACtB,IAAA,OAAO,OAAO,GAAG,KAAK,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC;AACzD,CAAC;AAED,SAAS,OAAO,CACd,KAA+B,EAC/B,MAAiC,EACjC,QAA8B,EAC9B,OAAiB,EACjB,cAAiC,EACjC,KAAe,EACf,UAAoB,EACpB,UAAkB,EAClB,YAAoB,EACpB,QAAgB,EAChB,UAAkB,EAAA;AAElB,IAAA,MAAM,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAC;AAC3B,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACxC,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;QAEpC,IAAI,EAAE,GAAG,QAAQ,CAAC;QAClB,IAAI,EAAE,GAAG,UAAU,CAAC;QACpB,IAAI,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE;YAC3B,MAAM,UAAU,GAAG,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC;AAC1C,YAAA,EAAE,GAAG,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,UAAU,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC;AAEtD,YAAA,IAAI,EAAE,KAAK,QAAQ,EAAE;AACnB,gBAAA,EAAE,GAAG,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,YAAY,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;aAC7D;AAAM,iBAAA,IAAI,EAAE,GAAG,QAAQ,EAAE;AACxB,gBAAA,EAAE,GAAG,YAAY,GAAG,UAAU,CAAC,MAAM,CAAC;aACvC;SACF;AAED,QAAA,UAAU,CACR,GAAG,EACH,MAAM,EACN,QAAQ,EACR,OAAO,EACP,cAAc,EACd,KAAK,EACL,UAAU,EACV,UAAU,GAAG,MAAM,CAAC,IAAI,EACxB,YAAY,GAAG,MAAM,CAAC,MAAM,EAC5B,EAAE,EACF,EAAE,CACH,CAAC;KACH;AACH,CAAC;AAED,SAAS,UAAU,CACjB,KAA2B,EAC3B,MAAiC,EACjC,QAA8B,EAC9B,OAAiB,EACjB,cAAiC,EACjC,KAAe,EACf,UAAoB,EACpB,UAAkB,EAClB,YAAoB,EACpB,QAAgB,EAChB,UAAkB,EAAA;AAElB,IAAA,MAAM,MAAM,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC;IAC5B,IAAI,UAAU,IAAI,MAAM;AAAE,QAAA,OAAO,OAAO,CAAC,GAAI,SAAmD,CAAC,CAAC;IAElG,MAAM,GAAG,GAAG,IAAI,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AACzC,IAAA,MAAM,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC;AACrC,IAAA,MAAM,WAAW,GAAG,KAAK,CAAC,MAAM,CAAC;AACjC,IAAA,MAAM,OAAO,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;AACrC,IAAA,MAAM,EAAE,eAAe,EAAE,cAAc,EAAE,QAAQ,EAAE,UAAU,EAAE,OAAO,EAAE,GAAG,GAAG,CAAC;AAE/E,IAAA,MAAM,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;AACjC,IAAA,MAAM,CAAC,KAAK,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC;AAEzB,IAAA,IAAI,QAAQ;AAAE,QAAA,MAAM,CAAC,cAAc,EAAE,QAAQ,CAAC,CAAC;;AAC1C,QAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,eAAe,CAAC,MAAM,EAAE,CAAC,EAAE;AAAE,YAAA,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAEhF,IAAA,IAAI,OAAO;AAAE,QAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE;YAAE,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,aAAa,CAAC,CAAC;AAElG,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACvC,QAAA,MAAM,KAAK,GAAG,UAAU,GAAG,CAAC,CAAC;;;;;QAM7B,IAAI,KAAK,GAAG,QAAQ;YAAE,OAAO;;;QAI7B,MAAM,GAAG,GAAG,OAAO,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;;;AAGrC,QAAA,MAAM,OAAO,GAAG,CAAC,KAAK,CAAC,GAAG,YAAY,GAAG,CAAC,CAAC;AAE3C,QAAA,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AACxB,QAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACpC,YAAA,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;YACpB,MAAM,MAAM,GAAG,OAAO,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC;;;AAIrC,YAAA,IAAI,KAAK,KAAK,QAAQ,IAAI,MAAM,IAAI,UAAU;gBAAE,OAAO;AAEvD,YAAA,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC,EAAE;AACpB,gBAAA,GAAG,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;gBACnB,SAAS;aACV;YAED,MAAM,YAAY,GAAG,aAAa,GAAG,GAAG,CAAC,aAAa,CAAC,CAAC;AACxD,YAAA,MAAM,UAAU,GAAG,GAAG,CAAC,WAAW,CAAC,CAAC;AACpC,YAAA,MAAM,YAAY,GAAG,GAAG,CAAC,aAAa,CAAC,CAAC;AACxC,YAAA,GAAG,CAAC,IAAI,CACN,GAAG,CAAC,MAAM,KAAK,CAAC;kBACZ,CAAC,MAAM,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,CAAC;AAClD,kBAAE,CAAC,MAAM,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,WAAW,GAAG,GAAG,CAAC,WAAW,CAAC,CAAC,CACrF,CAAC;SACH;KACF;AACH,CAAC;AAED,SAAS,MAAM,CAAI,GAAQ,EAAE,KAAU,EAAA;AACrC,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE;QAAE,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;AAC5D,CAAC;AAED,SAAS,OAAO,CAAI,GAAU,EAAE,KAAa,EAAA;AAC3C,IAAA,KAAK,IAAI,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,IAAI,KAAK,EAAE,CAAC,EAAE;AAAE,QAAA,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;AACtD,IAAA,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC;AACpB;;ACpHA,MAAM,aAAa,GAAG,uDAAuD,CAAC;AAC9E,MAAM,eAAe,GAAG,yEAAyE,CAAC;AAErF,MAAA,iBAAiB,GAAG,CAAC,EAAE;AAC7B,MAAM,oBAAoB,GAAG,EAAE;MAIzB,QAAQ,CAAA;IAkBnB,WAAY,CAAA,GAAmB,EAAE,MAAsB,EAAA;AACrD,QAAA,MAAM,QAAQ,GAAG,OAAO,GAAG,KAAK,QAAQ,CAAC;AAEzC,QAAA,IAAI,CAAC,QAAQ,IAAK,GAAwC,CAAC,YAAY;AAAE,YAAA,OAAO,GAAe,CAAC;AAEhG,QAAA,MAAM,MAAM,IAAI,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,GAAG,CAAwC,CAAC;AAEzF,QAAA,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE,cAAc,EAAE,GAAG,MAAM,CAAC;AAC7E,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;AACvB,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;AACjB,QAAA,IAAI,CAAC,KAAK,GAAG,KAAK,IAAI,EAAE,CAAC;AACzB,QAAA,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;AAC7B,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;AACvB,QAAA,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;AACrC,QAAA,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,IAAK,MAAiB,CAAC,mBAAmB,IAAI,SAAS,CAAC;AAE3F,QAAA,MAAM,IAAI,GAAG,OAAO,CAAC,UAAU,IAAI,EAAE,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC;QAC9D,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,IAAI,CAAC,CAAC,CAAC;AAElE,QAAA,MAAM,EAAE,QAAQ,EAAE,GAAG,MAAM,CAAC;AAC5B,QAAA,IAAI,OAAO,QAAQ,KAAK,QAAQ,EAAE;AAChC,YAAA,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;AACzB,YAAA,IAAI,CAAC,QAAQ,GAAG,SAAS,CAAC;SAC3B;aAAM;AACL,YAAA,IAAI,CAAC,QAAQ,GAAG,SAAS,CAAC;YAC1B,IAAI,CAAC,QAAQ,GAAG,SAAS,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;SAC/C;AAED,QAAA,IAAI,CAAC,YAAY,GAAG,aAAa,EAAE,CAAC;AACpC,QAAA,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;AAC5B,QAAA,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;KACjC;AACF,CAAA;AAED;;;AAGG;AACH,SAAS,IAAI,CAAC,GAAY,EAAA;AACxB,IAAA,OAAO,GAAU,CAAC;AACpB,CAAC;AAED;;AAEG;AACG,SAAU,eAAe,CAAC,GAAa,EAAA;;;IAC3C,QAAO,CAAA,EAAA,GAAA,CAAA,EAAA,GAAC,IAAI,CAAC,GAAG,CAAC,EAAC,QAAQ,uCAAR,QAAQ,GAAK,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,QAAS,CAAC,GAAE;AAC9D,CAAC;AAED;;AAEG;AACG,SAAU,eAAe,CAAC,GAAa,EAAA;;IAC3C,QAAO,CAAA,EAAA,GAAC,IAAI,CAAC,GAAG,CAAC,EAAC,QAAQ,QAAR,QAAQ,GAAK,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,QAAS,CAAC,GAAE;AAC9D,CAAC;AAED;;;AAGG;SACa,YAAY,CAC1B,GAAa,EACb,IAAY,EACZ,MAAc,EAAA;AAEd,IAAA,MAAM,OAAO,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;;;AAIrC,IAAA,IAAI,IAAI,IAAI,OAAO,CAAC,MAAM;AAAE,QAAA,OAAO,IAAI,CAAC;AAExC,IAAA,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAC/B,IAAA,MAAM,KAAK,GAAG,oBAAoB,CAChC,QAAQ,EACR,IAAI,CAAC,GAAG,CAAC,CAAC,YAAY,EACtB,IAAI,EACJ,MAAM,EACN,oBAAoB,CACrB,CAAC;AAEF,IAAA,OAAO,KAAK,KAAK,CAAC,CAAC,GAAG,IAAI,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;AAC/C,CAAC;AAED;;;;AAIG;AACa,SAAA,mBAAmB,CACjC,GAAa,EACb,MAAc,EAAA;IAEd,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC;AACpC,IAAA,IAAI,EAAE,CAAC;IACP,IAAI,IAAI,GAAG,CAAC;AAAE,QAAA,MAAM,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC;IAC7C,IAAI,MAAM,GAAG,CAAC;AAAE,QAAA,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;AAEjD,IAAA,MAAM,OAAO,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;;;AAIrC,IAAA,IAAI,IAAI,IAAI,OAAO,CAAC,MAAM;QAAE,OAAO,QAAQ,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAEpE,IAAA,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/B,MAAM,KAAK,GAAG,oBAAoB,CAChC,QAAQ,EACR,IAAI,CAAC,GAAG,CAAC,CAAC,YAAY,EACtB,IAAI,EACJ,MAAM,EACN,IAAI,IAAI,oBAAoB,CAC7B,CAAC;IAEF,IAAI,KAAK,KAAK,CAAC,CAAC;QAAE,OAAO,QAAQ,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAE1D,IAAA,MAAM,OAAO,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;AAChC,IAAA,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,QAAQ,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAElE,IAAA,MAAM,EAAE,KAAK,EAAE,eAAe,EAAE,GAAG,GAAG,CAAC;AACvC,IAAA,OAAO,QAAQ,CACb,eAAe,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,EACvC,OAAO,CAAC,WAAW,CAAC,GAAG,CAAC,EACxB,OAAO,CAAC,aAAa,CAAC,EACtB,OAAO,CAAC,MAAM,KAAK,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,GAAG,IAAI,CAC1D,CAAC;AACJ,CAAC;AAED;;AAEG;AACa,SAAA,oBAAoB,CAClC,GAAa,EACb,MAAoB,EAAA;IAEpB,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC;AAC9C,IAAA,OAAO,iBAAiB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,IAAI,oBAAoB,EAAE,KAAK,CAAC,CAAC;AAC3F,CAAC;AAED;;AAEG;AACa,SAAA,wBAAwB,CAAC,GAAa,EAAE,MAAoB,EAAA;IAC1E,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC;;AAE9C,IAAA,OAAO,iBAAiB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,IAAI,iBAAiB,EAAE,IAAI,CAAC,CAAC;AACvF,CAAC;AAED;;AAEG;AACa,SAAA,WAAW,CAAC,GAAa,EAAE,EAAkC,EAAA;AAC3E,IAAA,MAAM,OAAO,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;AACrC,IAAA,MAAM,EAAE,KAAK,EAAE,eAAe,EAAE,GAAG,GAAG,CAAC;AAEvC,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACvC,QAAA,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AACxB,QAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACpC,YAAA,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AAEpB,YAAA,MAAM,aAAa,GAAG,CAAC,GAAG,CAAC,CAAC;AAC5B,YAAA,MAAM,eAAe,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC;YAC/B,IAAI,MAAM,GAAG,IAAI,CAAC;YAClB,IAAI,YAAY,GAAG,IAAI,CAAC;YACxB,IAAI,cAAc,GAAG,IAAI,CAAC;YAC1B,IAAI,IAAI,GAAG,IAAI,CAAC;AAChB,YAAA,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC,EAAE;gBACpB,MAAM,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AACjC,gBAAA,YAAY,GAAG,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;AAC1B,gBAAA,cAAc,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC;aACzB;AACD,YAAA,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC;gBAAE,IAAI,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AAE3C,YAAA,EAAE,CAAC;gBACD,aAAa;gBACb,eAAe;gBACf,MAAM;gBACN,YAAY;gBACZ,cAAc;gBACd,IAAI;AACU,aAAA,CAAC,CAAC;SACnB;KACF;AACH,CAAC;AAED,SAAS,WAAW,CAAC,GAAa,EAAE,MAAc,EAAA;AAChD,IAAA,MAAM,EAAE,OAAO,EAAE,eAAe,EAAE,GAAG,GAAG,CAAC;IACzC,IAAI,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACpC,IAAI,KAAK,KAAK,CAAC,CAAC;AAAE,QAAA,KAAK,GAAG,eAAe,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;AAC1D,IAAA,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;AAEG;AACa,SAAA,gBAAgB,CAAC,GAAa,EAAE,MAAc,EAAA;AAC5D,IAAA,MAAM,EAAE,cAAc,EAAE,GAAG,GAAG,CAAC;IAC/B,IAAI,cAAc,IAAI,IAAI;AAAE,QAAA,OAAO,IAAI,CAAC;IACxC,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;AACvC,IAAA,OAAO,KAAK,KAAK,CAAC,CAAC,GAAG,IAAI,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;AACrD,CAAC;AAED;;AAEG;AACa,SAAA,SAAS,CAAC,GAAa,EAAE,MAAc,EAAA;AACrD,IAAA,MAAM,EAAE,UAAU,EAAE,GAAG,GAAG,CAAC;IAC3B,IAAI,UAAU,IAAI,IAAI;AAAE,QAAA,OAAO,KAAK,CAAC;IACrC,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;AACvC,IAAA,OAAO,KAAK,KAAK,CAAC,CAAC,GAAG,KAAK,GAAG,UAAU,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AAC3D,CAAC;AAED;;;AAGG;AACa,SAAA,mBAAmB,CAAC,GAAqB,EAAE,MAAe,EAAA;AACxE,IAAA,MAAM,MAAM,GAAG,IAAI,QAAQ,CAAC,KAAK,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC;IACpD,IAAI,CAAC,MAAM,CAAC,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAQ,CAAC;AACrC,IAAA,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;AAGG;AACG,SAAU,UAAU,CACxB,GAAa,EAAA;IAEb,OAAO,KAAK,CAAC,GAAG,EAAE,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC;AAC1C,CAAC;AAED;;;AAGG;AACG,SAAU,UAAU,CAAC,GAAa,EAAA;IACtC,OAAO,KAAK,CAAC,GAAG,EAAE,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC;AAC1C,CAAC;AAED,SAAS,KAAK,CACZ,GAAgC,EAChC,QAAW,EAAA;IAEX,OAAO;QACL,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,IAAI,EAAE,GAAG,CAAC,IAAI;QACd,KAAK,EAAE,GAAG,CAAC,KAAK;QAChB,UAAU,EAAE,GAAG,CAAC,UAAU;QAC1B,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,cAAc,EAAE,GAAG,CAAC,cAAc;QAClC,QAAQ;AACR,QAAA,UAAU,EAAE,GAAG,CAAC,UAAU,IAAK,GAAc,CAAC,mBAAmB;KAC3D,CAAC;AACX,CAAC;AASD,SAAS,QAAQ,CACf,MAAqB,EACrB,IAAmB,EACnB,MAAqB,EACrB,IAAmB,EAAA;IAEnB,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAS,CAAC;AAC/C,CAAC;AAID,SAAS,QAAQ,CACf,IAAmB,EACnB,MAAqB,EAAA;AAErB,IAAA,OAAO,EAAE,IAAI,EAAE,MAAM,EAAS,CAAC;AACjC,CAAC;AAgBD,SAAS,oBAAoB,CAC3B,QAA+C,EAC/C,IAAe,EACf,IAAY,EACZ,MAAc,EACd,IAAU,EAAA;AAEV,IAAA,IAAI,KAAK,GAAG,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAC/D,IAAIA,KAAO,EAAE;QACX,KAAK,GAAG,CAAC,IAAI,KAAK,iBAAiB,GAAG,UAAU,GAAG,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;KACzF;SAAM,IAAI,IAAI,KAAK,iBAAiB;AAAE,QAAA,KAAK,EAAE,CAAC;IAE/C,IAAI,KAAK,KAAK,CAAC,CAAC,IAAI,KAAK,KAAK,QAAQ,CAAC,MAAM;QAAE,OAAO,CAAC,CAAC,CAAC;AACzD,IAAA,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,uBAAuB,CAC9B,QAA0B,EAC1B,IAAe,EACf,IAAY,EACZ,MAAc,EACd,IAAU,EAAA;AAEV,IAAA,IAAI,GAAG,GAAG,oBAAoB,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,oBAAoB,CAAC,CAAC;;;;;;;AAQnF,IAAA,IAAI,CAACA,KAAO,IAAI,IAAI,KAAK,iBAAiB;AAAE,QAAA,GAAG,EAAE,CAAC;IAElD,IAAI,GAAG,KAAK,CAAC,CAAC,IAAI,GAAG,KAAK,QAAQ,CAAC,MAAM;AAAE,QAAA,OAAO,EAAE,CAAC;;;;AAKrD,IAAA,MAAM,aAAa,GAAGA,KAAO,GAAG,MAAM,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC;;AAG/D,IAAA,IAAI,CAACA,KAAO;QAAE,GAAG,GAAG,UAAU,CAAC,QAAQ,EAAE,aAAa,EAAE,GAAG,CAAC,CAAC;IAC7D,MAAM,GAAG,GAAG,UAAU,CAAC,QAAQ,EAAE,aAAa,EAAE,GAAG,CAAC,CAAC;IAErD,MAAM,MAAM,GAAG,EAAE,CAAC;AAClB,IAAA,OAAO,GAAG,IAAI,GAAG,EAAE,GAAG,EAAE,EAAE;AACxB,QAAA,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;AAC9B,QAAA,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,kBAAkB,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC;KACvF;AACD,IAAA,OAAO,MAAM,CAAC;AAChB,CAAC;AAkBD,SAAS,iBAAiB,CACxB,GAAa,EACb,MAAc,EACd,IAAY,EACZ,MAAc,EACd,IAAU,EACV,GAAY,EAAA;;AAEZ,IAAA,IAAI,EAAE,CAAC;IACP,IAAI,IAAI,GAAG,CAAC;AAAE,QAAA,MAAM,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC;IAC7C,IAAI,MAAM,GAAG,CAAC;AAAE,QAAA,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;AAEjD,IAAA,MAAM,EAAE,OAAO,EAAE,eAAe,EAAE,GAAG,GAAG,CAAC;IACzC,IAAI,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAC1C,IAAI,WAAW,KAAK,CAAC,CAAC;AAAE,QAAA,WAAW,GAAG,eAAe,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACtE,IAAI,WAAW,KAAK,CAAC,CAAC;AAAE,QAAA,OAAO,GAAG,GAAG,EAAE,GAAG,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AAE/D,IAAA,MAAM,SAAS,IAAG,CAAA,EAAA,GAAC,IAAI,CAAC,GAAG,CAAC,EAAC,UAAU,KAAA,EAAA,CAAV,UAAU,GAAK,cAAc,CACxD,eAAe,CAAC,GAAG,CAAC,GACnB,IAAI,CAAC,GAAG,CAAC,CAAC,cAAc,GAAG,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,EACvD,EAAC,CAAC;IAEH,MAAM,QAAQ,GAAG,SAAS,CAAC,WAAW,CAAC,CAAC,IAAI,CAAC,CAAC;IAC9C,IAAI,QAAQ,IAAI,IAAI;AAAE,QAAA,OAAO,GAAG,GAAG,EAAE,GAAG,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAE7D,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,cAAe,CAAC,WAAW,CAAC,CAAC;AAEpD,IAAA,IAAI,GAAG;AAAE,QAAA,OAAO,uBAAuB,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;AAE5E,IAAA,MAAM,KAAK,GAAG,oBAAoB,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;IACvE,IAAI,KAAK,KAAK,CAAC,CAAC;AAAE,QAAA,OAAO,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AAE9C,IAAA,MAAM,OAAO,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;AAChC,IAAA,OAAO,QAAQ,CAAC,OAAO,CAAC,kBAAkB,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC;AAClF;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js new file mode 100644 index 000000000..3be0f36ef --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js @@ -0,0 +1,600 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@jridgewell/sourcemap-codec'), require('@jridgewell/resolve-uri')) : + typeof define === 'function' && define.amd ? define(['exports', '@jridgewell/sourcemap-codec', '@jridgewell/resolve-uri'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.traceMapping = {}, global.sourcemapCodec, global.resolveURI)); +})(this, (function (exports, sourcemapCodec, resolveUri) { 'use strict'; + + function resolve(input, base) { + // The base is always treated as a directory, if it's not empty. + // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 + // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 + if (base && !base.endsWith('/')) + base += '/'; + return resolveUri(input, base); + } + + /** + * Removes everything after the last "/", but leaves the slash. + */ + function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); + } + + const COLUMN = 0; + const SOURCES_INDEX = 1; + const SOURCE_LINE = 2; + const SOURCE_COLUMN = 3; + const NAMES_INDEX = 4; + const REV_GENERATED_LINE = 1; + const REV_GENERATED_COLUMN = 2; + + function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) + return mappings; + // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If + // not, we do not want to modify the consumer's input array. + if (!owned) + mappings = mappings.slice(); + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; + } + function nextUnsortedSegmentLine(mappings, start) { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) + return i; + } + return mappings.length; + } + function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; + } + function sortSegments(line, owned) { + if (!owned) + line = line.slice(); + return line.sort(sortComparator); + } + function sortComparator(a, b) { + return a[COLUMN] - b[COLUMN]; + } + + let found = false; + /** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ + function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + found = false; + return low - 1; + } + function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; + } + function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; + } + function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1, + }; + } + /** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ + function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + // lastIndex may be -1 if the previous needle was not found. + low = lastIndex === -1 ? 0 : lastIndex; + } + else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return (state.lastIndex = binarySearch(haystack, needle, low, high)); + } + + // Rebuilds the original source files, with mappings that are ordered by source line/column instead + // of generated line/column. + function buildBySources(decoded, memos) { + const sources = memos.map(buildNullArray); + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) + continue; + const sourceIndex = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const originalSource = sources[sourceIndex]; + const originalLine = (originalSource[sourceLine] || (originalSource[sourceLine] = [])); + const memo = memos[sourceIndex]; + // The binary search either found a match, or it found the left-index just before where the + // segment should go. Either way, we want to insert after that. And there may be multiple + // generated segments associated with an original location, so there may need to move several + // indexes before we find where we need to insert. + let index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine)); + memo.lastIndex = ++index; + insert(originalLine, index, [sourceColumn, i, seg[COLUMN]]); + } + } + return sources; + } + function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; + } + // Null arrays allow us to use ordered index keys without actually allocating contiguous memory like + // a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations. + // Numeric properties on objects are magically sorted in ascending order by the engine regardless of + // the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending + // order when iterating with for-in. + function buildNullArray() { + return { __proto__: null }; + } + + const AnyMap = function (map, mapUrl) { + const parsed = parse(map); + if (!('sections' in parsed)) { + return new TraceMap(parsed, mapUrl); + } + const mappings = []; + const sources = []; + const sourcesContent = []; + const names = []; + const ignoreList = []; + recurse(parsed, mapUrl, mappings, sources, sourcesContent, names, ignoreList, 0, 0, Infinity, Infinity); + const joined = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + ignoreList, + }; + return presortedDecodedMap(joined); + }; + function parse(map) { + return typeof map === 'string' ? JSON.parse(map) : map; + } + function recurse(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) { + const { sections } = input; + for (let i = 0; i < sections.length; i++) { + const { map, offset } = sections[i]; + let sl = stopLine; + let sc = stopColumn; + if (i + 1 < sections.length) { + const nextOffset = sections[i + 1].offset; + sl = Math.min(stopLine, lineOffset + nextOffset.line); + if (sl === stopLine) { + sc = Math.min(stopColumn, columnOffset + nextOffset.column); + } + else if (sl < stopLine) { + sc = columnOffset + nextOffset.column; + } + } + addSection(map, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset + offset.line, columnOffset + offset.column, sl, sc); + } + } + function addSection(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) { + const parsed = parse(input); + if ('sections' in parsed) + return recurse(...arguments); + const map = new TraceMap(parsed, mapUrl); + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = decodedMappings(map); + const { resolvedSources, sourcesContent: contents, ignoreList: ignores } = map; + append(sources, resolvedSources); + append(names, map.names); + if (contents) + append(sourcesContent, contents); + else + for (let i = 0; i < resolvedSources.length; i++) + sourcesContent.push(null); + if (ignores) + for (let i = 0; i < ignores.length; i++) + ignoreList.push(ignores[i] + sourcesOffset); + for (let i = 0; i < decoded.length; i++) { + const lineI = lineOffset + i; + // We can only add so many lines before we step into the range that the next section's map + // controls. When we get to the last line, then we'll start checking the segments to see if + // they've crossed into the column range. But it may not have any columns that overstep, so we + // still need to check that we don't overstep lines, too. + if (lineI > stopLine) + return; + // The out line may already exist in mappings (if we're continuing the line started by a + // previous section). Or, we may have jumped ahead several lines to start this section. + const out = getLine(mappings, lineI); + // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the + // map can be multiple lines), it doesn't. + const cOffset = i === 0 ? columnOffset : 0; + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + // If this segment steps into the column range that the next section's map controls, we need + // to stop early. + if (lineI === stopLine && column >= stopColumn) + return; + if (seg.length === 1) { + out.push([column]); + continue; + } + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + out.push(seg.length === 4 + ? [column, sourcesIndex, sourceLine, sourceColumn] + : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]); + } + } + } + function append(arr, other) { + for (let i = 0; i < other.length; i++) + arr.push(other[i]); + } + function getLine(arr, index) { + for (let i = arr.length; i <= index; i++) + arr[i] = []; + return arr[index]; + } + + const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; + const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; + const LEAST_UPPER_BOUND = -1; + const GREATEST_LOWER_BOUND = 1; + class TraceMap { + constructor(map, mapUrl) { + const isString = typeof map === 'string'; + if (!isString && map._decodedMemo) + return map; + const parsed = (isString ? JSON.parse(map) : map); + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names || []; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || undefined; + const from = resolve(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve(s || '', from)); + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + } + } + /** + * Typescript doesn't allow friend access to private fields, so this just casts the map into a type + * with public access modifiers. + */ + function cast(map) { + return map; + } + /** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ + function encodedMappings(map) { + var _a; + var _b; + return ((_a = (_b = cast(map))._encoded) !== null && _a !== void 0 ? _a : (_b._encoded = sourcemapCodec.encode(cast(map)._decoded))); + } + /** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ + function decodedMappings(map) { + var _a; + return ((_a = cast(map))._decoded || (_a._decoded = sourcemapCodec.decode(cast(map)._encoded))); + } + /** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ + function traceSegment(map, line, column) { + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return null; + const segments = decoded[line]; + const index = traceSegmentInternal(segments, cast(map)._decodedMemo, line, column, GREATEST_LOWER_BOUND); + return index === -1 ? null : segments[index]; + } + /** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ + function originalPositionFor(map, needle) { + let { line, column, bias } = needle; + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return OMapping(null, null, null, null); + const segments = decoded[line]; + const index = traceSegmentInternal(segments, cast(map)._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND); + if (index === -1) + return OMapping(null, null, null, null); + const segment = segments[index]; + if (segment.length === 1) + return OMapping(null, null, null, null); + const { names, resolvedSources } = map; + return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null); + } + /** + * Finds the generated line/column position of the provided source/line/column source position. + */ + function generatedPositionFor(map, needle) { + const { source, line, column, bias } = needle; + return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false); + } + /** + * Finds all generated line/column positions of the provided source/line/column source position. + */ + function allGeneratedPositionsFor(map, needle) { + const { source, line, column, bias } = needle; + // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit. + return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true); + } + /** + * Iterates each mapping in generated position order. + */ + function eachMapping(map, cb) { + const decoded = decodedMappings(map); + const { names, resolvedSources } = map; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) + name = names[seg[4]]; + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name, + }); + } + } + } + function sourceIndex(map, source) { + const { sources, resolvedSources } = map; + let index = sources.indexOf(source); + if (index === -1) + index = resolvedSources.indexOf(source); + return index; + } + /** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ + function sourceContentFor(map, source) { + const { sourcesContent } = map; + if (sourcesContent == null) + return null; + const index = sourceIndex(map, source); + return index === -1 ? null : sourcesContent[index]; + } + /** + * Determines if the source is marked to ignore by the source map. + */ + function isIgnored(map, source) { + const { ignoreList } = map; + if (ignoreList == null) + return false; + const index = sourceIndex(map, source); + return index === -1 ? false : ignoreList.includes(index); + } + /** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ + function presortedDecodedMap(map, mapUrl) { + const tracer = new TraceMap(clone(map, []), mapUrl); + cast(tracer)._decoded = map.mappings; + return tracer; + } + /** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + function decodedMap(map) { + return clone(map, decodedMappings(map)); + } + /** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + function encodedMap(map) { + return clone(map, encodedMappings(map)); + } + function clone(map, mappings) { + return { + version: map.version, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings, + ignoreList: map.ignoreList || map.x_google_ignoreList, + }; + } + function OMapping(source, line, column, name) { + return { source, line, column, name }; + } + function GMapping(line, column) { + return { line, column }; + } + function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } + else if (bias === LEAST_UPPER_BOUND) + index++; + if (index === -1 || index === segments.length) + return -1; + return index; + } + function sliceGeneratedPositions(segments, memo, line, column, bias) { + let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND); + // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in + // insertion order) segment that matched. Even if we did respect the bias when tracing, we would + // still need to call `lowerBound()` to find the first segment, which is slower than just looking + // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the + // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to + // match LEAST_UPPER_BOUND. + if (!found && bias === LEAST_UPPER_BOUND) + min++; + if (min === -1 || min === segments.length) + return []; + // We may have found the segment that started at an earlier column. If this is the case, then we + // need to slice all generated segments that match _that_ column, because all such segments span + // to our desired column. + const matchedColumn = found ? column : segments[min][COLUMN]; + // The binary search is not guaranteed to find the lower bound when a match wasn't found. + if (!found) + min = lowerBound(segments, matchedColumn, min); + const max = upperBound(segments, matchedColumn, min); + const result = []; + for (; min <= max; min++) { + const segment = segments[min]; + result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN])); + } + return result; + } + function generatedPosition(map, source, line, column, bias, all) { + var _a; + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const { sources, resolvedSources } = map; + let sourceIndex = sources.indexOf(source); + if (sourceIndex === -1) + sourceIndex = resolvedSources.indexOf(source); + if (sourceIndex === -1) + return all ? [] : GMapping(null, null); + const generated = ((_a = cast(map))._bySources || (_a._bySources = buildBySources(decodedMappings(map), (cast(map)._bySourceMemos = sources.map(memoizedState))))); + const segments = generated[sourceIndex][line]; + if (segments == null) + return all ? [] : GMapping(null, null); + const memo = cast(map)._bySourceMemos[sourceIndex]; + if (all) + return sliceGeneratedPositions(segments, memo, line, column, bias); + const index = traceSegmentInternal(segments, memo, line, column, bias); + if (index === -1) + return GMapping(null, null); + const segment = segments[index]; + return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]); + } + + exports.AnyMap = AnyMap; + exports.GREATEST_LOWER_BOUND = GREATEST_LOWER_BOUND; + exports.LEAST_UPPER_BOUND = LEAST_UPPER_BOUND; + exports.TraceMap = TraceMap; + exports.allGeneratedPositionsFor = allGeneratedPositionsFor; + exports.decodedMap = decodedMap; + exports.decodedMappings = decodedMappings; + exports.eachMapping = eachMapping; + exports.encodedMap = encodedMap; + exports.encodedMappings = encodedMappings; + exports.generatedPositionFor = generatedPositionFor; + exports.isIgnored = isIgnored; + exports.originalPositionFor = originalPositionFor; + exports.presortedDecodedMap = presortedDecodedMap; + exports.sourceContentFor = sourceContentFor; + exports.traceSegment = traceSegment; + +})); +//# sourceMappingURL=trace-mapping.umd.js.map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map new file mode 100644 index 000000000..c6716eafc --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.umd.js","sources":["../src/resolve.ts","../src/strip-filename.ts","../src/sourcemap-segment.ts","../src/sort.ts","../src/binary-search.ts","../src/by-source.ts","../src/any-map.ts","../src/trace-mapping.ts"],"sourcesContent":["import resolveUri from '@jridgewell/resolve-uri';\n\nexport default function resolve(input: string, base: string | undefined): string {\n // The base is always treated as a directory, if it's not empty.\n // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327\n // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401\n if (base && !base.endsWith('/')) base += '/';\n\n return resolveUri(input, base);\n}\n","/**\n * Removes everything after the last \"/\", but leaves the slash.\n */\nexport default function stripFilename(path: string | undefined | null): string {\n if (!path) return '';\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n","type GeneratedColumn = number;\ntype SourcesIndex = number;\ntype SourceLine = number;\ntype SourceColumn = number;\ntype NamesIndex = number;\n\ntype GeneratedLine = number;\n\nexport type SourceMapSegment =\n | [GeneratedColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex];\n\nexport type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn];\n\nexport const COLUMN = 0;\nexport const SOURCES_INDEX = 1;\nexport const SOURCE_LINE = 2;\nexport const SOURCE_COLUMN = 3;\nexport const NAMES_INDEX = 4;\n\nexport const REV_GENERATED_LINE = 1;\nexport const REV_GENERATED_COLUMN = 2;\n","import { COLUMN } from './sourcemap-segment';\n\nimport type { SourceMapSegment } from './sourcemap-segment';\n\nexport default function maybeSort(\n mappings: SourceMapSegment[][],\n owned: boolean,\n): SourceMapSegment[][] {\n const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);\n if (unsortedIndex === mappings.length) return mappings;\n\n // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If\n // not, we do not want to modify the consumer's input array.\n if (!owned) mappings = mappings.slice();\n\n for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {\n mappings[i] = sortSegments(mappings[i], owned);\n }\n return mappings;\n}\n\nfunction nextUnsortedSegmentLine(mappings: SourceMapSegment[][], start: number): number {\n for (let i = start; i < mappings.length; i++) {\n if (!isSorted(mappings[i])) return i;\n }\n return mappings.length;\n}\n\nfunction isSorted(line: SourceMapSegment[]): boolean {\n for (let j = 1; j < line.length; j++) {\n if (line[j][COLUMN] < line[j - 1][COLUMN]) {\n return false;\n }\n }\n return true;\n}\n\nfunction sortSegments(line: SourceMapSegment[], owned: boolean): SourceMapSegment[] {\n if (!owned) line = line.slice();\n return line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[COLUMN] - b[COLUMN];\n}\n","import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';\nimport { COLUMN } from './sourcemap-segment';\n\nexport type MemoState = {\n lastKey: number;\n lastNeedle: number;\n lastIndex: number;\n};\n\nexport let found = false;\n\n/**\n * A binary search implementation that returns the index if a match is found.\n * If no match is found, then the left-index (the index associated with the item that comes just\n * before the desired index) is returned. To maintain proper sort order, a splice would happen at\n * the next index:\n *\n * ```js\n * const array = [1, 3];\n * const needle = 2;\n * const index = binarySearch(array, needle, (item, needle) => item - needle);\n *\n * assert.equal(index, 0);\n * array.splice(index + 1, 0, needle);\n * assert.deepEqual(array, [1, 2, 3]);\n * ```\n */\nexport function binarySearch(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n low: number,\n high: number,\n): number {\n while (low <= high) {\n const mid = low + ((high - low) >> 1);\n const cmp = haystack[mid][COLUMN] - needle;\n\n if (cmp === 0) {\n found = true;\n return mid;\n }\n\n if (cmp < 0) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n\n found = false;\n return low - 1;\n}\n\nexport function upperBound(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n index: number,\n): number {\n for (let i = index + 1; i < haystack.length; index = i++) {\n if (haystack[i][COLUMN] !== needle) break;\n }\n return index;\n}\n\nexport function lowerBound(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n index: number,\n): number {\n for (let i = index - 1; i >= 0; index = i--) {\n if (haystack[i][COLUMN] !== needle) break;\n }\n return index;\n}\n\nexport function memoizedState(): MemoState {\n return {\n lastKey: -1,\n lastNeedle: -1,\n lastIndex: -1,\n };\n}\n\n/**\n * This overly complicated beast is just to record the last tested line/column and the resulting\n * index, allowing us to skip a few tests if mappings are monotonically increasing.\n */\nexport function memoizedBinarySearch(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n state: MemoState,\n key: number,\n): number {\n const { lastKey, lastNeedle, lastIndex } = state;\n\n let low = 0;\n let high = haystack.length - 1;\n if (key === lastKey) {\n if (needle === lastNeedle) {\n found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;\n return lastIndex;\n }\n\n if (needle >= lastNeedle) {\n // lastIndex may be -1 if the previous needle was not found.\n low = lastIndex === -1 ? 0 : lastIndex;\n } else {\n high = lastIndex;\n }\n }\n state.lastKey = key;\n state.lastNeedle = needle;\n\n return (state.lastIndex = binarySearch(haystack, needle, low, high));\n}\n","import { COLUMN, SOURCES_INDEX, SOURCE_LINE, SOURCE_COLUMN } from './sourcemap-segment';\nimport { memoizedBinarySearch, upperBound } from './binary-search';\n\nimport type { ReverseSegment, SourceMapSegment } from './sourcemap-segment';\nimport type { MemoState } from './binary-search';\n\nexport type Source = {\n __proto__: null;\n [line: number]: Exclude[];\n};\n\n// Rebuilds the original source files, with mappings that are ordered by source line/column instead\n// of generated line/column.\nexport default function buildBySources(\n decoded: readonly SourceMapSegment[][],\n memos: MemoState[],\n): Source[] {\n const sources: Source[] = memos.map(buildNullArray);\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n if (seg.length === 1) continue;\n\n const sourceIndex = seg[SOURCES_INDEX];\n const sourceLine = seg[SOURCE_LINE];\n const sourceColumn = seg[SOURCE_COLUMN];\n const originalSource = sources[sourceIndex];\n const originalLine = (originalSource[sourceLine] ||= []);\n const memo = memos[sourceIndex];\n\n // The binary search either found a match, or it found the left-index just before where the\n // segment should go. Either way, we want to insert after that. And there may be multiple\n // generated segments associated with an original location, so there may need to move several\n // indexes before we find where we need to insert.\n let index = upperBound(\n originalLine,\n sourceColumn,\n memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine),\n );\n\n memo.lastIndex = ++index;\n insert(originalLine, index, [sourceColumn, i, seg[COLUMN]]);\n }\n }\n\n return sources;\n}\n\nfunction insert(array: T[], index: number, value: T) {\n for (let i = array.length; i > index; i--) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n}\n\n// Null arrays allow us to use ordered index keys without actually allocating contiguous memory like\n// a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations.\n// Numeric properties on objects are magically sorted in ascending order by the engine regardless of\n// the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending\n// order when iterating with for-in.\nfunction buildNullArray(): T {\n return { __proto__: null } as T;\n}\n","import { TraceMap, presortedDecodedMap, decodedMappings } from './trace-mapping';\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n} from './sourcemap-segment';\n\nimport type {\n DecodedSourceMap,\n DecodedSourceMapXInput,\n EncodedSourceMapXInput,\n SectionedSourceMapXInput,\n SectionedSourceMapInput,\n SectionXInput,\n} from './types';\nimport type { SourceMapSegment } from './sourcemap-segment';\n\ntype AnyMap = {\n new (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap;\n (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap;\n};\n\nexport const AnyMap: AnyMap = function (map, mapUrl) {\n const parsed = parse(map);\n\n if (!('sections' in parsed)) {\n return new TraceMap(parsed as DecodedSourceMapXInput | EncodedSourceMapXInput, mapUrl);\n }\n\n const mappings: SourceMapSegment[][] = [];\n const sources: string[] = [];\n const sourcesContent: (string | null)[] = [];\n const names: string[] = [];\n const ignoreList: number[] = [];\n\n recurse(\n parsed,\n mapUrl,\n mappings,\n sources,\n sourcesContent,\n names,\n ignoreList,\n 0,\n 0,\n Infinity,\n Infinity,\n );\n\n const joined: DecodedSourceMap = {\n version: 3,\n file: parsed.file,\n names,\n sources,\n sourcesContent,\n mappings,\n ignoreList,\n };\n\n return presortedDecodedMap(joined);\n} as AnyMap;\n\nfunction parse(map: T): Exclude {\n return typeof map === 'string' ? JSON.parse(map) : map;\n}\n\nfunction recurse(\n input: SectionedSourceMapXInput,\n mapUrl: string | null | undefined,\n mappings: SourceMapSegment[][],\n sources: string[],\n sourcesContent: (string | null)[],\n names: string[],\n ignoreList: number[],\n lineOffset: number,\n columnOffset: number,\n stopLine: number,\n stopColumn: number,\n) {\n const { sections } = input;\n for (let i = 0; i < sections.length; i++) {\n const { map, offset } = sections[i];\n\n let sl = stopLine;\n let sc = stopColumn;\n if (i + 1 < sections.length) {\n const nextOffset = sections[i + 1].offset;\n sl = Math.min(stopLine, lineOffset + nextOffset.line);\n\n if (sl === stopLine) {\n sc = Math.min(stopColumn, columnOffset + nextOffset.column);\n } else if (sl < stopLine) {\n sc = columnOffset + nextOffset.column;\n }\n }\n\n addSection(\n map,\n mapUrl,\n mappings,\n sources,\n sourcesContent,\n names,\n ignoreList,\n lineOffset + offset.line,\n columnOffset + offset.column,\n sl,\n sc,\n );\n }\n}\n\nfunction addSection(\n input: SectionXInput['map'],\n mapUrl: string | null | undefined,\n mappings: SourceMapSegment[][],\n sources: string[],\n sourcesContent: (string | null)[],\n names: string[],\n ignoreList: number[],\n lineOffset: number,\n columnOffset: number,\n stopLine: number,\n stopColumn: number,\n) {\n const parsed = parse(input);\n if ('sections' in parsed) return recurse(...(arguments as unknown as Parameters));\n\n const map = new TraceMap(parsed, mapUrl);\n const sourcesOffset = sources.length;\n const namesOffset = names.length;\n const decoded = decodedMappings(map);\n const { resolvedSources, sourcesContent: contents, ignoreList: ignores } = map;\n\n append(sources, resolvedSources);\n append(names, map.names);\n\n if (contents) append(sourcesContent, contents);\n else for (let i = 0; i < resolvedSources.length; i++) sourcesContent.push(null);\n\n if (ignores) for (let i = 0; i < ignores.length; i++) ignoreList.push(ignores[i] + sourcesOffset);\n\n for (let i = 0; i < decoded.length; i++) {\n const lineI = lineOffset + i;\n\n // We can only add so many lines before we step into the range that the next section's map\n // controls. When we get to the last line, then we'll start checking the segments to see if\n // they've crossed into the column range. But it may not have any columns that overstep, so we\n // still need to check that we don't overstep lines, too.\n if (lineI > stopLine) return;\n\n // The out line may already exist in mappings (if we're continuing the line started by a\n // previous section). Or, we may have jumped ahead several lines to start this section.\n const out = getLine(mappings, lineI);\n // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the\n // map can be multiple lines), it doesn't.\n const cOffset = i === 0 ? columnOffset : 0;\n\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n const column = cOffset + seg[COLUMN];\n\n // If this segment steps into the column range that the next section's map controls, we need\n // to stop early.\n if (lineI === stopLine && column >= stopColumn) return;\n\n if (seg.length === 1) {\n out.push([column]);\n continue;\n }\n\n const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX];\n const sourceLine = seg[SOURCE_LINE];\n const sourceColumn = seg[SOURCE_COLUMN];\n out.push(\n seg.length === 4\n ? [column, sourcesIndex, sourceLine, sourceColumn]\n : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]],\n );\n }\n }\n}\n\nfunction append(arr: T[], other: T[]) {\n for (let i = 0; i < other.length; i++) arr.push(other[i]);\n}\n\nfunction getLine(arr: T[][], index: number): T[] {\n for (let i = arr.length; i <= index; i++) arr[i] = [];\n return arr[index];\n}\n","import { encode, decode } from '@jridgewell/sourcemap-codec';\n\nimport resolve from './resolve';\nimport stripFilename from './strip-filename';\nimport maybeSort from './sort';\nimport buildBySources from './by-source';\nimport {\n memoizedState,\n memoizedBinarySearch,\n upperBound,\n lowerBound,\n found as bsFound,\n} from './binary-search';\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n REV_GENERATED_LINE,\n REV_GENERATED_COLUMN,\n} from './sourcemap-segment';\n\nimport type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';\nimport type {\n SourceMapV3,\n DecodedSourceMap,\n EncodedSourceMap,\n InvalidOriginalMapping,\n OriginalMapping,\n InvalidGeneratedMapping,\n GeneratedMapping,\n SourceMapInput,\n Needle,\n SourceNeedle,\n SourceMap,\n EachMapping,\n Bias,\n XInput,\n} from './types';\nimport type { Source } from './by-source';\nimport type { MemoState } from './binary-search';\n\nexport type { SourceMapSegment } from './sourcemap-segment';\nexport type {\n SourceMap,\n DecodedSourceMap,\n EncodedSourceMap,\n Section,\n SectionedSourceMap,\n SourceMapV3,\n Bias,\n EachMapping,\n GeneratedMapping,\n InvalidGeneratedMapping,\n InvalidOriginalMapping,\n Needle,\n OriginalMapping,\n OriginalMapping as Mapping,\n SectionedSourceMapInput,\n SourceMapInput,\n SourceNeedle,\n XInput,\n EncodedSourceMapXInput,\n DecodedSourceMapXInput,\n SectionedSourceMapXInput,\n SectionXInput,\n} from './types';\n\ninterface PublicMap {\n _encoded: TraceMap['_encoded'];\n _decoded: TraceMap['_decoded'];\n _decodedMemo: TraceMap['_decodedMemo'];\n _bySources: TraceMap['_bySources'];\n _bySourceMemos: TraceMap['_bySourceMemos'];\n}\n\nconst LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';\nconst COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';\n\nexport const LEAST_UPPER_BOUND = -1;\nexport const GREATEST_LOWER_BOUND = 1;\n\nexport { AnyMap } from './any-map';\n\nexport class TraceMap implements SourceMap {\n declare version: SourceMapV3['version'];\n declare file: SourceMapV3['file'];\n declare names: SourceMapV3['names'];\n declare sourceRoot: SourceMapV3['sourceRoot'];\n declare sources: SourceMapV3['sources'];\n declare sourcesContent: SourceMapV3['sourcesContent'];\n declare ignoreList: SourceMapV3['ignoreList'];\n\n declare resolvedSources: string[];\n private declare _encoded: string | undefined;\n\n private declare _decoded: SourceMapSegment[][] | undefined;\n private declare _decodedMemo: MemoState;\n\n private declare _bySources: Source[] | undefined;\n private declare _bySourceMemos: MemoState[] | undefined;\n\n constructor(map: SourceMapInput, mapUrl?: string | null) {\n const isString = typeof map === 'string';\n\n if (!isString && (map as unknown as { _decodedMemo: any })._decodedMemo) return map as TraceMap;\n\n const parsed = (isString ? JSON.parse(map) : map) as DecodedSourceMap | EncodedSourceMap;\n\n const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;\n this.version = version;\n this.file = file;\n this.names = names || [];\n this.sourceRoot = sourceRoot;\n this.sources = sources;\n this.sourcesContent = sourcesContent;\n this.ignoreList = parsed.ignoreList || (parsed as XInput).x_google_ignoreList || undefined;\n\n const from = resolve(sourceRoot || '', stripFilename(mapUrl));\n this.resolvedSources = sources.map((s) => resolve(s || '', from));\n\n const { mappings } = parsed;\n if (typeof mappings === 'string') {\n this._encoded = mappings;\n this._decoded = undefined;\n } else {\n this._encoded = undefined;\n this._decoded = maybeSort(mappings, isString);\n }\n\n this._decodedMemo = memoizedState();\n this._bySources = undefined;\n this._bySourceMemos = undefined;\n }\n}\n\n/**\n * Typescript doesn't allow friend access to private fields, so this just casts the map into a type\n * with public access modifiers.\n */\nfunction cast(map: unknown): PublicMap {\n return map as any;\n}\n\n/**\n * Returns the encoded (VLQ string) form of the SourceMap's mappings field.\n */\nexport function encodedMappings(map: TraceMap): EncodedSourceMap['mappings'] {\n return (cast(map)._encoded ??= encode(cast(map)._decoded!));\n}\n\n/**\n * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.\n */\nexport function decodedMappings(map: TraceMap): Readonly {\n return (cast(map)._decoded ||= decode(cast(map)._encoded!));\n}\n\n/**\n * A low-level API to find the segment associated with a generated line/column (think, from a\n * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.\n */\nexport function traceSegment(\n map: TraceMap,\n line: number,\n column: number,\n): Readonly | null {\n const decoded = decodedMappings(map);\n\n // It's common for parent source maps to have pointers to lines that have no\n // mapping (like a \"//# sourceMappingURL=\") at the end of the child file.\n if (line >= decoded.length) return null;\n\n const segments = decoded[line];\n const index = traceSegmentInternal(\n segments,\n cast(map)._decodedMemo,\n line,\n column,\n GREATEST_LOWER_BOUND,\n );\n\n return index === -1 ? null : segments[index];\n}\n\n/**\n * A higher-level API to find the source/line/column associated with a generated line/column\n * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in\n * `source-map` library.\n */\nexport function originalPositionFor(\n map: TraceMap,\n needle: Needle,\n): OriginalMapping | InvalidOriginalMapping {\n let { line, column, bias } = needle;\n line--;\n if (line < 0) throw new Error(LINE_GTR_ZERO);\n if (column < 0) throw new Error(COL_GTR_EQ_ZERO);\n\n const decoded = decodedMappings(map);\n\n // It's common for parent source maps to have pointers to lines that have no\n // mapping (like a \"//# sourceMappingURL=\") at the end of the child file.\n if (line >= decoded.length) return OMapping(null, null, null, null);\n\n const segments = decoded[line];\n const index = traceSegmentInternal(\n segments,\n cast(map)._decodedMemo,\n line,\n column,\n bias || GREATEST_LOWER_BOUND,\n );\n\n if (index === -1) return OMapping(null, null, null, null);\n\n const segment = segments[index];\n if (segment.length === 1) return OMapping(null, null, null, null);\n\n const { names, resolvedSources } = map;\n return OMapping(\n resolvedSources[segment[SOURCES_INDEX]],\n segment[SOURCE_LINE] + 1,\n segment[SOURCE_COLUMN],\n segment.length === 5 ? names[segment[NAMES_INDEX]] : null,\n );\n}\n\n/**\n * Finds the generated line/column position of the provided source/line/column source position.\n */\nexport function generatedPositionFor(\n map: TraceMap,\n needle: SourceNeedle,\n): GeneratedMapping | InvalidGeneratedMapping {\n const { source, line, column, bias } = needle;\n return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false);\n}\n\n/**\n * Finds all generated line/column positions of the provided source/line/column source position.\n */\nexport function allGeneratedPositionsFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping[] {\n const { source, line, column, bias } = needle;\n // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit.\n return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true);\n}\n\n/**\n * Iterates each mapping in generated position order.\n */\nexport function eachMapping(map: TraceMap, cb: (mapping: EachMapping) => void): void {\n const decoded = decodedMappings(map);\n const { names, resolvedSources } = map;\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n\n const generatedLine = i + 1;\n const generatedColumn = seg[0];\n let source = null;\n let originalLine = null;\n let originalColumn = null;\n let name = null;\n if (seg.length !== 1) {\n source = resolvedSources[seg[1]];\n originalLine = seg[2] + 1;\n originalColumn = seg[3];\n }\n if (seg.length === 5) name = names[seg[4]];\n\n cb({\n generatedLine,\n generatedColumn,\n source,\n originalLine,\n originalColumn,\n name,\n } as EachMapping);\n }\n }\n}\n\nfunction sourceIndex(map: TraceMap, source: string): number {\n const { sources, resolvedSources } = map;\n let index = sources.indexOf(source);\n if (index === -1) index = resolvedSources.indexOf(source);\n return index;\n}\n\n/**\n * Retrieves the source content for a particular source, if its found. Returns null if not.\n */\nexport function sourceContentFor(map: TraceMap, source: string): string | null {\n const { sourcesContent } = map;\n if (sourcesContent == null) return null;\n const index = sourceIndex(map, source);\n return index === -1 ? null : sourcesContent[index];\n}\n\n/**\n * Determines if the source is marked to ignore by the source map.\n */\nexport function isIgnored(map: TraceMap, source: string): boolean {\n const { ignoreList } = map;\n if (ignoreList == null) return false;\n const index = sourceIndex(map, source);\n return index === -1 ? false : ignoreList.includes(index);\n}\n\n/**\n * A helper that skips sorting of the input map's mappings array, which can be expensive for larger\n * maps.\n */\nexport function presortedDecodedMap(map: DecodedSourceMap, mapUrl?: string): TraceMap {\n const tracer = new TraceMap(clone(map, []), mapUrl);\n cast(tracer)._decoded = map.mappings;\n return tracer;\n}\n\n/**\n * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport function decodedMap(\n map: TraceMap,\n): Omit & { mappings: readonly SourceMapSegment[][] } {\n return clone(map, decodedMappings(map));\n}\n\n/**\n * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport function encodedMap(map: TraceMap): EncodedSourceMap {\n return clone(map, encodedMappings(map));\n}\n\nfunction clone(\n map: TraceMap | DecodedSourceMap,\n mappings: T,\n): T extends string ? EncodedSourceMap : DecodedSourceMap {\n return {\n version: map.version,\n file: map.file,\n names: map.names,\n sourceRoot: map.sourceRoot,\n sources: map.sources,\n sourcesContent: map.sourcesContent,\n mappings,\n ignoreList: map.ignoreList || (map as XInput).x_google_ignoreList,\n } as any;\n}\n\nfunction OMapping(source: null, line: null, column: null, name: null): InvalidOriginalMapping;\nfunction OMapping(\n source: string,\n line: number,\n column: number,\n name: string | null,\n): OriginalMapping;\nfunction OMapping(\n source: string | null,\n line: number | null,\n column: number | null,\n name: string | null,\n): OriginalMapping | InvalidOriginalMapping {\n return { source, line, column, name } as any;\n}\n\nfunction GMapping(line: null, column: null): InvalidGeneratedMapping;\nfunction GMapping(line: number, column: number): GeneratedMapping;\nfunction GMapping(\n line: number | null,\n column: number | null,\n): GeneratedMapping | InvalidGeneratedMapping {\n return { line, column } as any;\n}\n\nfunction traceSegmentInternal(\n segments: SourceMapSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number;\nfunction traceSegmentInternal(\n segments: ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number;\nfunction traceSegmentInternal(\n segments: SourceMapSegment[] | ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number {\n let index = memoizedBinarySearch(segments, column, memo, line);\n if (bsFound) {\n index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);\n } else if (bias === LEAST_UPPER_BOUND) index++;\n\n if (index === -1 || index === segments.length) return -1;\n return index;\n}\n\nfunction sliceGeneratedPositions(\n segments: ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): GeneratedMapping[] {\n let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND);\n\n // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in\n // insertion order) segment that matched. Even if we did respect the bias when tracing, we would\n // still need to call `lowerBound()` to find the first segment, which is slower than just looking\n // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the\n // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to\n // match LEAST_UPPER_BOUND.\n if (!bsFound && bias === LEAST_UPPER_BOUND) min++;\n\n if (min === -1 || min === segments.length) return [];\n\n // We may have found the segment that started at an earlier column. If this is the case, then we\n // need to slice all generated segments that match _that_ column, because all such segments span\n // to our desired column.\n const matchedColumn = bsFound ? column : segments[min][COLUMN];\n\n // The binary search is not guaranteed to find the lower bound when a match wasn't found.\n if (!bsFound) min = lowerBound(segments, matchedColumn, min);\n const max = upperBound(segments, matchedColumn, min);\n\n const result = [];\n for (; min <= max; min++) {\n const segment = segments[min];\n result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]));\n }\n return result;\n}\n\nfunction generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: false,\n): GeneratedMapping | InvalidGeneratedMapping;\nfunction generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: true,\n): GeneratedMapping[];\nfunction generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: boolean,\n): GeneratedMapping | InvalidGeneratedMapping | GeneratedMapping[] {\n line--;\n if (line < 0) throw new Error(LINE_GTR_ZERO);\n if (column < 0) throw new Error(COL_GTR_EQ_ZERO);\n\n const { sources, resolvedSources } = map;\n let sourceIndex = sources.indexOf(source);\n if (sourceIndex === -1) sourceIndex = resolvedSources.indexOf(source);\n if (sourceIndex === -1) return all ? [] : GMapping(null, null);\n\n const generated = (cast(map)._bySources ||= buildBySources(\n decodedMappings(map),\n (cast(map)._bySourceMemos = sources.map(memoizedState)),\n ));\n\n const segments = generated[sourceIndex][line];\n if (segments == null) return all ? [] : GMapping(null, null);\n\n const memo = cast(map)._bySourceMemos![sourceIndex];\n\n if (all) return sliceGeneratedPositions(segments, memo, line, column, bias);\n\n const index = traceSegmentInternal(segments, memo, line, column, bias);\n if (index === -1) return GMapping(null, null);\n\n const segment = segments[index];\n return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]);\n}\n"],"names":["encode","decode","bsFound"],"mappings":";;;;;;IAEc,SAAU,OAAO,CAAC,KAAa,EAAE,IAAwB,EAAA;;;;QAIrE,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;YAAE,IAAI,IAAI,GAAG,CAAC;IAE7C,IAAA,OAAO,UAAU,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IACjC;;ICTA;;IAEG;IACqB,SAAA,aAAa,CAAC,IAA+B,EAAA;IACnE,IAAA,IAAI,CAAC,IAAI;IAAE,QAAA,OAAO,EAAE,CAAC;QACrB,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;QACpC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;IAClC;;ICQO,MAAM,MAAM,GAAG,CAAC,CAAC;IACjB,MAAM,aAAa,GAAG,CAAC,CAAC;IACxB,MAAM,WAAW,GAAG,CAAC,CAAC;IACtB,MAAM,aAAa,GAAG,CAAC,CAAC;IACxB,MAAM,WAAW,GAAG,CAAC,CAAC;IAEtB,MAAM,kBAAkB,GAAG,CAAC,CAAC;IAC7B,MAAM,oBAAoB,GAAG,CAAC;;IClBvB,SAAU,SAAS,CAC/B,QAA8B,EAC9B,KAAc,EAAA;QAEd,MAAM,aAAa,GAAG,uBAAuB,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;IAC3D,IAAA,IAAI,aAAa,KAAK,QAAQ,CAAC,MAAM;IAAE,QAAA,OAAO,QAAQ,CAAC;;;IAIvD,IAAA,IAAI,CAAC,KAAK;IAAE,QAAA,QAAQ,GAAG,QAAQ,CAAC,KAAK,EAAE,CAAC;QAExC,KAAK,IAAI,CAAC,GAAG,aAAa,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,GAAG,uBAAuB,CAAC,QAAQ,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE;IAC7F,QAAA,QAAQ,CAAC,CAAC,CAAC,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;SAChD;IACD,IAAA,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,SAAS,uBAAuB,CAAC,QAA8B,EAAE,KAAa,EAAA;IAC5E,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IAC5C,QAAA,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;IAAE,YAAA,OAAO,CAAC,CAAC;SACtC;QACD,OAAO,QAAQ,CAAC,MAAM,CAAC;IACzB,CAAC;IAED,SAAS,QAAQ,CAAC,IAAwB,EAAA;IACxC,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IACpC,QAAA,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE;IACzC,YAAA,OAAO,KAAK,CAAC;aACd;SACF;IACD,IAAA,OAAO,IAAI,CAAC;IACd,CAAC;IAED,SAAS,YAAY,CAAC,IAAwB,EAAE,KAAc,EAAA;IAC5D,IAAA,IAAI,CAAC,KAAK;IAAE,QAAA,IAAI,GAAG,IAAI,CAAC,KAAK,EAAE,CAAC;IAChC,IAAA,OAAO,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;IACnC,CAAC;IAED,SAAS,cAAc,CAAC,CAAmB,EAAE,CAAmB,EAAA;QAC9D,OAAO,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC;IAC/B;;ICnCO,IAAI,KAAK,GAAG,KAAK,CAAC;IAEzB;;;;;;;;;;;;;;;IAeG;IACG,SAAU,YAAY,CAC1B,QAA+C,EAC/C,MAAc,EACd,GAAW,EACX,IAAY,EAAA;IAEZ,IAAA,OAAO,GAAG,IAAI,IAAI,EAAE;IAClB,QAAA,MAAM,GAAG,GAAG,GAAG,IAAI,CAAC,IAAI,GAAG,GAAG,KAAK,CAAC,CAAC,CAAC;YACtC,MAAM,GAAG,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;IAE3C,QAAA,IAAI,GAAG,KAAK,CAAC,EAAE;gBACb,KAAK,GAAG,IAAI,CAAC;IACb,YAAA,OAAO,GAAG,CAAC;aACZ;IAED,QAAA,IAAI,GAAG,GAAG,CAAC,EAAE;IACX,YAAA,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC;aACf;iBAAM;IACL,YAAA,IAAI,GAAG,GAAG,GAAG,CAAC,CAAC;aAChB;SACF;QAED,KAAK,GAAG,KAAK,CAAC;QACd,OAAO,GAAG,GAAG,CAAC,CAAC;IACjB,CAAC;aAEe,UAAU,CACxB,QAA+C,EAC/C,MAAc,EACd,KAAa,EAAA;IAEb,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,KAAK,GAAG,CAAC,EAAE,EAAE;YACxD,IAAI,QAAQ,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,MAAM;gBAAE,MAAM;SAC3C;IACD,IAAA,OAAO,KAAK,CAAC;IACf,CAAC;aAEe,UAAU,CACxB,QAA+C,EAC/C,MAAc,EACd,KAAa,EAAA;IAEb,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,EAAE;YAC3C,IAAI,QAAQ,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,MAAM;gBAAE,MAAM;SAC3C;IACD,IAAA,OAAO,KAAK,CAAC;IACf,CAAC;aAEe,aAAa,GAAA;QAC3B,OAAO;YACL,OAAO,EAAE,CAAC,CAAC;YACX,UAAU,EAAE,CAAC,CAAC;YACd,SAAS,EAAE,CAAC,CAAC;SACd,CAAC;IACJ,CAAC;IAED;;;IAGG;IACG,SAAU,oBAAoB,CAClC,QAA+C,EAC/C,MAAc,EACd,KAAgB,EAChB,GAAW,EAAA;QAEX,MAAM,EAAE,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,GAAG,KAAK,CAAC;QAEjD,IAAI,GAAG,GAAG,CAAC,CAAC;IACZ,IAAA,IAAI,IAAI,GAAG,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;IAC/B,IAAA,IAAI,GAAG,KAAK,OAAO,EAAE;IACnB,QAAA,IAAI,MAAM,KAAK,UAAU,EAAE;IACzB,YAAA,KAAK,GAAG,SAAS,KAAK,CAAC,CAAC,IAAI,QAAQ,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,KAAK,MAAM,CAAC;IACnE,YAAA,OAAO,SAAS,CAAC;aAClB;IAED,QAAA,IAAI,MAAM,IAAI,UAAU,EAAE;;IAExB,YAAA,GAAG,GAAG,SAAS,KAAK,CAAC,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC;aACxC;iBAAM;gBACL,IAAI,GAAG,SAAS,CAAC;aAClB;SACF;IACD,IAAA,KAAK,CAAC,OAAO,GAAG,GAAG,CAAC;IACpB,IAAA,KAAK,CAAC,UAAU,GAAG,MAAM,CAAC;IAE1B,IAAA,QAAQ,KAAK,CAAC,SAAS,GAAG,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE;IACvE;;ICvGA;IACA;IACc,SAAU,cAAc,CACpC,OAAsC,EACtC,KAAkB,EAAA;QAElB,MAAM,OAAO,GAAa,KAAK,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;IAEpD,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IACvC,QAAA,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IACxB,QAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IACpC,YAAA,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,YAAA,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC;oBAAE,SAAS;IAE/B,YAAA,MAAM,WAAW,GAAG,GAAG,CAAC,aAAa,CAAC,CAAC;IACvC,YAAA,MAAM,UAAU,GAAG,GAAG,CAAC,WAAW,CAAC,CAAC;IACpC,YAAA,MAAM,YAAY,GAAG,GAAG,CAAC,aAAa,CAAC,CAAC;IACxC,YAAA,MAAM,cAAc,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;IAC5C,YAAA,MAAM,YAAY,IAAI,cAAc,CAAC,UAAU,CAAzB,KAAA,cAAc,CAAC,UAAU,CAAM,GAAA,EAAE,EAAC,CAAC;IACzD,YAAA,MAAM,IAAI,GAAG,KAAK,CAAC,WAAW,CAAC,CAAC;;;;;IAMhC,YAAA,IAAI,KAAK,GAAG,UAAU,CACpB,YAAY,EACZ,YAAY,EACZ,oBAAoB,CAAC,YAAY,EAAE,YAAY,EAAE,IAAI,EAAE,UAAU,CAAC,CACnE,CAAC;IAEF,YAAA,IAAI,CAAC,SAAS,GAAG,EAAE,KAAK,CAAC;IACzB,YAAA,MAAM,CAAC,YAAY,EAAE,KAAK,EAAE,CAAC,YAAY,EAAE,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;aAC7D;SACF;IAED,IAAA,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,SAAS,MAAM,CAAI,KAAU,EAAE,KAAa,EAAE,KAAQ,EAAA;IACpD,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE;YACzC,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;SACzB;IACD,IAAA,KAAK,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;IACvB,CAAC;IAED;IACA;IACA;IACA;IACA;IACA,SAAS,cAAc,GAAA;IACrB,IAAA,OAAO,EAAE,SAAS,EAAE,IAAI,EAAO,CAAC;IAClC;;ACxCa,UAAA,MAAM,GAAW,UAAU,GAAG,EAAE,MAAM,EAAA;IACjD,IAAA,MAAM,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC;IAE1B,IAAA,IAAI,EAAE,UAAU,IAAI,MAAM,CAAC,EAAE;IAC3B,QAAA,OAAO,IAAI,QAAQ,CAAC,MAAyD,EAAE,MAAM,CAAC,CAAC;SACxF;QAED,MAAM,QAAQ,GAAyB,EAAE,CAAC;QAC1C,MAAM,OAAO,GAAa,EAAE,CAAC;QAC7B,MAAM,cAAc,GAAsB,EAAE,CAAC;QAC7C,MAAM,KAAK,GAAa,EAAE,CAAC;QAC3B,MAAM,UAAU,GAAa,EAAE,CAAC;QAEhC,OAAO,CACL,MAAM,EACN,MAAM,EACN,QAAQ,EACR,OAAO,EACP,cAAc,EACd,KAAK,EACL,UAAU,EACV,CAAC,EACD,CAAC,EACD,QAAQ,EACR,QAAQ,CACT,CAAC;IAEF,IAAA,MAAM,MAAM,GAAqB;IAC/B,QAAA,OAAO,EAAE,CAAC;YACV,IAAI,EAAE,MAAM,CAAC,IAAI;YACjB,KAAK;YACL,OAAO;YACP,cAAc;YACd,QAAQ;YACR,UAAU;SACX,CAAC;IAEF,IAAA,OAAO,mBAAmB,CAAC,MAAM,CAAC,CAAC;IACrC,EAAY;IAEZ,SAAS,KAAK,CAAI,GAAM,EAAA;IACtB,IAAA,OAAO,OAAO,GAAG,KAAK,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC;IACzD,CAAC;IAED,SAAS,OAAO,CACd,KAA+B,EAC/B,MAAiC,EACjC,QAA8B,EAC9B,OAAiB,EACjB,cAAiC,EACjC,KAAe,EACf,UAAoB,EACpB,UAAkB,EAClB,YAAoB,EACpB,QAAgB,EAChB,UAAkB,EAAA;IAElB,IAAA,MAAM,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAC;IAC3B,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACxC,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;YAEpC,IAAI,EAAE,GAAG,QAAQ,CAAC;YAClB,IAAI,EAAE,GAAG,UAAU,CAAC;YACpB,IAAI,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE;gBAC3B,MAAM,UAAU,GAAG,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC;IAC1C,YAAA,EAAE,GAAG,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,UAAU,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC;IAEtD,YAAA,IAAI,EAAE,KAAK,QAAQ,EAAE;IACnB,gBAAA,EAAE,GAAG,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,YAAY,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;iBAC7D;IAAM,iBAAA,IAAI,EAAE,GAAG,QAAQ,EAAE;IACxB,gBAAA,EAAE,GAAG,YAAY,GAAG,UAAU,CAAC,MAAM,CAAC;iBACvC;aACF;IAED,QAAA,UAAU,CACR,GAAG,EACH,MAAM,EACN,QAAQ,EACR,OAAO,EACP,cAAc,EACd,KAAK,EACL,UAAU,EACV,UAAU,GAAG,MAAM,CAAC,IAAI,EACxB,YAAY,GAAG,MAAM,CAAC,MAAM,EAC5B,EAAE,EACF,EAAE,CACH,CAAC;SACH;IACH,CAAC;IAED,SAAS,UAAU,CACjB,KAA2B,EAC3B,MAAiC,EACjC,QAA8B,EAC9B,OAAiB,EACjB,cAAiC,EACjC,KAAe,EACf,UAAoB,EACpB,UAAkB,EAClB,YAAoB,EACpB,QAAgB,EAChB,UAAkB,EAAA;IAElB,IAAA,MAAM,MAAM,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC;QAC5B,IAAI,UAAU,IAAI,MAAM;IAAE,QAAA,OAAO,OAAO,CAAC,GAAI,SAAmD,CAAC,CAAC;QAElG,MAAM,GAAG,GAAG,IAAI,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACzC,IAAA,MAAM,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC;IACrC,IAAA,MAAM,WAAW,GAAG,KAAK,CAAC,MAAM,CAAC;IACjC,IAAA,MAAM,OAAO,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;IACrC,IAAA,MAAM,EAAE,eAAe,EAAE,cAAc,EAAE,QAAQ,EAAE,UAAU,EAAE,OAAO,EAAE,GAAG,GAAG,CAAC;IAE/E,IAAA,MAAM,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;IACjC,IAAA,MAAM,CAAC,KAAK,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC;IAEzB,IAAA,IAAI,QAAQ;IAAE,QAAA,MAAM,CAAC,cAAc,EAAE,QAAQ,CAAC,CAAC;;IAC1C,QAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,eAAe,CAAC,MAAM,EAAE,CAAC,EAAE;IAAE,YAAA,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAEhF,IAAA,IAAI,OAAO;IAAE,QAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE;gBAAE,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,aAAa,CAAC,CAAC;IAElG,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IACvC,QAAA,MAAM,KAAK,GAAG,UAAU,GAAG,CAAC,CAAC;;;;;YAM7B,IAAI,KAAK,GAAG,QAAQ;gBAAE,OAAO;;;YAI7B,MAAM,GAAG,GAAG,OAAO,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;;;IAGrC,QAAA,MAAM,OAAO,GAAG,CAAC,KAAK,CAAC,GAAG,YAAY,GAAG,CAAC,CAAC;IAE3C,QAAA,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IACxB,QAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IACpC,YAAA,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;gBACpB,MAAM,MAAM,GAAG,OAAO,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC;;;IAIrC,YAAA,IAAI,KAAK,KAAK,QAAQ,IAAI,MAAM,IAAI,UAAU;oBAAE,OAAO;IAEvD,YAAA,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC,EAAE;IACpB,gBAAA,GAAG,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;oBACnB,SAAS;iBACV;gBAED,MAAM,YAAY,GAAG,aAAa,GAAG,GAAG,CAAC,aAAa,CAAC,CAAC;IACxD,YAAA,MAAM,UAAU,GAAG,GAAG,CAAC,WAAW,CAAC,CAAC;IACpC,YAAA,MAAM,YAAY,GAAG,GAAG,CAAC,aAAa,CAAC,CAAC;IACxC,YAAA,GAAG,CAAC,IAAI,CACN,GAAG,CAAC,MAAM,KAAK,CAAC;sBACZ,CAAC,MAAM,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,CAAC;IAClD,kBAAE,CAAC,MAAM,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,WAAW,GAAG,GAAG,CAAC,WAAW,CAAC,CAAC,CACrF,CAAC;aACH;SACF;IACH,CAAC;IAED,SAAS,MAAM,CAAI,GAAQ,EAAE,KAAU,EAAA;IACrC,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE;YAAE,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAC5D,CAAC;IAED,SAAS,OAAO,CAAI,GAAU,EAAE,KAAa,EAAA;IAC3C,IAAA,KAAK,IAAI,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,IAAI,KAAK,EAAE,CAAC,EAAE;IAAE,QAAA,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;IACtD,IAAA,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC;IACpB;;ICpHA,MAAM,aAAa,GAAG,uDAAuD,CAAC;IAC9E,MAAM,eAAe,GAAG,yEAAyE,CAAC;AAErF,UAAA,iBAAiB,GAAG,CAAC,EAAE;AAC7B,UAAM,oBAAoB,GAAG,EAAE;UAIzB,QAAQ,CAAA;QAkBnB,WAAY,CAAA,GAAmB,EAAE,MAAsB,EAAA;IACrD,QAAA,MAAM,QAAQ,GAAG,OAAO,GAAG,KAAK,QAAQ,CAAC;IAEzC,QAAA,IAAI,CAAC,QAAQ,IAAK,GAAwC,CAAC,YAAY;IAAE,YAAA,OAAO,GAAe,CAAC;IAEhG,QAAA,MAAM,MAAM,IAAI,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,GAAG,CAAwC,CAAC;IAEzF,QAAA,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE,cAAc,EAAE,GAAG,MAAM,CAAC;IAC7E,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACvB,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACjB,QAAA,IAAI,CAAC,KAAK,GAAG,KAAK,IAAI,EAAE,CAAC;IACzB,QAAA,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC7B,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACvB,QAAA,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;IACrC,QAAA,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,IAAK,MAAiB,CAAC,mBAAmB,IAAI,SAAS,CAAC;IAE3F,QAAA,MAAM,IAAI,GAAG,OAAO,CAAC,UAAU,IAAI,EAAE,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC;YAC9D,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,IAAI,CAAC,CAAC,CAAC;IAElE,QAAA,MAAM,EAAE,QAAQ,EAAE,GAAG,MAAM,CAAC;IAC5B,QAAA,IAAI,OAAO,QAAQ,KAAK,QAAQ,EAAE;IAChC,YAAA,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IACzB,YAAA,IAAI,CAAC,QAAQ,GAAG,SAAS,CAAC;aAC3B;iBAAM;IACL,YAAA,IAAI,CAAC,QAAQ,GAAG,SAAS,CAAC;gBAC1B,IAAI,CAAC,QAAQ,GAAG,SAAS,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;aAC/C;IAED,QAAA,IAAI,CAAC,YAAY,GAAG,aAAa,EAAE,CAAC;IACpC,QAAA,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;IAC5B,QAAA,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;SACjC;IACF,CAAA;IAED;;;IAGG;IACH,SAAS,IAAI,CAAC,GAAY,EAAA;IACxB,IAAA,OAAO,GAAU,CAAC;IACpB,CAAC;IAED;;IAEG;IACG,SAAU,eAAe,CAAC,GAAa,EAAA;;;QAC3C,QAAO,CAAA,EAAA,GAAA,CAAA,EAAA,GAAC,IAAI,CAAC,GAAG,CAAC,EAAC,QAAQ,uCAAR,QAAQ,GAAKA,qBAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,QAAS,CAAC,GAAE;IAC9D,CAAC;IAED;;IAEG;IACG,SAAU,eAAe,CAAC,GAAa,EAAA;;QAC3C,QAAO,CAAA,EAAA,GAAC,IAAI,CAAC,GAAG,CAAC,EAAC,QAAQ,QAAR,QAAQ,GAAKC,qBAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,QAAS,CAAC,GAAE;IAC9D,CAAC;IAED;;;IAGG;aACa,YAAY,CAC1B,GAAa,EACb,IAAY,EACZ,MAAc,EAAA;IAEd,IAAA,MAAM,OAAO,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;;;IAIrC,IAAA,IAAI,IAAI,IAAI,OAAO,CAAC,MAAM;IAAE,QAAA,OAAO,IAAI,CAAC;IAExC,IAAA,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/B,IAAA,MAAM,KAAK,GAAG,oBAAoB,CAChC,QAAQ,EACR,IAAI,CAAC,GAAG,CAAC,CAAC,YAAY,EACtB,IAAI,EACJ,MAAM,EACN,oBAAoB,CACrB,CAAC;IAEF,IAAA,OAAO,KAAK,KAAK,CAAC,CAAC,GAAG,IAAI,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC/C,CAAC;IAED;;;;IAIG;IACa,SAAA,mBAAmB,CACjC,GAAa,EACb,MAAc,EAAA;QAEd,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC;IACpC,IAAA,IAAI,EAAE,CAAC;QACP,IAAI,IAAI,GAAG,CAAC;IAAE,QAAA,MAAM,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC;QAC7C,IAAI,MAAM,GAAG,CAAC;IAAE,QAAA,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;IAEjD,IAAA,MAAM,OAAO,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;;;IAIrC,IAAA,IAAI,IAAI,IAAI,OAAO,CAAC,MAAM;YAAE,OAAO,QAAQ,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAEpE,IAAA,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;QAC/B,MAAM,KAAK,GAAG,oBAAoB,CAChC,QAAQ,EACR,IAAI,CAAC,GAAG,CAAC,CAAC,YAAY,EACtB,IAAI,EACJ,MAAM,EACN,IAAI,IAAI,oBAAoB,CAC7B,CAAC;QAEF,IAAI,KAAK,KAAK,CAAC,CAAC;YAAE,OAAO,QAAQ,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAE1D,IAAA,MAAM,OAAO,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IAChC,IAAA,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,QAAQ,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAElE,IAAA,MAAM,EAAE,KAAK,EAAE,eAAe,EAAE,GAAG,GAAG,CAAC;IACvC,IAAA,OAAO,QAAQ,CACb,eAAe,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,EACvC,OAAO,CAAC,WAAW,CAAC,GAAG,CAAC,EACxB,OAAO,CAAC,aAAa,CAAC,EACtB,OAAO,CAAC,MAAM,KAAK,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,GAAG,IAAI,CAC1D,CAAC;IACJ,CAAC;IAED;;IAEG;IACa,SAAA,oBAAoB,CAClC,GAAa,EACb,MAAoB,EAAA;QAEpB,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC;IAC9C,IAAA,OAAO,iBAAiB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,IAAI,oBAAoB,EAAE,KAAK,CAAC,CAAC;IAC3F,CAAC;IAED;;IAEG;IACa,SAAA,wBAAwB,CAAC,GAAa,EAAE,MAAoB,EAAA;QAC1E,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC;;IAE9C,IAAA,OAAO,iBAAiB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,IAAI,iBAAiB,EAAE,IAAI,CAAC,CAAC;IACvF,CAAC;IAED;;IAEG;IACa,SAAA,WAAW,CAAC,GAAa,EAAE,EAAkC,EAAA;IAC3E,IAAA,MAAM,OAAO,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;IACrC,IAAA,MAAM,EAAE,KAAK,EAAE,eAAe,EAAE,GAAG,GAAG,CAAC;IAEvC,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IACvC,QAAA,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IACxB,QAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IACpC,YAAA,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;IAEpB,YAAA,MAAM,aAAa,GAAG,CAAC,GAAG,CAAC,CAAC;IAC5B,YAAA,MAAM,eAAe,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC;gBAC/B,IAAI,MAAM,GAAG,IAAI,CAAC;gBAClB,IAAI,YAAY,GAAG,IAAI,CAAC;gBACxB,IAAI,cAAc,GAAG,IAAI,CAAC;gBAC1B,IAAI,IAAI,GAAG,IAAI,CAAC;IAChB,YAAA,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC,EAAE;oBACpB,MAAM,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IACjC,gBAAA,YAAY,GAAG,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IAC1B,gBAAA,cAAc,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC;iBACzB;IACD,YAAA,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC;oBAAE,IAAI,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAE3C,YAAA,EAAE,CAAC;oBACD,aAAa;oBACb,eAAe;oBACf,MAAM;oBACN,YAAY;oBACZ,cAAc;oBACd,IAAI;IACU,aAAA,CAAC,CAAC;aACnB;SACF;IACH,CAAC;IAED,SAAS,WAAW,CAAC,GAAa,EAAE,MAAc,EAAA;IAChD,IAAA,MAAM,EAAE,OAAO,EAAE,eAAe,EAAE,GAAG,GAAG,CAAC;QACzC,IAAI,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACpC,IAAI,KAAK,KAAK,CAAC,CAAC;IAAE,QAAA,KAAK,GAAG,eAAe,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAC1D,IAAA,OAAO,KAAK,CAAC;IACf,CAAC;IAED;;IAEG;IACa,SAAA,gBAAgB,CAAC,GAAa,EAAE,MAAc,EAAA;IAC5D,IAAA,MAAM,EAAE,cAAc,EAAE,GAAG,GAAG,CAAC;QAC/B,IAAI,cAAc,IAAI,IAAI;IAAE,QAAA,OAAO,IAAI,CAAC;QACxC,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IACvC,IAAA,OAAO,KAAK,KAAK,CAAC,CAAC,GAAG,IAAI,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;IACrD,CAAC;IAED;;IAEG;IACa,SAAA,SAAS,CAAC,GAAa,EAAE,MAAc,EAAA;IACrD,IAAA,MAAM,EAAE,UAAU,EAAE,GAAG,GAAG,CAAC;QAC3B,IAAI,UAAU,IAAI,IAAI;IAAE,QAAA,OAAO,KAAK,CAAC;QACrC,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IACvC,IAAA,OAAO,KAAK,KAAK,CAAC,CAAC,GAAG,KAAK,GAAG,UAAU,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC3D,CAAC;IAED;;;IAGG;IACa,SAAA,mBAAmB,CAAC,GAAqB,EAAE,MAAe,EAAA;IACxE,IAAA,MAAM,MAAM,GAAG,IAAI,QAAQ,CAAC,KAAK,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC;QACpD,IAAI,CAAC,MAAM,CAAC,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAQ,CAAC;IACrC,IAAA,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;IAGG;IACG,SAAU,UAAU,CACxB,GAAa,EAAA;QAEb,OAAO,KAAK,CAAC,GAAG,EAAE,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC;IAC1C,CAAC;IAED;;;IAGG;IACG,SAAU,UAAU,CAAC,GAAa,EAAA;QACtC,OAAO,KAAK,CAAC,GAAG,EAAE,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC;IAC1C,CAAC;IAED,SAAS,KAAK,CACZ,GAAgC,EAChC,QAAW,EAAA;QAEX,OAAO;YACL,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,IAAI,EAAE,GAAG,CAAC,IAAI;YACd,KAAK,EAAE,GAAG,CAAC,KAAK;YAChB,UAAU,EAAE,GAAG,CAAC,UAAU;YAC1B,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,cAAc,EAAE,GAAG,CAAC,cAAc;YAClC,QAAQ;IACR,QAAA,UAAU,EAAE,GAAG,CAAC,UAAU,IAAK,GAAc,CAAC,mBAAmB;SAC3D,CAAC;IACX,CAAC;IASD,SAAS,QAAQ,CACf,MAAqB,EACrB,IAAmB,EACnB,MAAqB,EACrB,IAAmB,EAAA;QAEnB,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAS,CAAC;IAC/C,CAAC;IAID,SAAS,QAAQ,CACf,IAAmB,EACnB,MAAqB,EAAA;IAErB,IAAA,OAAO,EAAE,IAAI,EAAE,MAAM,EAAS,CAAC;IACjC,CAAC;IAgBD,SAAS,oBAAoB,CAC3B,QAA+C,EAC/C,IAAe,EACf,IAAY,EACZ,MAAc,EACd,IAAU,EAAA;IAEV,IAAA,IAAI,KAAK,GAAG,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;QAC/D,IAAIC,KAAO,EAAE;YACX,KAAK,GAAG,CAAC,IAAI,KAAK,iBAAiB,GAAG,UAAU,GAAG,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;SACzF;aAAM,IAAI,IAAI,KAAK,iBAAiB;IAAE,QAAA,KAAK,EAAE,CAAC;QAE/C,IAAI,KAAK,KAAK,CAAC,CAAC,IAAI,KAAK,KAAK,QAAQ,CAAC,MAAM;YAAE,OAAO,CAAC,CAAC,CAAC;IACzD,IAAA,OAAO,KAAK,CAAC;IACf,CAAC;IAED,SAAS,uBAAuB,CAC9B,QAA0B,EAC1B,IAAe,EACf,IAAY,EACZ,MAAc,EACd,IAAU,EAAA;IAEV,IAAA,IAAI,GAAG,GAAG,oBAAoB,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,oBAAoB,CAAC,CAAC;;;;;;;IAQnF,IAAA,IAAI,CAACA,KAAO,IAAI,IAAI,KAAK,iBAAiB;IAAE,QAAA,GAAG,EAAE,CAAC;QAElD,IAAI,GAAG,KAAK,CAAC,CAAC,IAAI,GAAG,KAAK,QAAQ,CAAC,MAAM;IAAE,QAAA,OAAO,EAAE,CAAC;;;;IAKrD,IAAA,MAAM,aAAa,GAAGA,KAAO,GAAG,MAAM,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC;;IAG/D,IAAA,IAAI,CAACA,KAAO;YAAE,GAAG,GAAG,UAAU,CAAC,QAAQ,EAAE,aAAa,EAAE,GAAG,CAAC,CAAC;QAC7D,MAAM,GAAG,GAAG,UAAU,CAAC,QAAQ,EAAE,aAAa,EAAE,GAAG,CAAC,CAAC;QAErD,MAAM,MAAM,GAAG,EAAE,CAAC;IAClB,IAAA,OAAO,GAAG,IAAI,GAAG,EAAE,GAAG,EAAE,EAAE;IACxB,QAAA,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;IAC9B,QAAA,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,kBAAkB,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC;SACvF;IACD,IAAA,OAAO,MAAM,CAAC;IAChB,CAAC;IAkBD,SAAS,iBAAiB,CACxB,GAAa,EACb,MAAc,EACd,IAAY,EACZ,MAAc,EACd,IAAU,EACV,GAAY,EAAA;;IAEZ,IAAA,IAAI,EAAE,CAAC;QACP,IAAI,IAAI,GAAG,CAAC;IAAE,QAAA,MAAM,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC;QAC7C,IAAI,MAAM,GAAG,CAAC;IAAE,QAAA,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;IAEjD,IAAA,MAAM,EAAE,OAAO,EAAE,eAAe,EAAE,GAAG,GAAG,CAAC;QACzC,IAAI,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAC1C,IAAI,WAAW,KAAK,CAAC,CAAC;IAAE,QAAA,WAAW,GAAG,eAAe,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACtE,IAAI,WAAW,KAAK,CAAC,CAAC;IAAE,QAAA,OAAO,GAAG,GAAG,EAAE,GAAG,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAE/D,IAAA,MAAM,SAAS,IAAG,CAAA,EAAA,GAAC,IAAI,CAAC,GAAG,CAAC,EAAC,UAAU,KAAA,EAAA,CAAV,UAAU,GAAK,cAAc,CACxD,eAAe,CAAC,GAAG,CAAC,GACnB,IAAI,CAAC,GAAG,CAAC,CAAC,cAAc,GAAG,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,EACvD,EAAC,CAAC;QAEH,MAAM,QAAQ,GAAG,SAAS,CAAC,WAAW,CAAC,CAAC,IAAI,CAAC,CAAC;QAC9C,IAAI,QAAQ,IAAI,IAAI;IAAE,QAAA,OAAO,GAAG,GAAG,EAAE,GAAG,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QAE7D,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,cAAe,CAAC,WAAW,CAAC,CAAC;IAEpD,IAAA,IAAI,GAAG;IAAE,QAAA,OAAO,uBAAuB,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;IAE5E,IAAA,MAAM,KAAK,GAAG,oBAAoB,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;QACvE,IAAI,KAAK,KAAK,CAAC,CAAC;IAAE,QAAA,OAAO,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAE9C,IAAA,MAAM,OAAO,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IAChC,IAAA,OAAO,QAAQ,CAAC,OAAO,CAAC,kBAAkB,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC;IAClF;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts new file mode 100644 index 000000000..ec775fbea --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts @@ -0,0 +1,8 @@ +import { TraceMap } from './trace-mapping'; +import type { SectionedSourceMapInput } from './types'; +type AnyMap = { + new (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap; + (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap; +}; +export declare const AnyMap: AnyMap; +export {}; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts new file mode 100644 index 000000000..ecb2873c6 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts @@ -0,0 +1,32 @@ +import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment'; +export type MemoState = { + lastKey: number; + lastNeedle: number; + lastIndex: number; +}; +export declare let found: boolean; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +export declare function binarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, low: number, high: number): number; +export declare function upperBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function lowerBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function memoizedState(): MemoState; +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +export declare function memoizedBinarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, state: MemoState, key: number): number; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts new file mode 100644 index 000000000..a91751cd8 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts @@ -0,0 +1,7 @@ +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment'; +import type { MemoState } from './binary-search'; +export type Source = { + __proto__: null; + [line: number]: Exclude[]; +}; +export default function buildBySources(decoded: readonly SourceMapSegment[][], memos: MemoState[]): Source[]; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts new file mode 100644 index 000000000..cf7d4f8a5 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts @@ -0,0 +1 @@ +export default function resolve(input: string, base: string | undefined): string; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts new file mode 100644 index 000000000..2bfb5dc10 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts @@ -0,0 +1,2 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +export default function maybeSort(mappings: SourceMapSegment[][], owned: boolean): SourceMapSegment[][]; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts new file mode 100644 index 000000000..6d4d318d0 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts @@ -0,0 +1,16 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; +type GeneratedLine = number; +export type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export declare const REV_GENERATED_LINE = 1; +export declare const REV_GENERATED_COLUMN = 2; +export {}; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts new file mode 100644 index 000000000..bead5c12c --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts @@ -0,0 +1,4 @@ +/** + * Removes everything after the last "/", but leaves the slash. + */ +export default function stripFilename(path: string | undefined | null): string; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts new file mode 100644 index 000000000..f618ec36c --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts @@ -0,0 +1,79 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +import type { SourceMapV3, DecodedSourceMap, EncodedSourceMap, InvalidOriginalMapping, OriginalMapping, InvalidGeneratedMapping, GeneratedMapping, SourceMapInput, Needle, SourceNeedle, SourceMap, EachMapping } from './types'; +export type { SourceMapSegment } from './sourcemap-segment'; +export type { SourceMap, DecodedSourceMap, EncodedSourceMap, Section, SectionedSourceMap, SourceMapV3, Bias, EachMapping, GeneratedMapping, InvalidGeneratedMapping, InvalidOriginalMapping, Needle, OriginalMapping, OriginalMapping as Mapping, SectionedSourceMapInput, SourceMapInput, SourceNeedle, XInput, EncodedSourceMapXInput, DecodedSourceMapXInput, SectionedSourceMapXInput, SectionXInput, } from './types'; +export declare const LEAST_UPPER_BOUND = -1; +export declare const GREATEST_LOWER_BOUND = 1; +export { AnyMap } from './any-map'; +export declare class TraceMap implements SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + ignoreList: SourceMapV3['ignoreList']; + resolvedSources: string[]; + private _encoded; + private _decoded; + private _decodedMemo; + private _bySources; + private _bySourceMemos; + constructor(map: SourceMapInput, mapUrl?: string | null); +} +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +export declare function encodedMappings(map: TraceMap): EncodedSourceMap['mappings']; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +export declare function decodedMappings(map: TraceMap): Readonly; +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +export declare function traceSegment(map: TraceMap, line: number, column: number): Readonly | null; +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +export declare function originalPositionFor(map: TraceMap, needle: Needle): OriginalMapping | InvalidOriginalMapping; +/** + * Finds the generated line/column position of the provided source/line/column source position. + */ +export declare function generatedPositionFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping | InvalidGeneratedMapping; +/** + * Finds all generated line/column positions of the provided source/line/column source position. + */ +export declare function allGeneratedPositionsFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping[]; +/** + * Iterates each mapping in generated position order. + */ +export declare function eachMapping(map: TraceMap, cb: (mapping: EachMapping) => void): void; +/** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ +export declare function sourceContentFor(map: TraceMap, source: string): string | null; +/** + * Determines if the source is marked to ignore by the source map. + */ +export declare function isIgnored(map: TraceMap, source: string): boolean; +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +export declare function presortedDecodedMap(map: DecodedSourceMap, mapUrl?: string): TraceMap; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function decodedMap(map: TraceMap): Omit & { + mappings: readonly SourceMapSegment[][]; +}; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function encodedMap(map: TraceMap): EncodedSourceMap; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts new file mode 100644 index 000000000..a94e6b25f --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts @@ -0,0 +1,99 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +import type { GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap } from './trace-mapping'; +export interface SourceMapV3 { + file?: string | null; + names: string[]; + sourceRoot?: string; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; + ignoreList?: number[]; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: SourceMapSegment[][]; +} +export interface Section { + offset: { + line: number; + column: number; + }; + map: EncodedSourceMap | DecodedSourceMap | SectionedSourceMap; +} +export interface SectionedSourceMap { + file?: string | null; + sections: Section[]; + version: 3; +} +export type OriginalMapping = { + source: string | null; + line: number; + column: number; + name: string | null; +}; +export type InvalidOriginalMapping = { + source: null; + line: null; + column: null; + name: null; +}; +export type GeneratedMapping = { + line: number; + column: number; +}; +export type InvalidGeneratedMapping = { + line: null; + column: null; +}; +export type Bias = typeof GREATEST_LOWER_BOUND | typeof LEAST_UPPER_BOUND; +export type XInput = { + x_google_ignoreList?: SourceMapV3['ignoreList']; +}; +export type EncodedSourceMapXInput = EncodedSourceMap & XInput; +export type DecodedSourceMapXInput = DecodedSourceMap & XInput; +export type SectionedSourceMapXInput = Omit & { + sections: SectionXInput[]; +}; +export type SectionXInput = Omit & { + map: SectionedSourceMapInput; +}; +export type SourceMapInput = string | EncodedSourceMapXInput | DecodedSourceMapXInput | TraceMap; +export type SectionedSourceMapInput = SourceMapInput | SectionedSourceMapXInput; +export type Needle = { + line: number; + column: number; + bias?: Bias; +}; +export type SourceNeedle = { + source: string; + line: number; + column: number; + bias?: Bias; +}; +export type EachMapping = { + generatedLine: number; + generatedColumn: number; + source: null; + originalLine: null; + originalColumn: null; + name: null; +} | { + generatedLine: number; + generatedColumn: number; + source: string | null; + originalLine: number; + originalColumn: number; + name: string | null; +}; +export declare abstract class SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: SourceMapV3['sources']; + ignoreList: SourceMapV3['ignoreList']; +} diff --git a/node_modules/@jridgewell/trace-mapping/package.json b/node_modules/@jridgewell/trace-mapping/package.json new file mode 100644 index 000000000..454a1bdbe --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/package.json @@ -0,0 +1,77 @@ +{ + "name": "@jridgewell/trace-mapping", + "version": "0.3.25", + "description": "Trace the original position through a source map", + "keywords": [ + "source", + "map" + ], + "main": "dist/trace-mapping.umd.js", + "module": "dist/trace-mapping.mjs", + "types": "dist/types/trace-mapping.d.ts", + "files": [ + "dist" + ], + "exports": { + ".": [ + { + "types": "./dist/types/trace-mapping.d.ts", + "browser": "./dist/trace-mapping.umd.js", + "require": "./dist/trace-mapping.umd.js", + "import": "./dist/trace-mapping.mjs" + }, + "./dist/trace-mapping.umd.js" + ], + "./package.json": "./package.json" + }, + "author": "Justin Ridgewell ", + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/trace-mapping.git" + }, + "license": "MIT", + "scripts": { + "benchmark": "run-s build:rollup benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.mjs", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.mjs", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "prebuild": "rm -rf dist", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build", + "test": "run-s -n test:lint test:only", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts' '**/*.md'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "c8 mocha", + "test:watch": "mocha --watch" + }, + "devDependencies": { + "@rollup/plugin-typescript": "11.1.6", + "@types/mocha": "10.0.6", + "@types/node": "20.11.20", + "@typescript-eslint/eslint-plugin": "6.18.1", + "@typescript-eslint/parser": "6.18.1", + "benchmark": "2.1.4", + "c8": "9.0.0", + "esbuild": "0.19.11", + "eslint": "8.56.0", + "eslint-config-prettier": "9.1.0", + "eslint-plugin-no-only-tests": "3.1.0", + "mocha": "10.3.0", + "npm-run-all": "4.1.5", + "prettier": "3.1.1", + "rollup": "4.9.4", + "tsx": "4.7.0", + "typescript": "5.3.3" + }, + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } +} diff --git a/node_modules/@nicolo-ribaudo/chokidar-2/README.md b/node_modules/@nicolo-ribaudo/chokidar-2/README.md new file mode 100644 index 000000000..7902729e1 --- /dev/null +++ b/node_modules/@nicolo-ribaudo/chokidar-2/README.md @@ -0,0 +1,3 @@ +# `@nicolo-ribaudo/chokidar-2` + +A wrapper around `chokidar@2.1.8` that doesn't depend on `fsevents@1`. diff --git a/node_modules/@nicolo-ribaudo/chokidar-2/build-chokidar.sh b/node_modules/@nicolo-ribaudo/chokidar-2/build-chokidar.sh new file mode 100755 index 000000000..913c03014 --- /dev/null +++ b/node_modules/@nicolo-ribaudo/chokidar-2/build-chokidar.sh @@ -0,0 +1,30 @@ +#!/bin/sh + +set -e + +CHOKIDAR_VERSION=2.1.8 + +rm -rf dist chokidar node_modules + +mkdir chokidar + +npm pack "chokidar@$CHOKIDAR_VERSION" +tar zxvfC chokidar-$CHOKIDAR_VERSION.tgz chokidar --strip 1 package + +rm chokidar-$CHOKIDAR_VERSION.tgz + +node -e " + const pkg = require('./package.json'); + pkg.devDependencies = { + ...require('./chokidar/package.json').dependencies, + 'glob-parent': '^5.1.2', + 'webpack': '^5.53.0', + 'webpack-cli': '^4.8.0' + }; + pkg.dependencies = {}; + fs.writeFileSync('./package.json', JSON.stringify(pkg, null, 2) + '\n'); +" + +yarn && yarn bundle + +cp chokidar/types/index.d.ts ./types.d.ts \ No newline at end of file diff --git a/node_modules/@nicolo-ribaudo/chokidar-2/dist/main.js b/node_modules/@nicolo-ribaudo/chokidar-2/dist/main.js new file mode 100644 index 000000000..9a160b268 --- /dev/null +++ b/node_modules/@nicolo-ribaudo/chokidar-2/dist/main.js @@ -0,0 +1,2086 @@ +/* + * ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development"). + * This devtool is neither made for production nor for readable output files. + * It uses "eval()" calls to create a separate source file in the browser devtools. + * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/) + * or disable the default devtool with "devtool: false". + * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/). + */ +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ "./chokidar/index.js": +/*!***************************!*\ + !*** ./chokidar/index.js ***! + \***************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +eval("\nvar EventEmitter = __webpack_require__(/*! events */ \"events\").EventEmitter;\nvar fs = __webpack_require__(/*! fs */ \"fs\");\nvar sysPath = __webpack_require__(/*! path */ \"path\");\nvar asyncEach = __webpack_require__(/*! async-each */ \"./node_modules/async-each/index.js\");\nvar anymatch = __webpack_require__(/*! anymatch */ \"./node_modules/anymatch/index.js\");\nvar globParent = __webpack_require__(/*! glob-parent */ \"./node_modules/glob-parent/index.js\");\nvar isGlob = __webpack_require__(/*! is-glob */ \"./node_modules/is-glob/index.js\");\nvar isAbsolute = __webpack_require__(/*! path-is-absolute */ \"./node_modules/path-is-absolute/index.js\");\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits.js\");\nvar braces = __webpack_require__(/*! braces */ \"./node_modules/braces/index.js\");\nvar normalizePath = __webpack_require__(/*! normalize-path */ \"./node_modules/normalize-path/index.js\");\nvar upath = __webpack_require__(/*! upath */ \"./node_modules/upath/build/code/upath.js\");\n\nvar NodeFsHandler = __webpack_require__(/*! ./lib/nodefs-handler */ \"./chokidar/lib/nodefs-handler.js\");\nvar FsEventsHandler = __webpack_require__(/*! ./lib/fsevents-handler */ \"./chokidar/lib/fsevents-handler.js\");\n\nvar arrify = function(value) {\n if (value == null) return [];\n return Array.isArray(value) ? value : [value];\n};\n\nvar flatten = function(list, result) {\n if (result == null) result = [];\n list.forEach(function(item) {\n if (Array.isArray(item)) {\n flatten(item, result);\n } else {\n result.push(item);\n }\n });\n return result;\n};\n\n// Little isString util for use in Array#every.\nvar isString = function(thing) {\n return typeof thing === 'string';\n};\n\n// Public: Main class.\n// Watches files & directories for changes.\n//\n// * _opts - object, chokidar options hash\n//\n// Emitted events:\n// `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`\n//\n// Examples\n//\n// var watcher = new FSWatcher()\n// .add(directories)\n// .on('add', path => console.log('File', path, 'was added'))\n// .on('change', path => console.log('File', path, 'was changed'))\n// .on('unlink', path => console.log('File', path, 'was removed'))\n// .on('all', (event, path) => console.log(path, ' emitted ', event))\n//\nfunction FSWatcher(_opts) {\n EventEmitter.call(this);\n var opts = {};\n // in case _opts that is passed in is a frozen object\n if (_opts) for (var opt in _opts) opts[opt] = _opts[opt];\n this._watched = Object.create(null);\n this._closers = Object.create(null);\n this._ignoredPaths = Object.create(null);\n Object.defineProperty(this, '_globIgnored', {\n get: function() { return Object.keys(this._ignoredPaths); }\n });\n this.closed = false;\n this._throttled = Object.create(null);\n this._symlinkPaths = Object.create(null);\n\n function undef(key) {\n return opts[key] === undefined;\n }\n\n // Set up default options.\n if (undef('persistent')) opts.persistent = true;\n if (undef('ignoreInitial')) opts.ignoreInitial = false;\n if (undef('ignorePermissionErrors')) opts.ignorePermissionErrors = false;\n if (undef('interval')) opts.interval = 100;\n if (undef('binaryInterval')) opts.binaryInterval = 300;\n if (undef('disableGlobbing')) opts.disableGlobbing = false;\n this.enableBinaryInterval = opts.binaryInterval !== opts.interval;\n\n // Enable fsevents on OS X when polling isn't explicitly enabled.\n if (undef('useFsEvents')) opts.useFsEvents = !opts.usePolling;\n\n // If we can't use fsevents, ensure the options reflect it's disabled.\n if (!FsEventsHandler.canUse()) opts.useFsEvents = false;\n\n // Use polling on Mac if not using fsevents.\n // Other platforms use non-polling fs.watch.\n if (undef('usePolling') && !opts.useFsEvents) {\n opts.usePolling = process.platform === 'darwin';\n }\n\n // Global override (useful for end-developers that need to force polling for all\n // instances of chokidar, regardless of usage/dependency depth)\n var envPoll = process.env.CHOKIDAR_USEPOLLING;\n if (envPoll !== undefined) {\n var envLower = envPoll.toLowerCase();\n\n if (envLower === 'false' || envLower === '0') {\n opts.usePolling = false;\n } else if (envLower === 'true' || envLower === '1') {\n opts.usePolling = true;\n } else {\n opts.usePolling = !!envLower\n }\n }\n var envInterval = process.env.CHOKIDAR_INTERVAL;\n if (envInterval) {\n opts.interval = parseInt(envInterval);\n }\n\n // Editor atomic write normalization enabled by default with fs.watch\n if (undef('atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;\n if (opts.atomic) this._pendingUnlinks = Object.create(null);\n\n if (undef('followSymlinks')) opts.followSymlinks = true;\n\n if (undef('awaitWriteFinish')) opts.awaitWriteFinish = false;\n if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};\n var awf = opts.awaitWriteFinish;\n if (awf) {\n if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;\n if (!awf.pollInterval) awf.pollInterval = 100;\n\n this._pendingWrites = Object.create(null);\n }\n if (opts.ignored) opts.ignored = arrify(opts.ignored);\n\n this._isntIgnored = function(path, stat) {\n return !this._isIgnored(path, stat);\n }.bind(this);\n\n var readyCalls = 0;\n this._emitReady = function() {\n if (++readyCalls >= this._readyCount) {\n this._emitReady = Function.prototype;\n this._readyEmitted = true;\n // use process.nextTick to allow time for listener to be bound\n process.nextTick(this.emit.bind(this, 'ready'));\n }\n }.bind(this);\n\n this.options = opts;\n\n // You’re frozen when your heart’s not open.\n Object.freeze(opts);\n}\n\ninherits(FSWatcher, EventEmitter);\n\n// Common helpers\n// --------------\n\n// Private method: Normalize and emit events\n//\n// * event - string, type of event\n// * path - string, file or directory path\n// * val[1..3] - arguments to be passed with event\n//\n// Returns the error if defined, otherwise the value of the\n// FSWatcher instance's `closed` flag\nFSWatcher.prototype._emit = function(event, path, val1, val2, val3) {\n if (this.options.cwd) path = sysPath.relative(this.options.cwd, path);\n var args = [event, path];\n if (val3 !== undefined) args.push(val1, val2, val3);\n else if (val2 !== undefined) args.push(val1, val2);\n else if (val1 !== undefined) args.push(val1);\n\n var awf = this.options.awaitWriteFinish;\n if (awf && this._pendingWrites[path]) {\n this._pendingWrites[path].lastChange = new Date();\n return this;\n }\n\n if (this.options.atomic) {\n if (event === 'unlink') {\n this._pendingUnlinks[path] = args;\n setTimeout(function() {\n Object.keys(this._pendingUnlinks).forEach(function(path) {\n this.emit.apply(this, this._pendingUnlinks[path]);\n this.emit.apply(this, ['all'].concat(this._pendingUnlinks[path]));\n delete this._pendingUnlinks[path];\n }.bind(this));\n }.bind(this), typeof this.options.atomic === \"number\"\n ? this.options.atomic\n : 100);\n return this;\n } else if (event === 'add' && this._pendingUnlinks[path]) {\n event = args[0] = 'change';\n delete this._pendingUnlinks[path];\n }\n }\n\n var emitEvent = function() {\n this.emit.apply(this, args);\n if (event !== 'error') this.emit.apply(this, ['all'].concat(args));\n }.bind(this);\n\n if (awf && (event === 'add' || event === 'change') && this._readyEmitted) {\n var awfEmit = function(err, stats) {\n if (err) {\n event = args[0] = 'error';\n args[1] = err;\n emitEvent();\n } else if (stats) {\n // if stats doesn't exist the file must have been deleted\n if (args.length > 2) {\n args[2] = stats;\n } else {\n args.push(stats);\n }\n emitEvent();\n }\n };\n\n this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);\n return this;\n }\n\n if (event === 'change') {\n if (!this._throttle('change', path, 50)) return this;\n }\n\n if (\n this.options.alwaysStat && val1 === undefined &&\n (event === 'add' || event === 'addDir' || event === 'change')\n ) {\n var fullPath = this.options.cwd ? sysPath.join(this.options.cwd, path) : path;\n fs.stat(fullPath, function(error, stats) {\n // Suppress event when fs.stat fails, to avoid sending undefined 'stat'\n if (error || !stats) return;\n\n args.push(stats);\n emitEvent();\n });\n } else {\n emitEvent();\n }\n\n return this;\n};\n\n// Private method: Common handler for errors\n//\n// * error - object, Error instance\n//\n// Returns the error if defined, otherwise the value of the\n// FSWatcher instance's `closed` flag\nFSWatcher.prototype._handleError = function(error) {\n var code = error && error.code;\n var ipe = this.options.ignorePermissionErrors;\n if (error &&\n code !== 'ENOENT' &&\n code !== 'ENOTDIR' &&\n (!ipe || (code !== 'EPERM' && code !== 'EACCES'))\n ) this.emit('error', error);\n return error || this.closed;\n};\n\n// Private method: Helper utility for throttling\n//\n// * action - string, type of action being throttled\n// * path - string, path being acted upon\n// * timeout - int, duration of time to suppress duplicate actions\n//\n// Returns throttle tracking object or false if action should be suppressed\nFSWatcher.prototype._throttle = function(action, path, timeout) {\n if (!(action in this._throttled)) {\n this._throttled[action] = Object.create(null);\n }\n var throttled = this._throttled[action];\n if (path in throttled) {\n throttled[path].count++;\n return false;\n }\n function clear() {\n var count = throttled[path] ? throttled[path].count : 0;\n delete throttled[path];\n clearTimeout(timeoutObject);\n return count;\n }\n var timeoutObject = setTimeout(clear, timeout);\n throttled[path] = {timeoutObject: timeoutObject, clear: clear, count: 0};\n return throttled[path];\n};\n\n// Private method: Awaits write operation to finish\n//\n// * path - string, path being acted upon\n// * threshold - int, time in milliseconds a file size must be fixed before\n// acknowledging write operation is finished\n// * awfEmit - function, to be called when ready for event to be emitted\n// Polls a newly created file for size variations. When files size does not\n// change for 'threshold' milliseconds calls callback.\nFSWatcher.prototype._awaitWriteFinish = function(path, threshold, event, awfEmit) {\n var timeoutHandler;\n\n var fullPath = path;\n if (this.options.cwd && !isAbsolute(path)) {\n fullPath = sysPath.join(this.options.cwd, path);\n }\n\n var now = new Date();\n\n var awaitWriteFinish = (function (prevStat) {\n fs.stat(fullPath, function(err, curStat) {\n if (err || !(path in this._pendingWrites)) {\n if (err && err.code !== 'ENOENT') awfEmit(err);\n return;\n }\n\n var now = new Date();\n\n if (prevStat && curStat.size != prevStat.size) {\n this._pendingWrites[path].lastChange = now;\n }\n\n if (now - this._pendingWrites[path].lastChange >= threshold) {\n delete this._pendingWrites[path];\n awfEmit(null, curStat);\n } else {\n timeoutHandler = setTimeout(\n awaitWriteFinish.bind(this, curStat),\n this.options.awaitWriteFinish.pollInterval\n );\n }\n }.bind(this));\n }.bind(this));\n\n if (!(path in this._pendingWrites)) {\n this._pendingWrites[path] = {\n lastChange: now,\n cancelWait: function() {\n delete this._pendingWrites[path];\n clearTimeout(timeoutHandler);\n return event;\n }.bind(this)\n };\n timeoutHandler = setTimeout(\n awaitWriteFinish.bind(this),\n this.options.awaitWriteFinish.pollInterval\n );\n }\n};\n\n// Private method: Determines whether user has asked to ignore this path\n//\n// * path - string, path to file or directory\n// * stats - object, result of fs.stat\n//\n// Returns boolean\nvar dotRe = /\\..*\\.(sw[px])$|\\~$|\\.subl.*\\.tmp/;\nFSWatcher.prototype._isIgnored = function(path, stats) {\n if (this.options.atomic && dotRe.test(path)) return true;\n\n if (!this._userIgnored) {\n var cwd = this.options.cwd;\n var ignored = this.options.ignored;\n if (cwd && ignored) {\n ignored = ignored.map(function (path) {\n if (typeof path !== 'string') return path;\n return upath.normalize(isAbsolute(path) ? path : sysPath.join(cwd, path));\n });\n }\n var paths = arrify(ignored)\n .filter(function(path) {\n return typeof path === 'string' && !isGlob(path);\n }).map(function(path) {\n return path + '/**';\n });\n this._userIgnored = anymatch(\n this._globIgnored.concat(ignored).concat(paths)\n );\n }\n\n return this._userIgnored([path, stats]);\n};\n\n// Private method: Provides a set of common helpers and properties relating to\n// symlink and glob handling\n//\n// * path - string, file, directory, or glob pattern being watched\n// * depth - int, at any depth > 0, this isn't a glob\n//\n// Returns object containing helpers for this path\nvar replacerRe = /^\\.[\\/\\\\]/;\nFSWatcher.prototype._getWatchHelpers = function(path, depth) {\n path = path.replace(replacerRe, '');\n var watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);\n var fullWatchPath = sysPath.resolve(watchPath);\n var hasGlob = watchPath !== path;\n var globFilter = hasGlob ? anymatch(path) : false;\n var follow = this.options.followSymlinks;\n var globSymlink = hasGlob && follow ? null : false;\n\n var checkGlobSymlink = function(entry) {\n // only need to resolve once\n // first entry should always have entry.parentDir === ''\n if (globSymlink == null) {\n globSymlink = entry.fullParentDir === fullWatchPath ? false : {\n realPath: entry.fullParentDir,\n linkPath: fullWatchPath\n };\n }\n\n if (globSymlink) {\n return entry.fullPath.replace(globSymlink.realPath, globSymlink.linkPath);\n }\n\n return entry.fullPath;\n };\n\n var entryPath = function(entry) {\n return sysPath.join(watchPath,\n sysPath.relative(watchPath, checkGlobSymlink(entry))\n );\n };\n\n var filterPath = function(entry) {\n if (entry.stat && entry.stat.isSymbolicLink()) return filterDir(entry);\n var resolvedPath = entryPath(entry);\n return (!hasGlob || globFilter(resolvedPath)) &&\n this._isntIgnored(resolvedPath, entry.stat) &&\n (this.options.ignorePermissionErrors ||\n this._hasReadPermissions(entry.stat));\n }.bind(this);\n\n var getDirParts = function(path) {\n if (!hasGlob) return false;\n var parts = [];\n var expandedPath = braces.expand(path);\n expandedPath.forEach(function(path) {\n parts.push(sysPath.relative(watchPath, path).split(/[\\/\\\\]/));\n });\n return parts;\n };\n\n var dirParts = getDirParts(path);\n if (dirParts) {\n dirParts.forEach(function(parts) {\n if (parts.length > 1) parts.pop();\n });\n }\n var unmatchedGlob;\n\n var filterDir = function(entry) {\n if (hasGlob) {\n var entryParts = getDirParts(checkGlobSymlink(entry));\n var globstar = false;\n unmatchedGlob = !dirParts.some(function(parts) {\n return parts.every(function(part, i) {\n if (part === '**') globstar = true;\n return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i]);\n });\n });\n }\n return !unmatchedGlob && this._isntIgnored(entryPath(entry), entry.stat);\n }.bind(this);\n\n return {\n followSymlinks: follow,\n statMethod: follow ? 'stat' : 'lstat',\n path: path,\n watchPath: watchPath,\n entryPath: entryPath,\n hasGlob: hasGlob,\n globFilter: globFilter,\n filterPath: filterPath,\n filterDir: filterDir\n };\n};\n\n// Directory helpers\n// -----------------\n\n// Private method: Provides directory tracking objects\n//\n// * directory - string, path of the directory\n//\n// Returns the directory's tracking object\nFSWatcher.prototype._getWatchedDir = function(directory) {\n var dir = sysPath.resolve(directory);\n var watcherRemove = this._remove.bind(this);\n if (!(dir in this._watched)) this._watched[dir] = {\n _items: Object.create(null),\n add: function(item) {\n if (item !== '.' && item !== '..') this._items[item] = true;\n },\n remove: function(item) {\n delete this._items[item];\n if (!this.children().length) {\n fs.readdir(dir, function(err) {\n if (err) watcherRemove(sysPath.dirname(dir), sysPath.basename(dir));\n });\n }\n },\n has: function(item) {return item in this._items;},\n children: function() {return Object.keys(this._items);}\n };\n return this._watched[dir];\n};\n\n// File helpers\n// ------------\n\n// Private method: Check for read permissions\n// Based on this answer on SO: http://stackoverflow.com/a/11781404/1358405\n//\n// * stats - object, result of fs.stat\n//\n// Returns boolean\nFSWatcher.prototype._hasReadPermissions = function(stats) {\n return Boolean(4 & parseInt(((stats && stats.mode) & 0x1ff).toString(8)[0], 10));\n};\n\n// Private method: Handles emitting unlink events for\n// files and directories, and via recursion, for\n// files and directories within directories that are unlinked\n//\n// * directory - string, directory within which the following item is located\n// * item - string, base path of item/directory\n//\n// Returns nothing\nFSWatcher.prototype._remove = function(directory, item) {\n // if what is being deleted is a directory, get that directory's paths\n // for recursive deleting and cleaning of watched object\n // if it is not a directory, nestedDirectoryChildren will be empty array\n var path = sysPath.join(directory, item);\n var fullPath = sysPath.resolve(path);\n var isDirectory = this._watched[path] || this._watched[fullPath];\n\n // prevent duplicate handling in case of arriving here nearly simultaneously\n // via multiple paths (such as _handleFile and _handleDir)\n if (!this._throttle('remove', path, 100)) return;\n\n // if the only watched file is removed, watch for its return\n var watchedDirs = Object.keys(this._watched);\n if (!isDirectory && !this.options.useFsEvents && watchedDirs.length === 1) {\n this.add(directory, item, true);\n }\n\n // This will create a new entry in the watched object in either case\n // so we got to do the directory check beforehand\n var nestedDirectoryChildren = this._getWatchedDir(path).children();\n\n // Recursively remove children directories / files.\n nestedDirectoryChildren.forEach(function(nestedItem) {\n this._remove(path, nestedItem);\n }, this);\n\n // Check if item was on the watched list and remove it\n var parent = this._getWatchedDir(directory);\n var wasTracked = parent.has(item);\n parent.remove(item);\n\n // If we wait for this file to be fully written, cancel the wait.\n var relPath = path;\n if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);\n if (this.options.awaitWriteFinish && this._pendingWrites[relPath]) {\n var event = this._pendingWrites[relPath].cancelWait();\n if (event === 'add') return;\n }\n\n // The Entry will either be a directory that just got removed\n // or a bogus entry to a file, in either case we have to remove it\n delete this._watched[path];\n delete this._watched[fullPath];\n var eventName = isDirectory ? 'unlinkDir' : 'unlink';\n if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);\n\n // Avoid conflicts if we later create another file with the same name\n if (!this.options.useFsEvents) {\n this._closePath(path);\n }\n};\n\nFSWatcher.prototype._closePath = function(path) {\n if (!this._closers[path]) return;\n this._closers[path].forEach(function(closer) {\n closer();\n });\n delete this._closers[path];\n this._getWatchedDir(sysPath.dirname(path)).remove(sysPath.basename(path));\n}\n\n// Public method: Adds paths to be watched on an existing FSWatcher instance\n\n// * paths - string or array of strings, file/directory paths and/or globs\n// * _origAdd - private boolean, for handling non-existent paths to be watched\n// * _internal - private boolean, indicates a non-user add\n\n// Returns an instance of FSWatcher for chaining.\nFSWatcher.prototype.add = function(paths, _origAdd, _internal) {\n var disableGlobbing = this.options.disableGlobbing;\n var cwd = this.options.cwd;\n this.closed = false;\n paths = flatten(arrify(paths));\n\n if (!paths.every(isString)) {\n throw new TypeError('Non-string provided as watch path: ' + paths);\n }\n\n if (cwd) paths = paths.map(function(path) {\n var absPath;\n if (isAbsolute(path)) {\n absPath = path;\n } else if (path[0] === '!') {\n absPath = '!' + sysPath.join(cwd, path.substring(1));\n } else {\n absPath = sysPath.join(cwd, path);\n }\n\n // Check `path` instead of `absPath` because the cwd portion can't be a glob\n if (disableGlobbing || !isGlob(path)) {\n return absPath;\n } else {\n return normalizePath(absPath);\n }\n });\n\n // set aside negated glob strings\n paths = paths.filter(function(path) {\n if (path[0] === '!') {\n this._ignoredPaths[path.substring(1)] = true;\n } else {\n // if a path is being added that was previously ignored, stop ignoring it\n delete this._ignoredPaths[path];\n delete this._ignoredPaths[path + '/**'];\n\n // reset the cached userIgnored anymatch fn\n // to make ignoredPaths changes effective\n this._userIgnored = null;\n\n return true;\n }\n }, this);\n\n if (this.options.useFsEvents && FsEventsHandler.canUse()) {\n if (!this._readyCount) this._readyCount = paths.length;\n if (this.options.persistent) this._readyCount *= 2;\n paths.forEach(this._addToFsEvents, this);\n } else {\n if (!this._readyCount) this._readyCount = 0;\n this._readyCount += paths.length;\n asyncEach(paths, function(path, next) {\n this._addToNodeFs(path, !_internal, 0, 0, _origAdd, function(err, res) {\n if (res) this._emitReady();\n next(err, res);\n }.bind(this));\n }.bind(this), function(error, results) {\n results.forEach(function(item) {\n if (!item || this.closed) return;\n this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));\n }, this);\n }.bind(this));\n }\n\n return this;\n};\n\n// Public method: Close watchers or start ignoring events from specified paths.\n\n// * paths - string or array of strings, file/directory paths and/or globs\n\n// Returns instance of FSWatcher for chaining.\nFSWatcher.prototype.unwatch = function(paths) {\n if (this.closed) return this;\n paths = flatten(arrify(paths));\n\n paths.forEach(function(path) {\n // convert to absolute path unless relative path already matches\n if (!isAbsolute(path) && !this._closers[path]) {\n if (this.options.cwd) path = sysPath.join(this.options.cwd, path);\n path = sysPath.resolve(path);\n }\n\n this._closePath(path);\n\n this._ignoredPaths[path] = true;\n if (path in this._watched) {\n this._ignoredPaths[path + '/**'] = true;\n }\n\n // reset the cached userIgnored anymatch fn\n // to make ignoredPaths changes effective\n this._userIgnored = null;\n }, this);\n\n return this;\n};\n\n// Public method: Close watchers and remove all listeners from watched paths.\n\n// Returns instance of FSWatcher for chaining.\nFSWatcher.prototype.close = function() {\n if (this.closed) return this;\n\n this.closed = true;\n Object.keys(this._closers).forEach(function(watchPath) {\n this._closers[watchPath].forEach(function(closer) {\n closer();\n });\n delete this._closers[watchPath];\n }, this);\n this._watched = Object.create(null);\n\n this.removeAllListeners();\n return this;\n};\n\n// Public method: Expose list of watched paths\n\n// Returns object w/ dir paths as keys and arrays of contained paths as values.\nFSWatcher.prototype.getWatched = function() {\n var watchList = {};\n Object.keys(this._watched).forEach(function(dir) {\n var key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;\n watchList[key || '.'] = Object.keys(this._watched[dir]._items).sort();\n }.bind(this));\n return watchList;\n};\n\n// Attach watch handler prototype methods\nfunction importHandler(handler) {\n Object.keys(handler.prototype).forEach(function(method) {\n FSWatcher.prototype[method] = handler.prototype[method];\n });\n}\nimportHandler(NodeFsHandler);\nif (FsEventsHandler.canUse()) importHandler(FsEventsHandler);\n\n// Export FSWatcher class\nexports.FSWatcher = FSWatcher;\n\n// Public function: Instantiates watcher with paths to be tracked.\n\n// * paths - string or array of strings, file/directory paths and/or globs\n// * options - object, chokidar options\n\n// Returns an instance of FSWatcher for chaining.\nexports.watch = function(paths, options) {\n return new FSWatcher(options).add(paths);\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./chokidar/index.js?"); + +/***/ }), + +/***/ "./chokidar/lib/fsevents-handler.js": +/*!******************************************!*\ + !*** ./chokidar/lib/fsevents-handler.js ***! + \******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar fs = __webpack_require__(/*! fs */ \"fs\");\nvar sysPath = __webpack_require__(/*! path */ \"path\");\nvar readdirp = __webpack_require__(/*! readdirp */ \"./node_modules/readdirp/readdirp.js\");\nvar fsevents;\ntry { fsevents = __webpack_require__(Object(function webpackMissingModule() { var e = new Error(\"Cannot find module 'fsevents'\"); e.code = 'MODULE_NOT_FOUND'; throw e; }())); } catch (error) {\n if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error)\n}\n\n// fsevents instance helper functions\n\n// object to hold per-process fsevents instances\n// (may be shared across chokidar FSWatcher instances)\nvar FSEventsWatchers = Object.create(null);\n\n// Threshold of duplicate path prefixes at which to start\n// consolidating going forward\nvar consolidateThreshhold = 10;\n\n// Private function: Instantiates the fsevents interface\n\n// * path - string, path to be watched\n// * callback - function, called when fsevents is bound and ready\n\n// Returns new fsevents instance\nfunction createFSEventsInstance(path, callback) {\n return (new fsevents(path)).on('fsevent', callback).start();\n}\n\n// Private function: Instantiates the fsevents interface or binds listeners\n// to an existing one covering the same file tree\n\n// * path - string, path to be watched\n// * realPath - string, real path (in case of symlinks)\n// * listener - function, called when fsevents emits events\n// * rawEmitter - function, passes data to listeners of the 'raw' event\n\n// Returns close function\nfunction setFSEventsListener(path, realPath, listener, rawEmitter) {\n var watchPath = sysPath.extname(path) ? sysPath.dirname(path) : path;\n var watchContainer;\n var parentPath = sysPath.dirname(watchPath);\n\n // If we've accumulated a substantial number of paths that\n // could have been consolidated by watching one directory\n // above the current one, create a watcher on the parent\n // path instead, so that we do consolidate going forward.\n if (couldConsolidate(parentPath)) {\n watchPath = parentPath;\n }\n\n var resolvedPath = sysPath.resolve(path);\n var hasSymlink = resolvedPath !== realPath;\n function filteredListener(fullPath, flags, info) {\n if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);\n if (\n fullPath === resolvedPath ||\n !fullPath.indexOf(resolvedPath + sysPath.sep)\n ) listener(fullPath, flags, info);\n }\n\n // check if there is already a watcher on a parent path\n // modifies `watchPath` to the parent path when it finds a match\n function watchedParent() {\n return Object.keys(FSEventsWatchers).some(function(watchedPath) {\n // condition is met when indexOf returns 0\n if (!realPath.indexOf(sysPath.resolve(watchedPath) + sysPath.sep)) {\n watchPath = watchedPath;\n return true;\n }\n });\n }\n\n if (watchPath in FSEventsWatchers || watchedParent()) {\n watchContainer = FSEventsWatchers[watchPath];\n watchContainer.listeners.push(filteredListener);\n } else {\n watchContainer = FSEventsWatchers[watchPath] = {\n listeners: [filteredListener],\n rawEmitters: [rawEmitter],\n watcher: createFSEventsInstance(watchPath, function(fullPath, flags) {\n var info = fsevents.getInfo(fullPath, flags);\n watchContainer.listeners.forEach(function(listener) {\n listener(fullPath, flags, info);\n });\n watchContainer.rawEmitters.forEach(function(emitter) {\n emitter(info.event, fullPath, info);\n });\n })\n };\n }\n var listenerIndex = watchContainer.listeners.length - 1;\n\n // removes this instance's listeners and closes the underlying fsevents\n // instance if there are no more listeners left\n return function close() {\n delete watchContainer.listeners[listenerIndex];\n delete watchContainer.rawEmitters[listenerIndex];\n if (!Object.keys(watchContainer.listeners).length) {\n watchContainer.watcher.stop();\n delete FSEventsWatchers[watchPath];\n }\n };\n}\n\n// Decide whether or not we should start a new higher-level\n// parent watcher\nfunction couldConsolidate(path) {\n var keys = Object.keys(FSEventsWatchers);\n var count = 0;\n\n for (var i = 0, len = keys.length; i < len; ++i) {\n var watchPath = keys[i];\n if (watchPath.indexOf(path) === 0) {\n count++;\n if (count >= consolidateThreshhold) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nfunction isConstructor(obj) {\n return obj.prototype !== undefined && obj.prototype.constructor !== undefined;\n}\n\n// returns boolean indicating whether fsevents can be used\nfunction canUse() {\n return fsevents && Object.keys(FSEventsWatchers).length < 128 && isConstructor(fsevents);\n}\n\n// determines subdirectory traversal levels from root to path\nfunction depth(path, root) {\n var i = 0;\n while (!path.indexOf(root) && (path = sysPath.dirname(path)) !== root) i++;\n return i;\n}\n\n// fake constructor for attaching fsevents-specific prototype methods that\n// will be copied to FSWatcher's prototype\nfunction FsEventsHandler() {}\n\n// Private method: Handle symlinks encountered during directory scan\n\n// * watchPath - string, file/dir path to be watched with fsevents\n// * realPath - string, real path (in case of symlinks)\n// * transform - function, path transformer\n// * globFilter - function, path filter in case a glob pattern was provided\n\n// Returns close function for the watcher instance\nFsEventsHandler.prototype._watchWithFsEvents =\nfunction(watchPath, realPath, transform, globFilter) {\n if (this._isIgnored(watchPath)) return;\n var watchCallback = function(fullPath, flags, info) {\n if (\n this.options.depth !== undefined &&\n depth(fullPath, realPath) > this.options.depth\n ) return;\n var path = transform(sysPath.join(\n watchPath, sysPath.relative(watchPath, fullPath)\n ));\n if (globFilter && !globFilter(path)) return;\n // ensure directories are tracked\n var parent = sysPath.dirname(path);\n var item = sysPath.basename(path);\n var watchedDir = this._getWatchedDir(\n info.type === 'directory' ? path : parent\n );\n var checkIgnored = function(stats) {\n if (this._isIgnored(path, stats)) {\n this._ignoredPaths[path] = true;\n if (stats && stats.isDirectory()) {\n this._ignoredPaths[path + '/**/*'] = true;\n }\n return true;\n } else {\n delete this._ignoredPaths[path];\n delete this._ignoredPaths[path + '/**/*'];\n }\n }.bind(this);\n\n var handleEvent = function(event) {\n if (checkIgnored()) return;\n\n if (event === 'unlink') {\n // suppress unlink events on never before seen files\n if (info.type === 'directory' || watchedDir.has(item)) {\n this._remove(parent, item);\n }\n } else {\n if (event === 'add') {\n // track new directories\n if (info.type === 'directory') this._getWatchedDir(path);\n\n if (info.type === 'symlink' && this.options.followSymlinks) {\n // push symlinks back to the top of the stack to get handled\n var curDepth = this.options.depth === undefined ?\n undefined : depth(fullPath, realPath) + 1;\n return this._addToFsEvents(path, false, true, curDepth);\n } else {\n // track new paths\n // (other than symlinks being followed, which will be tracked soon)\n this._getWatchedDir(parent).add(item);\n }\n }\n var eventName = info.type === 'directory' ? event + 'Dir' : event;\n this._emit(eventName, path);\n if (eventName === 'addDir') this._addToFsEvents(path, false, true);\n }\n }.bind(this);\n\n function addOrChange() {\n handleEvent(watchedDir.has(item) ? 'change' : 'add');\n }\n function checkFd() {\n fs.open(path, 'r', function(error, fd) {\n if (error) {\n error.code !== 'EACCES' ?\n handleEvent('unlink') : addOrChange();\n } else {\n fs.close(fd, function(err) {\n err && err.code !== 'EACCES' ?\n handleEvent('unlink') : addOrChange();\n });\n }\n });\n }\n // correct for wrong events emitted\n var wrongEventFlags = [\n 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912\n ];\n if (wrongEventFlags.indexOf(flags) !== -1 || info.event === 'unknown') {\n if (typeof this.options.ignored === 'function') {\n fs.stat(path, function(error, stats) {\n if (checkIgnored(stats)) return;\n stats ? addOrChange() : handleEvent('unlink');\n });\n } else {\n checkFd();\n }\n } else {\n switch (info.event) {\n case 'created':\n case 'modified':\n return addOrChange();\n case 'deleted':\n case 'moved':\n return checkFd();\n }\n }\n }.bind(this);\n\n var closer = setFSEventsListener(\n watchPath,\n realPath,\n watchCallback,\n this.emit.bind(this, 'raw')\n );\n\n this._emitReady();\n return closer;\n};\n\n// Private method: Handle symlinks encountered during directory scan\n\n// * linkPath - string, path to symlink\n// * fullPath - string, absolute path to the symlink\n// * transform - function, pre-existing path transformer\n// * curDepth - int, level of subdirectories traversed to where symlink is\n\n// Returns nothing\nFsEventsHandler.prototype._handleFsEventsSymlink =\nfunction(linkPath, fullPath, transform, curDepth) {\n // don't follow the same symlink more than once\n if (this._symlinkPaths[fullPath]) return;\n else this._symlinkPaths[fullPath] = true;\n\n this._readyCount++;\n\n fs.realpath(linkPath, function(error, linkTarget) {\n if (this._handleError(error) || this._isIgnored(linkTarget)) {\n return this._emitReady();\n }\n\n this._readyCount++;\n\n // add the linkTarget for watching with a wrapper for transform\n // that causes emitted paths to incorporate the link's path\n this._addToFsEvents(linkTarget || linkPath, function(path) {\n var dotSlash = '.' + sysPath.sep;\n var aliasedPath = linkPath;\n if (linkTarget && linkTarget !== dotSlash) {\n aliasedPath = path.replace(linkTarget, linkPath);\n } else if (path !== dotSlash) {\n aliasedPath = sysPath.join(linkPath, path);\n }\n return transform(aliasedPath);\n }, false, curDepth);\n }.bind(this));\n};\n\n// Private method: Handle added path with fsevents\n\n// * path - string, file/directory path or glob pattern\n// * transform - function, converts working path to what the user expects\n// * forceAdd - boolean, ensure add is emitted\n// * priorDepth - int, level of subdirectories already traversed\n\n// Returns nothing\nFsEventsHandler.prototype._addToFsEvents =\nfunction(path, transform, forceAdd, priorDepth) {\n\n // applies transform if provided, otherwise returns same value\n var processPath = typeof transform === 'function' ?\n transform : function(val) { return val; };\n\n var emitAdd = function(newPath, stats) {\n var pp = processPath(newPath);\n var isDir = stats.isDirectory();\n var dirObj = this._getWatchedDir(sysPath.dirname(pp));\n var base = sysPath.basename(pp);\n\n // ensure empty dirs get tracked\n if (isDir) this._getWatchedDir(pp);\n\n if (dirObj.has(base)) return;\n dirObj.add(base);\n\n if (!this.options.ignoreInitial || forceAdd === true) {\n this._emit(isDir ? 'addDir' : 'add', pp, stats);\n }\n }.bind(this);\n\n var wh = this._getWatchHelpers(path);\n\n // evaluate what is at the path we're being asked to watch\n fs[wh.statMethod](wh.watchPath, function(error, stats) {\n if (this._handleError(error) || this._isIgnored(wh.watchPath, stats)) {\n this._emitReady();\n return this._emitReady();\n }\n\n if (stats.isDirectory()) {\n // emit addDir unless this is a glob parent\n if (!wh.globFilter) emitAdd(processPath(path), stats);\n\n // don't recurse further if it would exceed depth setting\n if (priorDepth && priorDepth > this.options.depth) return;\n\n // scan the contents of the dir\n readdirp({\n root: wh.watchPath,\n entryType: 'all',\n fileFilter: wh.filterPath,\n directoryFilter: wh.filterDir,\n lstat: true,\n depth: this.options.depth - (priorDepth || 0)\n }).on('data', function(entry) {\n // need to check filterPath on dirs b/c filterDir is less restrictive\n if (entry.stat.isDirectory() && !wh.filterPath(entry)) return;\n\n var joinedPath = sysPath.join(wh.watchPath, entry.path);\n var fullPath = entry.fullPath;\n\n if (wh.followSymlinks && entry.stat.isSymbolicLink()) {\n // preserve the current depth here since it can't be derived from\n // real paths past the symlink\n var curDepth = this.options.depth === undefined ?\n undefined : depth(joinedPath, sysPath.resolve(wh.watchPath)) + 1;\n\n this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);\n } else {\n emitAdd(joinedPath, entry.stat);\n }\n }.bind(this)).on('error', function() {\n // Ignore readdirp errors\n }).on('end', this._emitReady);\n } else {\n emitAdd(wh.watchPath, stats);\n this._emitReady();\n }\n }.bind(this));\n\n if (this.options.persistent && forceAdd !== true) {\n var initWatch = function(error, realPath) {\n if (this.closed) return;\n var closer = this._watchWithFsEvents(\n wh.watchPath,\n sysPath.resolve(realPath || wh.watchPath),\n processPath,\n wh.globFilter\n );\n if (closer) {\n this._closers[path] = this._closers[path] || [];\n this._closers[path].push(closer);\n }\n }.bind(this);\n\n if (typeof transform === 'function') {\n // realpath has already been resolved\n initWatch();\n } else {\n fs.realpath(wh.watchPath, initWatch);\n }\n }\n};\n\nmodule.exports = FsEventsHandler;\nmodule.exports.canUse = canUse;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./chokidar/lib/fsevents-handler.js?"); + +/***/ }), + +/***/ "./chokidar/lib/nodefs-handler.js": +/*!****************************************!*\ + !*** ./chokidar/lib/nodefs-handler.js ***! + \****************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar fs = __webpack_require__(/*! fs */ \"fs\");\nvar sysPath = __webpack_require__(/*! path */ \"path\");\nvar readdirp = __webpack_require__(/*! readdirp */ \"./node_modules/readdirp/readdirp.js\");\nvar isBinaryPath = __webpack_require__(/*! is-binary-path */ \"./node_modules/is-binary-path/index.js\");\n\n// fs.watch helpers\n\n// object to hold per-process fs.watch instances\n// (may be shared across chokidar FSWatcher instances)\nvar FsWatchInstances = Object.create(null);\n\n\n// Private function: Instantiates the fs.watch interface\n\n// * path - string, path to be watched\n// * options - object, options to be passed to fs.watch\n// * listener - function, main event handler\n// * errHandler - function, handler which emits info about errors\n// * emitRaw - function, handler which emits raw event data\n\n// Returns new fsevents instance\nfunction createFsWatchInstance(path, options, listener, errHandler, emitRaw) {\n var handleEvent = function(rawEvent, evPath) {\n listener(path);\n emitRaw(rawEvent, evPath, {watchedPath: path});\n\n // emit based on events occurring for files from a directory's watcher in\n // case the file's watcher misses it (and rely on throttling to de-dupe)\n if (evPath && path !== evPath) {\n fsWatchBroadcast(\n sysPath.resolve(path, evPath), 'listeners', sysPath.join(path, evPath)\n );\n }\n };\n try {\n return fs.watch(path, options, handleEvent);\n } catch (error) {\n errHandler(error);\n }\n}\n\n// Private function: Helper for passing fs.watch event data to a\n// collection of listeners\n\n// * fullPath - string, absolute path bound to the fs.watch instance\n// * type - string, listener type\n// * val[1..3] - arguments to be passed to listeners\n\n// Returns nothing\nfunction fsWatchBroadcast(fullPath, type, val1, val2, val3) {\n if (!FsWatchInstances[fullPath]) return;\n FsWatchInstances[fullPath][type].forEach(function(listener) {\n listener(val1, val2, val3);\n });\n}\n\n// Private function: Instantiates the fs.watch interface or binds listeners\n// to an existing one covering the same file system entry\n\n// * path - string, path to be watched\n// * fullPath - string, absolute path\n// * options - object, options to be passed to fs.watch\n// * handlers - object, container for event listener functions\n\n// Returns close function\nfunction setFsWatchListener(path, fullPath, options, handlers) {\n var listener = handlers.listener;\n var errHandler = handlers.errHandler;\n var rawEmitter = handlers.rawEmitter;\n var container = FsWatchInstances[fullPath];\n var watcher;\n if (!options.persistent) {\n watcher = createFsWatchInstance(\n path, options, listener, errHandler, rawEmitter\n );\n return watcher.close.bind(watcher);\n }\n if (!container) {\n watcher = createFsWatchInstance(\n path,\n options,\n fsWatchBroadcast.bind(null, fullPath, 'listeners'),\n errHandler, // no need to use broadcast here\n fsWatchBroadcast.bind(null, fullPath, 'rawEmitters')\n );\n if (!watcher) return;\n var broadcastErr = fsWatchBroadcast.bind(null, fullPath, 'errHandlers');\n watcher.on('error', function(error) {\n container.watcherUnusable = true; // documented since Node 10.4.1\n // Workaround for https://github.com/joyent/node/issues/4337\n if (process.platform === 'win32' && error.code === 'EPERM') {\n fs.open(path, 'r', function(err, fd) {\n if (!err) fs.close(fd, function(err) {\n if (!err) broadcastErr(error);\n });\n });\n } else {\n broadcastErr(error);\n }\n });\n container = FsWatchInstances[fullPath] = {\n listeners: [listener],\n errHandlers: [errHandler],\n rawEmitters: [rawEmitter],\n watcher: watcher\n };\n } else {\n container.listeners.push(listener);\n container.errHandlers.push(errHandler);\n container.rawEmitters.push(rawEmitter);\n }\n var listenerIndex = container.listeners.length - 1;\n\n // removes this instance's listeners and closes the underlying fs.watch\n // instance if there are no more listeners left\n return function close() {\n delete container.listeners[listenerIndex];\n delete container.errHandlers[listenerIndex];\n delete container.rawEmitters[listenerIndex];\n if (!Object.keys(container.listeners).length) {\n if (!container.watcherUnusable) { // check to protect against issue #730\n container.watcher.close();\n }\n delete FsWatchInstances[fullPath];\n }\n };\n}\n\n// fs.watchFile helpers\n\n// object to hold per-process fs.watchFile instances\n// (may be shared across chokidar FSWatcher instances)\nvar FsWatchFileInstances = Object.create(null);\n\n// Private function: Instantiates the fs.watchFile interface or binds listeners\n// to an existing one covering the same file system entry\n\n// * path - string, path to be watched\n// * fullPath - string, absolute path\n// * options - object, options to be passed to fs.watchFile\n// * handlers - object, container for event listener functions\n\n// Returns close function\nfunction setFsWatchFileListener(path, fullPath, options, handlers) {\n var listener = handlers.listener;\n var rawEmitter = handlers.rawEmitter;\n var container = FsWatchFileInstances[fullPath];\n var listeners = [];\n var rawEmitters = [];\n if (\n container && (\n container.options.persistent < options.persistent ||\n container.options.interval > options.interval\n )\n ) {\n // \"Upgrade\" the watcher to persistence or a quicker interval.\n // This creates some unlikely edge case issues if the user mixes\n // settings in a very weird way, but solving for those cases\n // doesn't seem worthwhile for the added complexity.\n listeners = container.listeners;\n rawEmitters = container.rawEmitters;\n fs.unwatchFile(fullPath);\n container = false;\n }\n if (!container) {\n listeners.push(listener);\n rawEmitters.push(rawEmitter);\n container = FsWatchFileInstances[fullPath] = {\n listeners: listeners,\n rawEmitters: rawEmitters,\n options: options,\n watcher: fs.watchFile(fullPath, options, function(curr, prev) {\n container.rawEmitters.forEach(function(rawEmitter) {\n rawEmitter('change', fullPath, {curr: curr, prev: prev});\n });\n var currmtime = curr.mtime.getTime();\n if (curr.size !== prev.size || currmtime > prev.mtime.getTime() || currmtime === 0) {\n container.listeners.forEach(function(listener) {\n listener(path, curr);\n });\n }\n })\n };\n } else {\n container.listeners.push(listener);\n container.rawEmitters.push(rawEmitter);\n }\n var listenerIndex = container.listeners.length - 1;\n\n // removes this instance's listeners and closes the underlying fs.watchFile\n // instance if there are no more listeners left\n return function close() {\n delete container.listeners[listenerIndex];\n delete container.rawEmitters[listenerIndex];\n if (!Object.keys(container.listeners).length) {\n fs.unwatchFile(fullPath);\n delete FsWatchFileInstances[fullPath];\n }\n };\n}\n\n// fake constructor for attaching nodefs-specific prototype methods that\n// will be copied to FSWatcher's prototype\nfunction NodeFsHandler() {}\n\n// Private method: Watch file for changes with fs.watchFile or fs.watch.\n\n// * path - string, path to file or directory.\n// * listener - function, to be executed on fs change.\n\n// Returns close function for the watcher instance\nNodeFsHandler.prototype._watchWithNodeFs =\nfunction(path, listener) {\n var directory = sysPath.dirname(path);\n var basename = sysPath.basename(path);\n var parent = this._getWatchedDir(directory);\n parent.add(basename);\n var absolutePath = sysPath.resolve(path);\n var options = {persistent: this.options.persistent};\n if (!listener) listener = Function.prototype; // empty function\n\n var closer;\n if (this.options.usePolling) {\n options.interval = this.enableBinaryInterval && isBinaryPath(basename) ?\n this.options.binaryInterval : this.options.interval;\n closer = setFsWatchFileListener(path, absolutePath, options, {\n listener: listener,\n rawEmitter: this.emit.bind(this, 'raw')\n });\n } else {\n closer = setFsWatchListener(path, absolutePath, options, {\n listener: listener,\n errHandler: this._handleError.bind(this),\n rawEmitter: this.emit.bind(this, 'raw')\n });\n }\n return closer;\n};\n\n// Private method: Watch a file and emit add event if warranted\n\n// * file - string, the file's path\n// * stats - object, result of fs.stat\n// * initialAdd - boolean, was the file added at watch instantiation?\n// * callback - function, called when done processing as a newly seen file\n\n// Returns close function for the watcher instance\nNodeFsHandler.prototype._handleFile =\nfunction(file, stats, initialAdd, callback) {\n var dirname = sysPath.dirname(file);\n var basename = sysPath.basename(file);\n var parent = this._getWatchedDir(dirname);\n // stats is always present\n var prevStats = stats;\n\n // if the file is already being watched, do nothing\n if (parent.has(basename)) return callback();\n\n // kick off the watcher\n var closer = this._watchWithNodeFs(file, function(path, newStats) {\n if (!this._throttle('watch', file, 5)) return;\n if (!newStats || newStats && newStats.mtime.getTime() === 0) {\n fs.stat(file, function(error, newStats) {\n // Fix issues where mtime is null but file is still present\n if (error) {\n this._remove(dirname, basename);\n } else {\n // Check that change event was not fired because of changed only accessTime.\n var at = newStats.atime.getTime();\n var mt = newStats.mtime.getTime();\n if (!at || at <= mt || mt !== prevStats.mtime.getTime()) {\n this._emit('change', file, newStats);\n }\n prevStats = newStats;\n }\n }.bind(this));\n // add is about to be emitted if file not already tracked in parent\n } else if (parent.has(basename)) {\n // Check that change event was not fired because of changed only accessTime.\n var at = newStats.atime.getTime();\n var mt = newStats.mtime.getTime();\n if (!at || at <= mt || mt !== prevStats.mtime.getTime()) {\n this._emit('change', file, newStats);\n }\n prevStats = newStats;\n }\n }.bind(this));\n\n // emit an add event if we're supposed to\n if (!(initialAdd && this.options.ignoreInitial)) {\n if (!this._throttle('add', file, 0)) return;\n this._emit('add', file, stats);\n }\n\n if (callback) callback();\n return closer;\n};\n\n// Private method: Handle symlinks encountered while reading a dir\n\n// * entry - object, entry object returned by readdirp\n// * directory - string, path of the directory being read\n// * path - string, path of this item\n// * item - string, basename of this item\n\n// Returns true if no more processing is needed for this entry.\nNodeFsHandler.prototype._handleSymlink =\nfunction(entry, directory, path, item) {\n var full = entry.fullPath;\n var dir = this._getWatchedDir(directory);\n\n if (!this.options.followSymlinks) {\n // watch symlink directly (don't follow) and detect changes\n this._readyCount++;\n fs.realpath(path, function(error, linkPath) {\n if (dir.has(item)) {\n if (this._symlinkPaths[full] !== linkPath) {\n this._symlinkPaths[full] = linkPath;\n this._emit('change', path, entry.stat);\n }\n } else {\n dir.add(item);\n this._symlinkPaths[full] = linkPath;\n this._emit('add', path, entry.stat);\n }\n this._emitReady();\n }.bind(this));\n return true;\n }\n\n // don't follow the same symlink more than once\n if (this._symlinkPaths[full]) return true;\n else this._symlinkPaths[full] = true;\n};\n\n// Private method: Read directory to add / remove files from `@watched` list\n// and re-read it on change.\n\n// * dir - string, fs path.\n// * stats - object, result of fs.stat\n// * initialAdd - boolean, was the file added at watch instantiation?\n// * depth - int, depth relative to user-supplied path\n// * target - string, child path actually targeted for watch\n// * wh - object, common watch helpers for this path\n// * callback - function, called when dir scan is complete\n\n// Returns close function for the watcher instance\nNodeFsHandler.prototype._handleDir =\nfunction(dir, stats, initialAdd, depth, target, wh, callback) {\n var parentDir = this._getWatchedDir(sysPath.dirname(dir));\n var tracked = parentDir.has(sysPath.basename(dir));\n if (!(initialAdd && this.options.ignoreInitial) && !target && !tracked) {\n if (!wh.hasGlob || wh.globFilter(dir)) this._emit('addDir', dir, stats);\n }\n\n // ensure dir is tracked (harmless if redundant)\n parentDir.add(sysPath.basename(dir));\n this._getWatchedDir(dir);\n\n var read = function(directory, initialAdd, done) {\n // Normalize the directory name on Windows\n directory = sysPath.join(directory, '');\n\n if (!wh.hasGlob) {\n var throttler = this._throttle('readdir', directory, 1000);\n if (!throttler) return;\n }\n\n var previous = this._getWatchedDir(wh.path);\n var current = [];\n\n readdirp({\n root: directory,\n entryType: 'all',\n fileFilter: wh.filterPath,\n directoryFilter: wh.filterDir,\n depth: 0,\n lstat: true\n }).on('data', function(entry) {\n var item = entry.path;\n var path = sysPath.join(directory, item);\n current.push(item);\n\n if (entry.stat.isSymbolicLink() &&\n this._handleSymlink(entry, directory, path, item)) return;\n\n // Files that present in current directory snapshot\n // but absent in previous are added to watch list and\n // emit `add` event.\n if (item === target || !target && !previous.has(item)) {\n this._readyCount++;\n\n // ensure relativeness of path is preserved in case of watcher reuse\n path = sysPath.join(dir, sysPath.relative(dir, path));\n\n this._addToNodeFs(path, initialAdd, wh, depth + 1);\n }\n }.bind(this)).on('end', function() {\n var wasThrottled = throttler ? throttler.clear() : false;\n if (done) done();\n\n // Files that absent in current directory snapshot\n // but present in previous emit `remove` event\n // and are removed from @watched[directory].\n previous.children().filter(function(item) {\n return item !== directory &&\n current.indexOf(item) === -1 &&\n // in case of intersecting globs;\n // a path may have been filtered out of this readdir, but\n // shouldn't be removed because it matches a different glob\n (!wh.hasGlob || wh.filterPath({\n fullPath: sysPath.resolve(directory, item)\n }));\n }).forEach(function(item) {\n this._remove(directory, item);\n }, this);\n\n // one more time for any missed in case changes came in extremely quickly\n if (wasThrottled) read(directory, false);\n }.bind(this)).on('error', this._handleError.bind(this));\n }.bind(this);\n\n var closer;\n\n if (this.options.depth == null || depth <= this.options.depth) {\n if (!target) read(dir, initialAdd, callback);\n closer = this._watchWithNodeFs(dir, function(dirPath, stats) {\n // if current directory is removed, do nothing\n if (stats && stats.mtime.getTime() === 0) return;\n\n read(dirPath, false);\n });\n } else {\n callback();\n }\n return closer;\n};\n\n// Private method: Handle added file, directory, or glob pattern.\n// Delegates call to _handleFile / _handleDir after checks.\n\n// * path - string, path to file or directory.\n// * initialAdd - boolean, was the file added at watch instantiation?\n// * depth - int, depth relative to user-supplied path\n// * target - string, child path actually targeted for watch\n// * callback - function, indicates whether the path was found or not\n\n// Returns nothing\nNodeFsHandler.prototype._addToNodeFs =\nfunction(path, initialAdd, priorWh, depth, target, callback) {\n if (!callback) callback = Function.prototype;\n var ready = this._emitReady;\n if (this._isIgnored(path) || this.closed) {\n ready();\n return callback(null, false);\n }\n\n var wh = this._getWatchHelpers(path, depth);\n if (!wh.hasGlob && priorWh) {\n wh.hasGlob = priorWh.hasGlob;\n wh.globFilter = priorWh.globFilter;\n wh.filterPath = priorWh.filterPath;\n wh.filterDir = priorWh.filterDir;\n }\n\n // evaluate what is at the path we're being asked to watch\n fs[wh.statMethod](wh.watchPath, function(error, stats) {\n if (this._handleError(error)) return callback(null, path);\n if (this._isIgnored(wh.watchPath, stats)) {\n ready();\n return callback(null, false);\n }\n\n var initDir = function(dir, target) {\n return this._handleDir(dir, stats, initialAdd, depth, target, wh, ready);\n }.bind(this);\n\n var closer;\n if (stats.isDirectory()) {\n closer = initDir(wh.watchPath, target);\n } else if (stats.isSymbolicLink()) {\n var parent = sysPath.dirname(wh.watchPath);\n this._getWatchedDir(parent).add(wh.watchPath);\n this._emit('add', wh.watchPath, stats);\n closer = initDir(parent, path);\n\n // preserve this symlink's target path\n fs.realpath(path, function(error, targetPath) {\n this._symlinkPaths[sysPath.resolve(path)] = targetPath;\n ready();\n }.bind(this));\n } else {\n closer = this._handleFile(wh.watchPath, stats, initialAdd, ready);\n }\n\n if (closer) {\n this._closers[path] = this._closers[path] || [];\n this._closers[path].push(closer);\n }\n callback(null, false);\n }.bind(this));\n};\n\nmodule.exports = NodeFsHandler;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./chokidar/lib/nodefs-handler.js?"); + +/***/ }), + +/***/ "./node_modules/anymatch/index.js": +/*!****************************************!*\ + !*** ./node_modules/anymatch/index.js ***! + \****************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar micromatch = __webpack_require__(/*! micromatch */ \"./node_modules/micromatch/index.js\");\nvar normalize = __webpack_require__(/*! normalize-path */ \"./node_modules/anymatch/node_modules/normalize-path/index.js\");\nvar path = __webpack_require__(/*! path */ \"path\"); // required for tests.\nvar arrify = function(a) { return a == null ? [] : (Array.isArray(a) ? a : [a]); };\n\nvar anymatch = function(criteria, value, returnIndex, startIndex, endIndex) {\n criteria = arrify(criteria);\n value = arrify(value);\n if (arguments.length === 1) {\n return anymatch.bind(null, criteria.map(function(criterion) {\n return typeof criterion === 'string' && criterion[0] !== '!' ?\n micromatch.matcher(criterion) : criterion;\n }));\n }\n startIndex = startIndex || 0;\n var string = value[0];\n var altString, altValue;\n var matched = false;\n var matchIndex = -1;\n function testCriteria(criterion, index) {\n var result;\n switch (Object.prototype.toString.call(criterion)) {\n case '[object String]':\n result = string === criterion || altString && altString === criterion;\n result = result || micromatch.isMatch(string, criterion);\n break;\n case '[object RegExp]':\n result = criterion.test(string) || altString && criterion.test(altString);\n break;\n case '[object Function]':\n result = criterion.apply(null, value);\n result = result || altValue && criterion.apply(null, altValue);\n break;\n default:\n result = false;\n }\n if (result) {\n matchIndex = index + startIndex;\n }\n return result;\n }\n var crit = criteria;\n var negGlobs = crit.reduce(function(arr, criterion, index) {\n if (typeof criterion === 'string' && criterion[0] === '!') {\n if (crit === criteria) {\n // make a copy before modifying\n crit = crit.slice();\n }\n crit[index] = null;\n arr.push(criterion.substr(1));\n }\n return arr;\n }, []);\n if (!negGlobs.length || !micromatch.any(string, negGlobs)) {\n if (path.sep === '\\\\' && typeof string === 'string') {\n altString = normalize(string);\n altString = altString === string ? null : altString;\n if (altString) altValue = [altString].concat(value.slice(1));\n }\n matched = crit.slice(startIndex, endIndex).some(testCriteria);\n }\n return returnIndex === true ? matchIndex : matched;\n};\n\nmodule.exports = anymatch;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/anymatch/index.js?"); + +/***/ }), + +/***/ "./node_modules/anymatch/node_modules/normalize-path/index.js": +/*!********************************************************************!*\ + !*** ./node_modules/anymatch/node_modules/normalize-path/index.js ***! + \********************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("/*!\n * normalize-path \n *\n * Copyright (c) 2014-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\nvar removeTrailingSeparator = __webpack_require__(/*! remove-trailing-separator */ \"./node_modules/remove-trailing-separator/index.js\");\n\nmodule.exports = function normalizePath(str, stripTrailing) {\n if (typeof str !== 'string') {\n throw new TypeError('expected a string');\n }\n str = str.replace(/[\\\\\\/]+/g, '/');\n if (stripTrailing !== false) {\n str = removeTrailingSeparator(str);\n }\n return str;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/anymatch/node_modules/normalize-path/index.js?"); + +/***/ }), + +/***/ "./node_modules/arr-diff/index.js": +/*!****************************************!*\ + !*** ./node_modules/arr-diff/index.js ***! + \****************************************/ +/***/ ((module) => { + +"use strict"; +eval("/*!\n * arr-diff \n *\n * Copyright (c) 2014-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nmodule.exports = function diff(arr/*, arrays*/) {\n var len = arguments.length;\n var idx = 0;\n while (++idx < len) {\n arr = diffArray(arr, arguments[idx]);\n }\n return arr;\n};\n\nfunction diffArray(one, two) {\n if (!Array.isArray(two)) {\n return one.slice();\n }\n\n var tlen = two.length\n var olen = one.length;\n var idx = -1;\n var arr = [];\n\n while (++idx < olen) {\n var ele = one[idx];\n\n var hasEle = false;\n for (var i = 0; i < tlen; i++) {\n var val = two[i];\n\n if (ele === val) {\n hasEle = true;\n break;\n }\n }\n\n if (hasEle === false) {\n arr.push(ele);\n }\n }\n return arr;\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/arr-diff/index.js?"); + +/***/ }), + +/***/ "./node_modules/arr-flatten/index.js": +/*!*******************************************!*\ + !*** ./node_modules/arr-flatten/index.js ***! + \*******************************************/ +/***/ ((module) => { + +"use strict"; +eval("/*!\n * arr-flatten \n *\n * Copyright (c) 2014-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nmodule.exports = function (arr) {\n return flat(arr, []);\n};\n\nfunction flat(arr, res) {\n var i = 0, cur;\n var len = arr.length;\n for (; i < len; i++) {\n cur = arr[i];\n Array.isArray(cur) ? flat(cur, res) : res.push(cur);\n }\n return res;\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/arr-flatten/index.js?"); + +/***/ }), + +/***/ "./node_modules/arr-union/index.js": +/*!*****************************************!*\ + !*** ./node_modules/arr-union/index.js ***! + \*****************************************/ +/***/ ((module) => { + +"use strict"; +eval("\n\nmodule.exports = function union(init) {\n if (!Array.isArray(init)) {\n throw new TypeError('arr-union expects the first argument to be an array.');\n }\n\n var len = arguments.length;\n var i = 0;\n\n while (++i < len) {\n var arg = arguments[i];\n if (!arg) continue;\n\n if (!Array.isArray(arg)) {\n arg = [arg];\n }\n\n for (var j = 0; j < arg.length; j++) {\n var ele = arg[j];\n\n if (init.indexOf(ele) >= 0) {\n continue;\n }\n init.push(ele);\n }\n }\n return init;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/arr-union/index.js?"); + +/***/ }), + +/***/ "./node_modules/array-unique/index.js": +/*!********************************************!*\ + !*** ./node_modules/array-unique/index.js ***! + \********************************************/ +/***/ ((module) => { + +"use strict"; +eval("/*!\n * array-unique \n *\n * Copyright (c) 2014-2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n\n\nmodule.exports = function unique(arr) {\n if (!Array.isArray(arr)) {\n throw new TypeError('array-unique expects an array.');\n }\n\n var len = arr.length;\n var i = -1;\n\n while (i++ < len) {\n var j = i + 1;\n\n for (; j < arr.length; ++j) {\n if (arr[i] === arr[j]) {\n arr.splice(j--, 1);\n }\n }\n }\n return arr;\n};\n\nmodule.exports.immutable = function uniqueImmutable(arr) {\n if (!Array.isArray(arr)) {\n throw new TypeError('array-unique expects an array.');\n }\n\n var arrLen = arr.length;\n var newArr = new Array(arrLen);\n\n for (var i = 0; i < arrLen; i++) {\n newArr[i] = arr[i];\n }\n\n return module.exports(newArr);\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/array-unique/index.js?"); + +/***/ }), + +/***/ "./node_modules/assign-symbols/index.js": +/*!**********************************************!*\ + !*** ./node_modules/assign-symbols/index.js ***! + \**********************************************/ +/***/ ((module) => { + +"use strict"; +eval("/*!\n * assign-symbols \n *\n * Copyright (c) 2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n\n\nmodule.exports = function(receiver, objects) {\n if (receiver === null || typeof receiver === 'undefined') {\n throw new TypeError('expected first argument to be an object.');\n }\n\n if (typeof objects === 'undefined' || typeof Symbol === 'undefined') {\n return receiver;\n }\n\n if (typeof Object.getOwnPropertySymbols !== 'function') {\n return receiver;\n }\n\n var isEnumerable = Object.prototype.propertyIsEnumerable;\n var target = Object(receiver);\n var len = arguments.length, i = 0;\n\n while (++i < len) {\n var provider = Object(arguments[i]);\n var names = Object.getOwnPropertySymbols(provider);\n\n for (var j = 0; j < names.length; j++) {\n var key = names[j];\n\n if (isEnumerable.call(provider, key)) {\n target[key] = provider[key];\n }\n }\n }\n return target;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/assign-symbols/index.js?"); + +/***/ }), + +/***/ "./node_modules/async-each/index.js": +/*!******************************************!*\ + !*** ./node_modules/async-each/index.js ***! + \******************************************/ +/***/ (function(module, exports) { + +eval("var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// async-each MIT license (by Paul Miller from https://paulmillr.com).\n(function(globals) {\n 'use strict';\n var each = function(items, next, callback) {\n if (!Array.isArray(items)) throw new TypeError('each() expects array as first argument');\n if (typeof next !== 'function') throw new TypeError('each() expects function as second argument');\n if (typeof callback !== 'function') callback = Function.prototype; // no-op\n\n if (items.length === 0) return callback(undefined, items);\n\n var transformed = new Array(items.length);\n var count = 0;\n var returned = false;\n\n items.forEach(function(item, index) {\n next(item, function(error, transformedItem) {\n if (returned) return;\n if (error) {\n returned = true;\n return callback(error);\n }\n transformed[index] = transformedItem;\n count += 1;\n if (count === items.length) return callback(undefined, transformed);\n });\n });\n };\n\n if (true) {\n !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() {\n return each;\n }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),\n\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); // RequireJS\n } else {}\n})(this);\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/async-each/index.js?"); + +/***/ }), + +/***/ "./node_modules/atob/node-atob.js": +/*!****************************************!*\ + !*** ./node_modules/atob/node-atob.js ***! + \****************************************/ +/***/ ((module) => { + +"use strict"; +eval("\n\nfunction atob(str) {\n return Buffer.from(str, 'base64').toString('binary');\n}\n\nmodule.exports = atob.atob = atob;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/atob/node-atob.js?"); + +/***/ }), + +/***/ "./node_modules/base/index.js": +/*!************************************!*\ + !*** ./node_modules/base/index.js ***! + \************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar util = __webpack_require__(/*! util */ \"util\");\nvar define = __webpack_require__(/*! define-property */ \"./node_modules/base/node_modules/define-property/index.js\");\nvar CacheBase = __webpack_require__(/*! cache-base */ \"./node_modules/cache-base/index.js\");\nvar Emitter = __webpack_require__(/*! component-emitter */ \"./node_modules/component-emitter/index.js\");\nvar isObject = __webpack_require__(/*! isobject */ \"./node_modules/isobject/index.js\");\nvar merge = __webpack_require__(/*! mixin-deep */ \"./node_modules/mixin-deep/index.js\");\nvar pascal = __webpack_require__(/*! pascalcase */ \"./node_modules/pascalcase/index.js\");\nvar cu = __webpack_require__(/*! class-utils */ \"./node_modules/class-utils/index.js\");\n\n/**\n * Optionally define a custom `cache` namespace to use.\n */\n\nfunction namespace(name) {\n var Cache = name ? CacheBase.namespace(name) : CacheBase;\n var fns = [];\n\n /**\n * Create an instance of `Base` with the given `config` and `options`.\n *\n * ```js\n * // initialize with `config` and `options`\n * var app = new Base({isApp: true}, {abc: true});\n * app.set('foo', 'bar');\n *\n * // values defined with the given `config` object will be on the root of the instance\n * console.log(app.baz); //=> undefined\n * console.log(app.foo); //=> 'bar'\n * // or use `.get`\n * console.log(app.get('isApp')); //=> true\n * console.log(app.get('foo')); //=> 'bar'\n *\n * // values defined with the given `options` object will be on `app.options\n * console.log(app.options.abc); //=> true\n * ```\n *\n * @param {Object} `config` If supplied, this object is passed to [cache-base][] to merge onto the the instance upon instantiation.\n * @param {Object} `options` If supplied, this object is used to initialize the `base.options` object.\n * @api public\n */\n\n function Base(config, options) {\n if (!(this instanceof Base)) {\n return new Base(config, options);\n }\n Cache.call(this, config);\n this.is('base');\n this.initBase(config, options);\n }\n\n /**\n * Inherit cache-base\n */\n\n util.inherits(Base, Cache);\n\n /**\n * Add static emitter methods\n */\n\n Emitter(Base);\n\n /**\n * Initialize `Base` defaults with the given `config` object\n */\n\n Base.prototype.initBase = function(config, options) {\n this.options = merge({}, this.options, options);\n this.cache = this.cache || {};\n this.define('registered', {});\n if (name) this[name] = {};\n\n // make `app._callbacks` non-enumerable\n this.define('_callbacks', this._callbacks);\n if (isObject(config)) {\n this.visit('set', config);\n }\n Base.run(this, 'use', fns);\n };\n\n /**\n * Set the given `name` on `app._name` and `app.is*` properties. Used for doing\n * lookups in plugins.\n *\n * ```js\n * app.is('foo');\n * console.log(app._name);\n * //=> 'foo'\n * console.log(app.isFoo);\n * //=> true\n * app.is('bar');\n * console.log(app.isFoo);\n * //=> true\n * console.log(app.isBar);\n * //=> true\n * console.log(app._name);\n * //=> 'bar'\n * ```\n * @name .is\n * @param {String} `name`\n * @return {Boolean}\n * @api public\n */\n\n Base.prototype.is = function(name) {\n if (typeof name !== 'string') {\n throw new TypeError('expected name to be a string');\n }\n this.define('is' + pascal(name), true);\n this.define('_name', name);\n this.define('_appname', name);\n return this;\n };\n\n /**\n * Returns true if a plugin has already been registered on an instance.\n *\n * Plugin implementors are encouraged to use this first thing in a plugin\n * to prevent the plugin from being called more than once on the same\n * instance.\n *\n * ```js\n * var base = new Base();\n * base.use(function(app) {\n * if (app.isRegistered('myPlugin')) return;\n * // do stuff to `app`\n * });\n *\n * // to also record the plugin as being registered\n * base.use(function(app) {\n * if (app.isRegistered('myPlugin', true)) return;\n * // do stuff to `app`\n * });\n * ```\n * @name .isRegistered\n * @emits `plugin` Emits the name of the plugin being registered. Useful for unit tests, to ensure plugins are only registered once.\n * @param {String} `name` The plugin name.\n * @param {Boolean} `register` If the plugin if not already registered, to record it as being registered pass `true` as the second argument.\n * @return {Boolean} Returns true if a plugin is already registered.\n * @api public\n */\n\n Base.prototype.isRegistered = function(name, register) {\n if (this.registered.hasOwnProperty(name)) {\n return true;\n }\n if (register !== false) {\n this.registered[name] = true;\n this.emit('plugin', name);\n }\n return false;\n };\n\n /**\n * Define a plugin function to be called immediately upon init. Plugins are chainable\n * and expose the following arguments to the plugin function:\n *\n * - `app`: the current instance of `Base`\n * - `base`: the [first ancestor instance](#base) of `Base`\n *\n * ```js\n * var app = new Base()\n * .use(foo)\n * .use(bar)\n * .use(baz)\n * ```\n * @name .use\n * @param {Function} `fn` plugin function to call\n * @return {Object} Returns the item instance for chaining.\n * @api public\n */\n\n Base.prototype.use = function(fn) {\n fn.call(this, this);\n return this;\n };\n\n /**\n * The `.define` method is used for adding non-enumerable property on the instance.\n * Dot-notation is **not supported** with `define`.\n *\n * ```js\n * // arbitrary `render` function using lodash `template`\n * app.define('render', function(str, locals) {\n * return _.template(str)(locals);\n * });\n * ```\n * @name .define\n * @param {String} `key` The name of the property to define.\n * @param {any} `value`\n * @return {Object} Returns the instance for chaining.\n * @api public\n */\n\n Base.prototype.define = function(key, val) {\n if (isObject(key)) {\n return this.visit('define', key);\n }\n define(this, key, val);\n return this;\n };\n\n /**\n * Mix property `key` onto the Base prototype. If base is inherited using\n * `Base.extend` this method will be overridden by a new `mixin` method that will\n * only add properties to the prototype of the inheriting application.\n *\n * ```js\n * app.mixin('foo', function() {\n * // do stuff\n * });\n * ```\n * @name .mixin\n * @param {String} `key`\n * @param {Object|Array} `val`\n * @return {Object} Returns the `base` instance for chaining.\n * @api public\n */\n\n Base.prototype.mixin = function(key, val) {\n Base.prototype[key] = val;\n return this;\n };\n\n /**\n * Non-enumberable mixin array, used by the static [Base.mixin]() method.\n */\n\n Base.prototype.mixins = Base.prototype.mixins || [];\n\n /**\n * Getter/setter used when creating nested instances of `Base`, for storing a reference\n * to the first ancestor instance. This works by setting an instance of `Base` on the `parent`\n * property of a \"child\" instance. The `base` property defaults to the current instance if\n * no `parent` property is defined.\n *\n * ```js\n * // create an instance of `Base`, this is our first (\"base\") instance\n * var first = new Base();\n * first.foo = 'bar'; // arbitrary property, to make it easier to see what's happening later\n *\n * // create another instance\n * var second = new Base();\n * // create a reference to the first instance (`first`)\n * second.parent = first;\n *\n * // create another instance\n * var third = new Base();\n * // create a reference to the previous instance (`second`)\n * // repeat this pattern every time a \"child\" instance is created\n * third.parent = second;\n *\n * // we can always access the first instance using the `base` property\n * console.log(first.base.foo);\n * //=> 'bar'\n * console.log(second.base.foo);\n * //=> 'bar'\n * console.log(third.base.foo);\n * //=> 'bar'\n * // and now you know how to get to third base ;)\n * ```\n * @name .base\n * @api public\n */\n\n Object.defineProperty(Base.prototype, 'base', {\n configurable: true,\n get: function() {\n return this.parent ? this.parent.base : this;\n }\n });\n\n /**\n * Static method for adding global plugin functions that will\n * be added to an instance when created.\n *\n * ```js\n * Base.use(function(app) {\n * app.foo = 'bar';\n * });\n * var app = new Base();\n * console.log(app.foo);\n * //=> 'bar'\n * ```\n * @name #use\n * @param {Function} `fn` Plugin function to use on each instance.\n * @return {Object} Returns the `Base` constructor for chaining\n * @api public\n */\n\n define(Base, 'use', function(fn) {\n fns.push(fn);\n return Base;\n });\n\n /**\n * Run an array of functions by passing each function\n * to a method on the given object specified by the given property.\n *\n * @param {Object} `obj` Object containing method to use.\n * @param {String} `prop` Name of the method on the object to use.\n * @param {Array} `arr` Array of functions to pass to the method.\n */\n\n define(Base, 'run', function(obj, prop, arr) {\n var len = arr.length, i = 0;\n while (len--) {\n obj[prop](arr[i++]);\n }\n return Base;\n });\n\n /**\n * Static method for inheriting the prototype and static methods of the `Base` class.\n * This method greatly simplifies the process of creating inheritance-based applications.\n * See [static-extend][] for more details.\n *\n * ```js\n * var extend = cu.extend(Parent);\n * Parent.extend(Child);\n *\n * // optional methods\n * Parent.extend(Child, {\n * foo: function() {},\n * bar: function() {}\n * });\n * ```\n * @name #extend\n * @param {Function} `Ctor` constructor to extend\n * @param {Object} `methods` Optional prototype properties to mix in.\n * @return {Object} Returns the `Base` constructor for chaining\n * @api public\n */\n\n define(Base, 'extend', cu.extend(Base, function(Ctor, Parent) {\n Ctor.prototype.mixins = Ctor.prototype.mixins || [];\n\n define(Ctor, 'mixin', function(fn) {\n var mixin = fn(Ctor.prototype, Ctor);\n if (typeof mixin === 'function') {\n Ctor.prototype.mixins.push(mixin);\n }\n return Ctor;\n });\n\n define(Ctor, 'mixins', function(Child) {\n Base.run(Child, 'mixin', Ctor.prototype.mixins);\n return Ctor;\n });\n\n Ctor.prototype.mixin = function(key, value) {\n Ctor.prototype[key] = value;\n return this;\n };\n return Base;\n }));\n\n /**\n * Used for adding methods to the `Base` prototype, and/or to the prototype of child instances.\n * When a mixin function returns a function, the returned function is pushed onto the `.mixins`\n * array, making it available to be used on inheriting classes whenever `Base.mixins()` is\n * called (e.g. `Base.mixins(Child)`).\n *\n * ```js\n * Base.mixin(function(proto) {\n * proto.foo = function(msg) {\n * return 'foo ' + msg;\n * };\n * });\n * ```\n * @name #mixin\n * @param {Function} `fn` Function to call\n * @return {Object} Returns the `Base` constructor for chaining\n * @api public\n */\n\n define(Base, 'mixin', function(fn) {\n var mixin = fn(Base.prototype, Base);\n if (typeof mixin === 'function') {\n Base.prototype.mixins.push(mixin);\n }\n return Base;\n });\n\n /**\n * Static method for running global mixin functions against a child constructor.\n * Mixins must be registered before calling this method.\n *\n * ```js\n * Base.extend(Child);\n * Base.mixins(Child);\n * ```\n * @name #mixins\n * @param {Function} `Child` Constructor function of a child class\n * @return {Object} Returns the `Base` constructor for chaining\n * @api public\n */\n\n define(Base, 'mixins', function(Child) {\n Base.run(Child, 'mixin', Base.prototype.mixins);\n return Base;\n });\n\n /**\n * Similar to `util.inherit`, but copies all static properties, prototype properties, and\n * getters/setters from `Provider` to `Receiver`. See [class-utils][]{#inherit} for more details.\n *\n * ```js\n * Base.inherit(Foo, Bar);\n * ```\n * @name #inherit\n * @param {Function} `Receiver` Receiving (child) constructor\n * @param {Function} `Provider` Providing (parent) constructor\n * @return {Object} Returns the `Base` constructor for chaining\n * @api public\n */\n\n define(Base, 'inherit', cu.inherit);\n define(Base, 'bubble', cu.bubble);\n return Base;\n}\n\n/**\n * Expose `Base` with default settings\n */\n\nmodule.exports = namespace();\n\n/**\n * Allow users to define a namespace\n */\n\nmodule.exports.namespace = namespace;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/base/index.js?"); + +/***/ }), + +/***/ "./node_modules/base/node_modules/define-property/index.js": +/*!*****************************************************************!*\ + !*** ./node_modules/base/node_modules/define-property/index.js ***! + \*****************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * define-property \n *\n * Copyright (c) 2015, 2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar isDescriptor = __webpack_require__(/*! is-descriptor */ \"./node_modules/is-descriptor/index.js\");\n\nmodule.exports = function defineProperty(obj, prop, val) {\n if (typeof obj !== 'object' && typeof obj !== 'function') {\n throw new TypeError('expected an object or function.');\n }\n\n if (typeof prop !== 'string') {\n throw new TypeError('expected `prop` to be a string.');\n }\n\n if (isDescriptor(val) && ('set' in val || 'get' in val)) {\n return Object.defineProperty(obj, prop, val);\n }\n\n return Object.defineProperty(obj, prop, {\n configurable: true,\n enumerable: false,\n writable: true,\n value: val\n });\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/base/node_modules/define-property/index.js?"); + +/***/ }), + +/***/ "./node_modules/braces/index.js": +/*!**************************************!*\ + !*** ./node_modules/braces/index.js ***! + \**************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\n/**\n * Module dependencies\n */\n\nvar toRegex = __webpack_require__(/*! to-regex */ \"./node_modules/to-regex/index.js\");\nvar unique = __webpack_require__(/*! array-unique */ \"./node_modules/array-unique/index.js\");\nvar extend = __webpack_require__(/*! extend-shallow */ \"./node_modules/extend-shallow/index.js\");\n\n/**\n * Local dependencies\n */\n\nvar compilers = __webpack_require__(/*! ./lib/compilers */ \"./node_modules/braces/lib/compilers.js\");\nvar parsers = __webpack_require__(/*! ./lib/parsers */ \"./node_modules/braces/lib/parsers.js\");\nvar Braces = __webpack_require__(/*! ./lib/braces */ \"./node_modules/braces/lib/braces.js\");\nvar utils = __webpack_require__(/*! ./lib/utils */ \"./node_modules/braces/lib/utils.js\");\nvar MAX_LENGTH = 1024 * 64;\nvar cache = {};\n\n/**\n * Convert the given `braces` pattern into a regex-compatible string. By default, only one string is generated for every input string. Set `options.expand` to true to return an array of patterns (similar to Bash or minimatch. Before using `options.expand`, it's recommended that you read the [performance notes](#performance)).\n *\n * ```js\n * var braces = require('braces');\n * console.log(braces('{a,b,c}'));\n * //=> ['(a|b|c)']\n *\n * console.log(braces('{a,b,c}', {expand: true}));\n * //=> ['a', 'b', 'c']\n * ```\n * @param {String} `str`\n * @param {Object} `options`\n * @return {String}\n * @api public\n */\n\nfunction braces(pattern, options) {\n var key = utils.createKey(String(pattern), options);\n var arr = [];\n\n var disabled = options && options.cache === false;\n if (!disabled && cache.hasOwnProperty(key)) {\n return cache[key];\n }\n\n if (Array.isArray(pattern)) {\n for (var i = 0; i < pattern.length; i++) {\n arr.push.apply(arr, braces.create(pattern[i], options));\n }\n } else {\n arr = braces.create(pattern, options);\n }\n\n if (options && options.nodupes === true) {\n arr = unique(arr);\n }\n\n if (!disabled) {\n cache[key] = arr;\n }\n return arr;\n}\n\n/**\n * Expands a brace pattern into an array. This method is called by the main [braces](#braces) function when `options.expand` is true. Before using this method it's recommended that you read the [performance notes](#performance)) and advantages of using [.optimize](#optimize) instead.\n *\n * ```js\n * var braces = require('braces');\n * console.log(braces.expand('a/{b,c}/d'));\n * //=> ['a/b/d', 'a/c/d'];\n * ```\n * @param {String} `pattern` Brace pattern\n * @param {Object} `options`\n * @return {Array} Returns an array of expanded values.\n * @api public\n */\n\nbraces.expand = function(pattern, options) {\n return braces.create(pattern, extend({}, options, {expand: true}));\n};\n\n/**\n * Expands a brace pattern into a regex-compatible, optimized string. This method is called by the main [braces](#braces) function by default.\n *\n * ```js\n * var braces = require('braces');\n * console.log(braces.expand('a/{b,c}/d'));\n * //=> ['a/(b|c)/d']\n * ```\n * @param {String} `pattern` Brace pattern\n * @param {Object} `options`\n * @return {Array} Returns an array of expanded values.\n * @api public\n */\n\nbraces.optimize = function(pattern, options) {\n return braces.create(pattern, options);\n};\n\n/**\n * Processes a brace pattern and returns either an expanded array (if `options.expand` is true), a highly optimized regex-compatible string. This method is called by the main [braces](#braces) function.\n *\n * ```js\n * var braces = require('braces');\n * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))\n * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'\n * ```\n * @param {String} `pattern` Brace pattern\n * @param {Object} `options`\n * @return {Array} Returns an array of expanded values.\n * @api public\n */\n\nbraces.create = function(pattern, options) {\n if (typeof pattern !== 'string') {\n throw new TypeError('expected a string');\n }\n\n var maxLength = (options && options.maxLength) || MAX_LENGTH;\n if (pattern.length >= maxLength) {\n throw new Error('expected pattern to be less than ' + maxLength + ' characters');\n }\n\n function create() {\n if (pattern === '' || pattern.length < 3) {\n return [pattern];\n }\n\n if (utils.isEmptySets(pattern)) {\n return [];\n }\n\n if (utils.isQuotedString(pattern)) {\n return [pattern.slice(1, -1)];\n }\n\n var proto = new Braces(options);\n var result = !options || options.expand !== true\n ? proto.optimize(pattern, options)\n : proto.expand(pattern, options);\n\n // get the generated pattern(s)\n var arr = result.output;\n\n // filter out empty strings if specified\n if (options && options.noempty === true) {\n arr = arr.filter(Boolean);\n }\n\n // filter out duplicates if specified\n if (options && options.nodupes === true) {\n arr = unique(arr);\n }\n\n Object.defineProperty(arr, 'result', {\n enumerable: false,\n value: result\n });\n\n return arr;\n }\n\n return memoize('create', pattern, options, create);\n};\n\n/**\n * Create a regular expression from the given string `pattern`.\n *\n * ```js\n * var braces = require('braces');\n *\n * console.log(braces.makeRe('id-{200..300}'));\n * //=> /^(?:id-(20[0-9]|2[1-9][0-9]|300))$/\n * ```\n * @param {String} `pattern` The pattern to convert to regex.\n * @param {Object} `options`\n * @return {RegExp}\n * @api public\n */\n\nbraces.makeRe = function(pattern, options) {\n if (typeof pattern !== 'string') {\n throw new TypeError('expected a string');\n }\n\n var maxLength = (options && options.maxLength) || MAX_LENGTH;\n if (pattern.length >= maxLength) {\n throw new Error('expected pattern to be less than ' + maxLength + ' characters');\n }\n\n function makeRe() {\n var arr = braces(pattern, options);\n var opts = extend({strictErrors: false}, options);\n return toRegex(arr, opts);\n }\n\n return memoize('makeRe', pattern, options, makeRe);\n};\n\n/**\n * Parse the given `str` with the given `options`.\n *\n * ```js\n * var braces = require('braces');\n * var ast = braces.parse('a/{b,c}/d');\n * console.log(ast);\n * // { type: 'root',\n * // errors: [],\n * // input: 'a/{b,c}/d',\n * // nodes:\n * // [ { type: 'bos', val: '' },\n * // { type: 'text', val: 'a/' },\n * // { type: 'brace',\n * // nodes:\n * // [ { type: 'brace.open', val: '{' },\n * // { type: 'text', val: 'b,c' },\n * // { type: 'brace.close', val: '}' } ] },\n * // { type: 'text', val: '/d' },\n * // { type: 'eos', val: '' } ] }\n * ```\n * @param {String} `pattern` Brace pattern to parse\n * @param {Object} `options`\n * @return {Object} Returns an AST\n * @api public\n */\n\nbraces.parse = function(pattern, options) {\n var proto = new Braces(options);\n return proto.parse(pattern, options);\n};\n\n/**\n * Compile the given `ast` or string with the given `options`.\n *\n * ```js\n * var braces = require('braces');\n * var ast = braces.parse('a/{b,c}/d');\n * console.log(braces.compile(ast));\n * // { options: { source: 'string' },\n * // state: {},\n * // compilers:\n * // { eos: [Function],\n * // noop: [Function],\n * // bos: [Function],\n * // brace: [Function],\n * // 'brace.open': [Function],\n * // text: [Function],\n * // 'brace.close': [Function] },\n * // output: [ 'a/(b|c)/d' ],\n * // ast:\n * // { ... },\n * // parsingErrors: [] }\n * ```\n * @param {Object|String} `ast` AST from [.parse](#parse). If a string is passed it will be parsed first.\n * @param {Object} `options`\n * @return {Object} Returns an object that has an `output` property with the compiled string.\n * @api public\n */\n\nbraces.compile = function(ast, options) {\n var proto = new Braces(options);\n return proto.compile(ast, options);\n};\n\n/**\n * Clear the regex cache.\n *\n * ```js\n * braces.clearCache();\n * ```\n * @api public\n */\n\nbraces.clearCache = function() {\n cache = braces.cache = {};\n};\n\n/**\n * Memoize a generated regex or function. A unique key is generated\n * from the method name, pattern, and user-defined options. Set\n * options.memoize to false to disable.\n */\n\nfunction memoize(type, pattern, options, fn) {\n var key = utils.createKey(type + ':' + pattern, options);\n var disabled = options && options.cache === false;\n if (disabled) {\n braces.clearCache();\n return fn(pattern, options);\n }\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n\n var res = fn(pattern, options);\n cache[key] = res;\n return res;\n}\n\n/**\n * Expose `Braces` constructor and methods\n * @type {Function}\n */\n\nbraces.Braces = Braces;\nbraces.compilers = compilers;\nbraces.parsers = parsers;\nbraces.cache = cache;\n\n/**\n * Expose `braces`\n * @type {Function}\n */\n\nmodule.exports = braces;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/braces/index.js?"); + +/***/ }), + +/***/ "./node_modules/braces/lib/braces.js": +/*!*******************************************!*\ + !*** ./node_modules/braces/lib/braces.js ***! + \*******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar extend = __webpack_require__(/*! extend-shallow */ \"./node_modules/extend-shallow/index.js\");\nvar Snapdragon = __webpack_require__(/*! snapdragon */ \"./node_modules/snapdragon/index.js\");\nvar compilers = __webpack_require__(/*! ./compilers */ \"./node_modules/braces/lib/compilers.js\");\nvar parsers = __webpack_require__(/*! ./parsers */ \"./node_modules/braces/lib/parsers.js\");\nvar utils = __webpack_require__(/*! ./utils */ \"./node_modules/braces/lib/utils.js\");\n\n/**\n * Customize Snapdragon parser and renderer\n */\n\nfunction Braces(options) {\n this.options = extend({}, options);\n}\n\n/**\n * Initialize braces\n */\n\nBraces.prototype.init = function(options) {\n if (this.isInitialized) return;\n this.isInitialized = true;\n var opts = utils.createOptions({}, this.options, options);\n this.snapdragon = this.options.snapdragon || new Snapdragon(opts);\n this.compiler = this.snapdragon.compiler;\n this.parser = this.snapdragon.parser;\n\n compilers(this.snapdragon, opts);\n parsers(this.snapdragon, opts);\n\n /**\n * Call Snapdragon `.parse` method. When AST is returned, we check to\n * see if any unclosed braces are left on the stack and, if so, we iterate\n * over the stack and correct the AST so that compilers are called in the correct\n * order and unbalance braces are properly escaped.\n */\n\n utils.define(this.snapdragon, 'parse', function(pattern, options) {\n var parsed = Snapdragon.prototype.parse.apply(this, arguments);\n this.parser.ast.input = pattern;\n\n var stack = this.parser.stack;\n while (stack.length) {\n addParent({type: 'brace.close', val: ''}, stack.pop());\n }\n\n function addParent(node, parent) {\n utils.define(node, 'parent', parent);\n parent.nodes.push(node);\n }\n\n // add non-enumerable parser reference\n utils.define(parsed, 'parser', this.parser);\n return parsed;\n });\n};\n\n/**\n * Decorate `.parse` method\n */\n\nBraces.prototype.parse = function(ast, options) {\n if (ast && typeof ast === 'object' && ast.nodes) return ast;\n this.init(options);\n return this.snapdragon.parse(ast, options);\n};\n\n/**\n * Decorate `.compile` method\n */\n\nBraces.prototype.compile = function(ast, options) {\n if (typeof ast === 'string') {\n ast = this.parse(ast, options);\n } else {\n this.init(options);\n }\n return this.snapdragon.compile(ast, options);\n};\n\n/**\n * Expand\n */\n\nBraces.prototype.expand = function(pattern) {\n var ast = this.parse(pattern, {expand: true});\n return this.compile(ast, {expand: true});\n};\n\n/**\n * Optimize\n */\n\nBraces.prototype.optimize = function(pattern) {\n var ast = this.parse(pattern, {optimize: true});\n return this.compile(ast, {optimize: true});\n};\n\n/**\n * Expose `Braces`\n */\n\nmodule.exports = Braces;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/braces/lib/braces.js?"); + +/***/ }), + +/***/ "./node_modules/braces/lib/compilers.js": +/*!**********************************************!*\ + !*** ./node_modules/braces/lib/compilers.js ***! + \**********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar utils = __webpack_require__(/*! ./utils */ \"./node_modules/braces/lib/utils.js\");\n\nmodule.exports = function(braces, options) {\n braces.compiler\n\n /**\n * bos\n */\n\n .set('bos', function() {\n if (this.output) return;\n this.ast.queue = isEscaped(this.ast) ? [this.ast.val] : [];\n this.ast.count = 1;\n })\n\n /**\n * Square brackets\n */\n\n .set('bracket', function(node) {\n var close = node.close;\n var open = !node.escaped ? '[' : '\\\\[';\n var negated = node.negated;\n var inner = node.inner;\n\n inner = inner.replace(/\\\\(?=[\\\\\\w]|$)/g, '\\\\\\\\');\n if (inner === ']-') {\n inner = '\\\\]\\\\-';\n }\n\n if (negated && inner.indexOf('.') === -1) {\n inner += '.';\n }\n if (negated && inner.indexOf('/') === -1) {\n inner += '/';\n }\n\n var val = open + negated + inner + close;\n var queue = node.parent.queue;\n var last = utils.arrayify(queue.pop());\n\n queue.push(utils.join(last, val));\n queue.push.apply(queue, []);\n })\n\n /**\n * Brace\n */\n\n .set('brace', function(node) {\n node.queue = isEscaped(node) ? [node.val] : [];\n node.count = 1;\n return this.mapVisit(node.nodes);\n })\n\n /**\n * Open\n */\n\n .set('brace.open', function(node) {\n node.parent.open = node.val;\n })\n\n /**\n * Inner\n */\n\n .set('text', function(node) {\n var queue = node.parent.queue;\n var escaped = node.escaped;\n var segs = [node.val];\n\n if (node.optimize === false) {\n options = utils.extend({}, options, {optimize: false});\n }\n\n if (node.multiplier > 1) {\n node.parent.count *= node.multiplier;\n }\n\n if (options.quantifiers === true && utils.isQuantifier(node.val)) {\n escaped = true;\n\n } else if (node.val.length > 1) {\n if (isType(node.parent, 'brace') && !isEscaped(node)) {\n var expanded = utils.expand(node.val, options);\n segs = expanded.segs;\n\n if (expanded.isOptimized) {\n node.parent.isOptimized = true;\n }\n\n // if nothing was expanded, we probably have a literal brace\n if (!segs.length) {\n var val = (expanded.val || node.val);\n if (options.unescape !== false) {\n // unescape unexpanded brace sequence/set separators\n val = val.replace(/\\\\([,.])/g, '$1');\n // strip quotes\n val = val.replace(/[\"'`]/g, '');\n }\n\n segs = [val];\n escaped = true;\n }\n }\n\n } else if (node.val === ',') {\n if (options.expand) {\n node.parent.queue.push(['']);\n segs = [''];\n } else {\n segs = ['|'];\n }\n } else {\n escaped = true;\n }\n\n if (escaped && isType(node.parent, 'brace')) {\n if (node.parent.nodes.length <= 4 && node.parent.count === 1) {\n node.parent.escaped = true;\n } else if (node.parent.length <= 3) {\n node.parent.escaped = true;\n }\n }\n\n if (!hasQueue(node.parent)) {\n node.parent.queue = segs;\n return;\n }\n\n var last = utils.arrayify(queue.pop());\n if (node.parent.count > 1 && options.expand) {\n last = multiply(last, node.parent.count);\n node.parent.count = 1;\n }\n\n queue.push(utils.join(utils.flatten(last), segs.shift()));\n queue.push.apply(queue, segs);\n })\n\n /**\n * Close\n */\n\n .set('brace.close', function(node) {\n var queue = node.parent.queue;\n var prev = node.parent.parent;\n var last = prev.queue.pop();\n var open = node.parent.open;\n var close = node.val;\n\n if (open && close && isOptimized(node, options)) {\n open = '(';\n close = ')';\n }\n\n // if a close brace exists, and the previous segment is one character\n // don't wrap the result in braces or parens\n var ele = utils.last(queue);\n if (node.parent.count > 1 && options.expand) {\n ele = multiply(queue.pop(), node.parent.count);\n node.parent.count = 1;\n queue.push(ele);\n }\n\n if (close && typeof ele === 'string' && ele.length === 1) {\n open = '';\n close = '';\n }\n\n if ((isLiteralBrace(node, options) || noInner(node)) && !node.parent.hasEmpty) {\n queue.push(utils.join(open, queue.pop() || ''));\n queue = utils.flatten(utils.join(queue, close));\n }\n\n if (typeof last === 'undefined') {\n prev.queue = [queue];\n } else {\n prev.queue.push(utils.flatten(utils.join(last, queue)));\n }\n })\n\n /**\n * eos\n */\n\n .set('eos', function(node) {\n if (this.input) return;\n\n if (options.optimize !== false) {\n this.output = utils.last(utils.flatten(this.ast.queue));\n } else if (Array.isArray(utils.last(this.ast.queue))) {\n this.output = utils.flatten(this.ast.queue.pop());\n } else {\n this.output = utils.flatten(this.ast.queue);\n }\n\n if (node.parent.count > 1 && options.expand) {\n this.output = multiply(this.output, node.parent.count);\n }\n\n this.output = utils.arrayify(this.output);\n this.ast.queue = [];\n });\n\n};\n\n/**\n * Multiply the segments in the current brace level\n */\n\nfunction multiply(queue, n, options) {\n return utils.flatten(utils.repeat(utils.arrayify(queue), n));\n}\n\n/**\n * Return true if `node` is escaped\n */\n\nfunction isEscaped(node) {\n return node.escaped === true;\n}\n\n/**\n * Returns true if regex parens should be used for sets. If the parent `type`\n * is not `brace`, then we're on a root node, which means we should never\n * expand segments and open/close braces should be `{}` (since this indicates\n * a brace is missing from the set)\n */\n\nfunction isOptimized(node, options) {\n if (node.parent.isOptimized) return true;\n return isType(node.parent, 'brace')\n && !isEscaped(node.parent)\n && options.expand !== true;\n}\n\n/**\n * Returns true if the value in `node` should be wrapped in a literal brace.\n * @return {Boolean}\n */\n\nfunction isLiteralBrace(node, options) {\n return isEscaped(node.parent) || options.optimize !== false;\n}\n\n/**\n * Returns true if the given `node` does not have an inner value.\n * @return {Boolean}\n */\n\nfunction noInner(node, type) {\n if (node.parent.queue.length === 1) {\n return true;\n }\n var nodes = node.parent.nodes;\n return nodes.length === 3\n && isType(nodes[0], 'brace.open')\n && !isType(nodes[1], 'text')\n && isType(nodes[2], 'brace.close');\n}\n\n/**\n * Returns true if the given `node` is the given `type`\n * @return {Boolean}\n */\n\nfunction isType(node, type) {\n return typeof node !== 'undefined' && node.type === type;\n}\n\n/**\n * Returns true if the given `node` has a non-empty queue.\n * @return {Boolean}\n */\n\nfunction hasQueue(node) {\n return Array.isArray(node.queue) && node.queue.length;\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/braces/lib/compilers.js?"); + +/***/ }), + +/***/ "./node_modules/braces/lib/parsers.js": +/*!********************************************!*\ + !*** ./node_modules/braces/lib/parsers.js ***! + \********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar Node = __webpack_require__(/*! snapdragon-node */ \"./node_modules/snapdragon-node/index.js\");\nvar utils = __webpack_require__(/*! ./utils */ \"./node_modules/braces/lib/utils.js\");\n\n/**\n * Braces parsers\n */\n\nmodule.exports = function(braces, options) {\n braces.parser\n .set('bos', function() {\n if (!this.parsed) {\n this.ast = this.nodes[0] = new Node(this.ast);\n }\n })\n\n /**\n * Character parsers\n */\n\n .set('escape', function() {\n var pos = this.position();\n var m = this.match(/^(?:\\\\(.)|\\$\\{)/);\n if (!m) return;\n\n var prev = this.prev();\n var last = utils.last(prev.nodes);\n\n var node = pos(new Node({\n type: 'text',\n multiplier: 1,\n val: m[0]\n }));\n\n if (node.val === '\\\\\\\\') {\n return node;\n }\n\n if (node.val === '${') {\n var str = this.input;\n var idx = -1;\n var ch;\n\n while ((ch = str[++idx])) {\n this.consume(1);\n node.val += ch;\n if (ch === '\\\\') {\n node.val += str[++idx];\n continue;\n }\n if (ch === '}') {\n break;\n }\n }\n }\n\n if (this.options.unescape !== false) {\n node.val = node.val.replace(/\\\\([{}])/g, '$1');\n }\n\n if (last.val === '\"' && this.input.charAt(0) === '\"') {\n last.val = node.val;\n this.consume(1);\n return;\n }\n\n return concatNodes.call(this, pos, node, prev, options);\n })\n\n /**\n * Brackets: \"[...]\" (basic, this is overridden by\n * other parsers in more advanced implementations)\n */\n\n .set('bracket', function() {\n var isInside = this.isInside('brace');\n var pos = this.position();\n var m = this.match(/^(?:\\[([!^]?)([^\\]]{2,}|\\]-)(\\]|[^*+?]+)|\\[)/);\n if (!m) return;\n\n var prev = this.prev();\n var val = m[0];\n var negated = m[1] ? '^' : '';\n var inner = m[2] || '';\n var close = m[3] || '';\n\n if (isInside && prev.type === 'brace') {\n prev.text = prev.text || '';\n prev.text += val;\n }\n\n var esc = this.input.slice(0, 2);\n if (inner === '' && esc === '\\\\]') {\n inner += esc;\n this.consume(2);\n\n var str = this.input;\n var idx = -1;\n var ch;\n\n while ((ch = str[++idx])) {\n this.consume(1);\n if (ch === ']') {\n close = ch;\n break;\n }\n inner += ch;\n }\n }\n\n return pos(new Node({\n type: 'bracket',\n val: val,\n escaped: close !== ']',\n negated: negated,\n inner: inner,\n close: close\n }));\n })\n\n /**\n * Empty braces (we capture these early to\n * speed up processing in the compiler)\n */\n\n .set('multiplier', function() {\n var isInside = this.isInside('brace');\n var pos = this.position();\n var m = this.match(/^\\{((?:,|\\{,+\\})+)\\}/);\n if (!m) return;\n\n this.multiplier = true;\n var prev = this.prev();\n var val = m[0];\n\n if (isInside && prev.type === 'brace') {\n prev.text = prev.text || '';\n prev.text += val;\n }\n\n var node = pos(new Node({\n type: 'text',\n multiplier: 1,\n match: m,\n val: val\n }));\n\n return concatNodes.call(this, pos, node, prev, options);\n })\n\n /**\n * Open\n */\n\n .set('brace.open', function() {\n var pos = this.position();\n var m = this.match(/^\\{(?!(?:[^\\\\}]?|,+)\\})/);\n if (!m) return;\n\n var prev = this.prev();\n var last = utils.last(prev.nodes);\n\n // if the last parsed character was an extglob character\n // we need to _not optimize_ the brace pattern because\n // it might be mistaken for an extglob by a downstream parser\n if (last && last.val && isExtglobChar(last.val.slice(-1))) {\n last.optimize = false;\n }\n\n var open = pos(new Node({\n type: 'brace.open',\n val: m[0]\n }));\n\n var node = pos(new Node({\n type: 'brace',\n nodes: []\n }));\n\n node.push(open);\n prev.push(node);\n this.push('brace', node);\n })\n\n /**\n * Close\n */\n\n .set('brace.close', function() {\n var pos = this.position();\n var m = this.match(/^\\}/);\n if (!m || !m[0]) return;\n\n var brace = this.pop('brace');\n var node = pos(new Node({\n type: 'brace.close',\n val: m[0]\n }));\n\n if (!this.isType(brace, 'brace')) {\n if (this.options.strict) {\n throw new Error('missing opening \"{\"');\n }\n node.type = 'text';\n node.multiplier = 0;\n node.escaped = true;\n return node;\n }\n\n var prev = this.prev();\n var last = utils.last(prev.nodes);\n if (last.text) {\n var lastNode = utils.last(last.nodes);\n if (lastNode.val === ')' && /[!@*?+]\\(/.test(last.text)) {\n var open = last.nodes[0];\n var text = last.nodes[1];\n if (open.type === 'brace.open' && text && text.type === 'text') {\n text.optimize = false;\n }\n }\n }\n\n if (brace.nodes.length > 2) {\n var first = brace.nodes[1];\n if (first.type === 'text' && first.val === ',') {\n brace.nodes.splice(1, 1);\n brace.nodes.push(first);\n }\n }\n\n brace.push(node);\n })\n\n /**\n * Capture boundary characters\n */\n\n .set('boundary', function() {\n var pos = this.position();\n var m = this.match(/^[$^](?!\\{)/);\n if (!m) return;\n return pos(new Node({\n type: 'text',\n val: m[0]\n }));\n })\n\n /**\n * One or zero, non-comma characters wrapped in braces\n */\n\n .set('nobrace', function() {\n var isInside = this.isInside('brace');\n var pos = this.position();\n var m = this.match(/^\\{[^,]?\\}/);\n if (!m) return;\n\n var prev = this.prev();\n var val = m[0];\n\n if (isInside && prev.type === 'brace') {\n prev.text = prev.text || '';\n prev.text += val;\n }\n\n return pos(new Node({\n type: 'text',\n multiplier: 0,\n val: val\n }));\n })\n\n /**\n * Text\n */\n\n .set('text', function() {\n var isInside = this.isInside('brace');\n var pos = this.position();\n var m = this.match(/^((?!\\\\)[^${}[\\]])+/);\n if (!m) return;\n\n var prev = this.prev();\n var val = m[0];\n\n if (isInside && prev.type === 'brace') {\n prev.text = prev.text || '';\n prev.text += val;\n }\n\n var node = pos(new Node({\n type: 'text',\n multiplier: 1,\n val: val\n }));\n\n return concatNodes.call(this, pos, node, prev, options);\n });\n};\n\n/**\n * Returns true if the character is an extglob character.\n */\n\nfunction isExtglobChar(ch) {\n return ch === '!' || ch === '@' || ch === '*' || ch === '?' || ch === '+';\n}\n\n/**\n * Combine text nodes, and calculate empty sets (`{,,}`)\n * @param {Function} `pos` Function to calculate node position\n * @param {Object} `node` AST node\n * @return {Object}\n */\n\nfunction concatNodes(pos, node, parent, options) {\n node.orig = node.val;\n var prev = this.prev();\n var last = utils.last(prev.nodes);\n var isEscaped = false;\n\n if (node.val.length > 1) {\n var a = node.val.charAt(0);\n var b = node.val.slice(-1);\n\n isEscaped = (a === '\"' && b === '\"')\n || (a === \"'\" && b === \"'\")\n || (a === '`' && b === '`');\n }\n\n if (isEscaped && options.unescape !== false) {\n node.val = node.val.slice(1, node.val.length - 1);\n node.escaped = true;\n }\n\n if (node.match) {\n var match = node.match[1];\n if (!match || match.indexOf('}') === -1) {\n match = node.match[0];\n }\n\n // replace each set with a single \",\"\n var val = match.replace(/\\{/g, ',').replace(/\\}/g, '');\n node.multiplier *= val.length;\n node.val = '';\n }\n\n var simpleText = last.type === 'text'\n && last.multiplier === 1\n && node.multiplier === 1\n && node.val;\n\n if (simpleText) {\n last.val += node.val;\n return;\n }\n\n prev.push(node);\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/braces/lib/parsers.js?"); + +/***/ }), + +/***/ "./node_modules/braces/lib/utils.js": +/*!******************************************!*\ + !*** ./node_modules/braces/lib/utils.js ***! + \******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar splitString = __webpack_require__(/*! split-string */ \"./node_modules/split-string/index.js\");\nvar utils = module.exports;\n\n/**\n * Module dependencies\n */\n\nutils.extend = __webpack_require__(/*! extend-shallow */ \"./node_modules/extend-shallow/index.js\");\nutils.flatten = __webpack_require__(/*! arr-flatten */ \"./node_modules/arr-flatten/index.js\");\nutils.isObject = __webpack_require__(/*! isobject */ \"./node_modules/isobject/index.js\");\nutils.fillRange = __webpack_require__(/*! fill-range */ \"./node_modules/fill-range/index.js\");\nutils.repeat = __webpack_require__(/*! repeat-element */ \"./node_modules/repeat-element/index.js\");\nutils.unique = __webpack_require__(/*! array-unique */ \"./node_modules/array-unique/index.js\");\n\nutils.define = function(obj, key, val) {\n Object.defineProperty(obj, key, {\n writable: true,\n configurable: true,\n enumerable: false,\n value: val\n });\n};\n\n/**\n * Returns true if the given string contains only empty brace sets.\n */\n\nutils.isEmptySets = function(str) {\n return /^(?:\\{,\\})+$/.test(str);\n};\n\n/**\n * Returns true if the given string contains only empty brace sets.\n */\n\nutils.isQuotedString = function(str) {\n var open = str.charAt(0);\n if (open === '\\'' || open === '\"' || open === '`') {\n return str.slice(-1) === open;\n }\n return false;\n};\n\n/**\n * Create the key to use for memoization. The unique key is generated\n * by iterating over the options and concatenating key-value pairs\n * to the pattern string.\n */\n\nutils.createKey = function(pattern, options) {\n var id = pattern;\n if (typeof options === 'undefined') {\n return id;\n }\n var keys = Object.keys(options);\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n id += ';' + key + '=' + String(options[key]);\n }\n return id;\n};\n\n/**\n * Normalize options\n */\n\nutils.createOptions = function(options) {\n var opts = utils.extend.apply(null, arguments);\n if (typeof opts.expand === 'boolean') {\n opts.optimize = !opts.expand;\n }\n if (typeof opts.optimize === 'boolean') {\n opts.expand = !opts.optimize;\n }\n if (opts.optimize === true) {\n opts.makeRe = true;\n }\n return opts;\n};\n\n/**\n * Join patterns in `a` to patterns in `b`\n */\n\nutils.join = function(a, b, options) {\n options = options || {};\n a = utils.arrayify(a);\n b = utils.arrayify(b);\n\n if (!a.length) return b;\n if (!b.length) return a;\n\n var len = a.length;\n var idx = -1;\n var arr = [];\n\n while (++idx < len) {\n var val = a[idx];\n if (Array.isArray(val)) {\n for (var i = 0; i < val.length; i++) {\n val[i] = utils.join(val[i], b, options);\n }\n arr.push(val);\n continue;\n }\n\n for (var j = 0; j < b.length; j++) {\n var bval = b[j];\n\n if (Array.isArray(bval)) {\n arr.push(utils.join(val, bval, options));\n } else {\n arr.push(val + bval);\n }\n }\n }\n return arr;\n};\n\n/**\n * Split the given string on `,` if not escaped.\n */\n\nutils.split = function(str, options) {\n var opts = utils.extend({sep: ','}, options);\n if (typeof opts.keepQuotes !== 'boolean') {\n opts.keepQuotes = true;\n }\n if (opts.unescape === false) {\n opts.keepEscaping = true;\n }\n return splitString(str, opts, utils.escapeBrackets(opts));\n};\n\n/**\n * Expand ranges or sets in the given `pattern`.\n *\n * @param {String} `str`\n * @param {Object} `options`\n * @return {Object}\n */\n\nutils.expand = function(str, options) {\n var opts = utils.extend({rangeLimit: 10000}, options);\n var segs = utils.split(str, opts);\n var tok = { segs: segs };\n\n if (utils.isQuotedString(str)) {\n return tok;\n }\n\n if (opts.rangeLimit === true) {\n opts.rangeLimit = 10000;\n }\n\n if (segs.length > 1) {\n if (opts.optimize === false) {\n tok.val = segs[0];\n return tok;\n }\n\n tok.segs = utils.stringifyArray(tok.segs);\n } else if (segs.length === 1) {\n var arr = str.split('..');\n\n if (arr.length === 1) {\n tok.val = tok.segs[tok.segs.length - 1] || tok.val || str;\n tok.segs = [];\n return tok;\n }\n\n if (arr.length === 2 && arr[0] === arr[1]) {\n tok.escaped = true;\n tok.val = arr[0];\n tok.segs = [];\n return tok;\n }\n\n if (arr.length > 1) {\n if (opts.optimize !== false) {\n opts.optimize = true;\n delete opts.expand;\n }\n\n if (opts.optimize !== true) {\n var min = Math.min(arr[0], arr[1]);\n var max = Math.max(arr[0], arr[1]);\n var step = arr[2] || 1;\n\n if (opts.rangeLimit !== false && ((max - min) / step >= opts.rangeLimit)) {\n throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');\n }\n }\n\n arr.push(opts);\n tok.segs = utils.fillRange.apply(null, arr);\n\n if (!tok.segs.length) {\n tok.escaped = true;\n tok.val = str;\n return tok;\n }\n\n if (opts.optimize === true) {\n tok.segs = utils.stringifyArray(tok.segs);\n }\n\n if (tok.segs === '') {\n tok.val = str;\n } else {\n tok.val = tok.segs[0];\n }\n return tok;\n }\n } else {\n tok.val = str;\n }\n return tok;\n};\n\n/**\n * Ensure commas inside brackets and parens are not split.\n * @param {Object} `tok` Token from the `split-string` module\n * @return {undefined}\n */\n\nutils.escapeBrackets = function(options) {\n return function(tok) {\n if (tok.escaped && tok.val === 'b') {\n tok.val = '\\\\b';\n return;\n }\n\n if (tok.val !== '(' && tok.val !== '[') return;\n var opts = utils.extend({}, options);\n var brackets = [];\n var parens = [];\n var stack = [];\n var val = tok.val;\n var str = tok.str;\n var i = tok.idx - 1;\n\n while (++i < str.length) {\n var ch = str[i];\n\n if (ch === '\\\\') {\n val += (opts.keepEscaping === false ? '' : ch) + str[++i];\n continue;\n }\n\n if (ch === '(') {\n parens.push(ch);\n stack.push(ch);\n }\n\n if (ch === '[') {\n brackets.push(ch);\n stack.push(ch);\n }\n\n if (ch === ')') {\n parens.pop();\n stack.pop();\n if (!stack.length) {\n val += ch;\n break;\n }\n }\n\n if (ch === ']') {\n brackets.pop();\n stack.pop();\n if (!stack.length) {\n val += ch;\n break;\n }\n }\n val += ch;\n }\n\n tok.split = false;\n tok.val = val.slice(1);\n tok.idx = i;\n };\n};\n\n/**\n * Returns true if the given string looks like a regex quantifier\n * @return {Boolean}\n */\n\nutils.isQuantifier = function(str) {\n return /^(?:[0-9]?,[0-9]|[0-9],)$/.test(str);\n};\n\n/**\n * Cast `val` to an array.\n * @param {*} `val`\n */\n\nutils.stringifyArray = function(arr) {\n return [utils.arrayify(arr).join('|')];\n};\n\n/**\n * Cast `val` to an array.\n * @param {*} `val`\n */\n\nutils.arrayify = function(arr) {\n if (typeof arr === 'undefined') {\n return [];\n }\n if (typeof arr === 'string') {\n return [arr];\n }\n return arr;\n};\n\n/**\n * Returns true if the given `str` is a non-empty string\n * @return {Boolean}\n */\n\nutils.isString = function(str) {\n return str != null && typeof str === 'string';\n};\n\n/**\n * Get the last element from `array`\n * @param {Array} `array`\n * @return {*}\n */\n\nutils.last = function(arr, n) {\n return arr[arr.length - (n || 1)];\n};\n\nutils.escapeRegex = function(str) {\n return str.replace(/\\\\?([!^*?()[\\]{}+?/])/g, '\\\\$1');\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/braces/lib/utils.js?"); + +/***/ }), + +/***/ "./node_modules/cache-base/index.js": +/*!******************************************!*\ + !*** ./node_modules/cache-base/index.js ***! + \******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar isObject = __webpack_require__(/*! isobject */ \"./node_modules/isobject/index.js\");\nvar Emitter = __webpack_require__(/*! component-emitter */ \"./node_modules/component-emitter/index.js\");\nvar visit = __webpack_require__(/*! collection-visit */ \"./node_modules/collection-visit/index.js\");\nvar toPath = __webpack_require__(/*! to-object-path */ \"./node_modules/to-object-path/index.js\");\nvar union = __webpack_require__(/*! union-value */ \"./node_modules/union-value/index.js\");\nvar del = __webpack_require__(/*! unset-value */ \"./node_modules/unset-value/index.js\");\nvar get = __webpack_require__(/*! get-value */ \"./node_modules/get-value/index.js\");\nvar has = __webpack_require__(/*! has-value */ \"./node_modules/has-value/index.js\");\nvar set = __webpack_require__(/*! set-value */ \"./node_modules/set-value/index.js\");\n\n/**\n * Create a `Cache` constructor that when instantiated will\n * store values on the given `prop`.\n *\n * ```js\n * var Cache = require('cache-base').namespace('data');\n * var cache = new Cache();\n *\n * cache.set('foo', 'bar');\n * //=> {data: {foo: 'bar'}}\n * ```\n * @param {String} `prop` The property name to use for storing values.\n * @return {Function} Returns a custom `Cache` constructor\n * @api public\n */\n\nfunction namespace(prop) {\n\n /**\n * Create a new `Cache`. Internally the `Cache` constructor is created using\n * the `namespace` function, with `cache` defined as the storage object.\n *\n * ```js\n * var app = new Cache();\n * ```\n * @param {Object} `cache` Optionally pass an object to initialize with.\n * @constructor\n * @api public\n */\n\n function Cache(cache) {\n if (prop) {\n this[prop] = {};\n }\n if (cache) {\n this.set(cache);\n }\n }\n\n /**\n * Inherit Emitter\n */\n\n Emitter(Cache.prototype);\n\n /**\n * Assign `value` to `key`. Also emits `set` with\n * the key and value.\n *\n * ```js\n * app.on('set', function(key, val) {\n * // do something when `set` is emitted\n * });\n *\n * app.set(key, value);\n *\n * // also takes an object or array\n * app.set({name: 'Halle'});\n * app.set([{foo: 'bar'}, {baz: 'quux'}]);\n * console.log(app);\n * //=> {name: 'Halle', foo: 'bar', baz: 'quux'}\n * ```\n *\n * @name .set\n * @emits `set` with `key` and `value` as arguments.\n * @param {String} `key`\n * @param {any} `value`\n * @return {Object} Returns the instance for chaining.\n * @api public\n */\n\n Cache.prototype.set = function(key, val) {\n if (Array.isArray(key) && arguments.length === 2) {\n key = toPath(key);\n }\n if (isObject(key) || Array.isArray(key)) {\n this.visit('set', key);\n } else {\n set(prop ? this[prop] : this, key, val);\n this.emit('set', key, val);\n }\n return this;\n };\n\n /**\n * Union `array` to `key`. Also emits `set` with\n * the key and value.\n *\n * ```js\n * app.union('a.b', ['foo']);\n * app.union('a.b', ['bar']);\n * console.log(app.get('a'));\n * //=> {b: ['foo', 'bar']}\n * ```\n * @name .union\n * @param {String} `key`\n * @param {any} `value`\n * @return {Object} Returns the instance for chaining.\n * @api public\n */\n\n Cache.prototype.union = function(key, val) {\n if (Array.isArray(key) && arguments.length === 2) {\n key = toPath(key);\n }\n var ctx = prop ? this[prop] : this;\n union(ctx, key, arrayify(val));\n this.emit('union', val);\n return this;\n };\n\n /**\n * Return the value of `key`. Dot notation may be used\n * to get [nested property values][get-value].\n *\n * ```js\n * app.set('a.b.c', 'd');\n * app.get('a.b');\n * //=> {c: 'd'}\n *\n * app.get(['a', 'b']);\n * //=> {c: 'd'}\n * ```\n *\n * @name .get\n * @emits `get` with `key` and `value` as arguments.\n * @param {String} `key` The name of the property to get. Dot-notation may be used.\n * @return {any} Returns the value of `key`\n * @api public\n */\n\n Cache.prototype.get = function(key) {\n key = toPath(arguments);\n\n var ctx = prop ? this[prop] : this;\n var val = get(ctx, key);\n\n this.emit('get', key, val);\n return val;\n };\n\n /**\n * Return true if app has a stored value for `key`,\n * false only if value is `undefined`.\n *\n * ```js\n * app.set('foo', 'bar');\n * app.has('foo');\n * //=> true\n * ```\n *\n * @name .has\n * @emits `has` with `key` and true or false as arguments.\n * @param {String} `key`\n * @return {Boolean}\n * @api public\n */\n\n Cache.prototype.has = function(key) {\n key = toPath(arguments);\n\n var ctx = prop ? this[prop] : this;\n var val = get(ctx, key);\n\n var has = typeof val !== 'undefined';\n this.emit('has', key, has);\n return has;\n };\n\n /**\n * Delete one or more properties from the instance.\n *\n * ```js\n * app.del(); // delete all\n * // or\n * app.del('foo');\n * // or\n * app.del(['foo', 'bar']);\n * ```\n * @name .del\n * @emits `del` with the `key` as the only argument.\n * @param {String|Array} `key` Property name or array of property names.\n * @return {Object} Returns the instance for chaining.\n * @api public\n */\n\n Cache.prototype.del = function(key) {\n if (Array.isArray(key)) {\n this.visit('del', key);\n } else {\n del(prop ? this[prop] : this, key);\n this.emit('del', key);\n }\n return this;\n };\n\n /**\n * Reset the entire cache to an empty object.\n *\n * ```js\n * app.clear();\n * ```\n * @api public\n */\n\n Cache.prototype.clear = function() {\n if (prop) {\n this[prop] = {};\n }\n };\n\n /**\n * Visit `method` over the properties in the given object, or map\n * visit over the object-elements in an array.\n *\n * @name .visit\n * @param {String} `method` The name of the `base` method to call.\n * @param {Object|Array} `val` The object or array to iterate over.\n * @return {Object} Returns the instance for chaining.\n * @api public\n */\n\n Cache.prototype.visit = function(method, val) {\n visit(this, method, val);\n return this;\n };\n\n return Cache;\n}\n\n/**\n * Cast val to an array\n */\n\nfunction arrayify(val) {\n return val ? (Array.isArray(val) ? val : [val]) : [];\n}\n\n/**\n * Expose `Cache`\n */\n\nmodule.exports = namespace();\n\n/**\n * Expose `Cache.namespace`\n */\n\nmodule.exports.namespace = namespace;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/cache-base/index.js?"); + +/***/ }), + +/***/ "./node_modules/class-utils/index.js": +/*!*******************************************!*\ + !*** ./node_modules/class-utils/index.js ***! + \*******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar util = __webpack_require__(/*! util */ \"util\");\nvar union = __webpack_require__(/*! arr-union */ \"./node_modules/arr-union/index.js\");\nvar define = __webpack_require__(/*! define-property */ \"./node_modules/define-property/index.js\");\nvar staticExtend = __webpack_require__(/*! static-extend */ \"./node_modules/static-extend/index.js\");\nvar isObj = __webpack_require__(/*! isobject */ \"./node_modules/isobject/index.js\");\n\n/**\n * Expose class utils\n */\n\nvar cu = module.exports;\n\n/**\n * Expose class utils: `cu`\n */\n\ncu.isObject = function isObject(val) {\n return isObj(val) || typeof val === 'function';\n};\n\n/**\n * Returns true if an array has any of the given elements, or an\n * object has any of the give keys.\n *\n * ```js\n * cu.has(['a', 'b', 'c'], 'c');\n * //=> true\n *\n * cu.has(['a', 'b', 'c'], ['c', 'z']);\n * //=> true\n *\n * cu.has({a: 'b', c: 'd'}, ['c', 'z']);\n * //=> true\n * ```\n * @param {Object} `obj`\n * @param {String|Array} `val`\n * @return {Boolean}\n * @api public\n */\n\ncu.has = function has(obj, val) {\n val = cu.arrayify(val);\n var len = val.length;\n\n if (cu.isObject(obj)) {\n for (var key in obj) {\n if (val.indexOf(key) > -1) {\n return true;\n }\n }\n\n var keys = cu.nativeKeys(obj);\n return cu.has(keys, val);\n }\n\n if (Array.isArray(obj)) {\n var arr = obj;\n while (len--) {\n if (arr.indexOf(val[len]) > -1) {\n return true;\n }\n }\n return false;\n }\n\n throw new TypeError('expected an array or object.');\n};\n\n/**\n * Returns true if an array or object has all of the given values.\n *\n * ```js\n * cu.hasAll(['a', 'b', 'c'], 'c');\n * //=> true\n *\n * cu.hasAll(['a', 'b', 'c'], ['c', 'z']);\n * //=> false\n *\n * cu.hasAll({a: 'b', c: 'd'}, ['c', 'z']);\n * //=> false\n * ```\n * @param {Object|Array} `val`\n * @param {String|Array} `values`\n * @return {Boolean}\n * @api public\n */\n\ncu.hasAll = function hasAll(val, values) {\n values = cu.arrayify(values);\n var len = values.length;\n while (len--) {\n if (!cu.has(val, values[len])) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Cast the given value to an array.\n *\n * ```js\n * cu.arrayify('foo');\n * //=> ['foo']\n *\n * cu.arrayify(['foo']);\n * //=> ['foo']\n * ```\n *\n * @param {String|Array} `val`\n * @return {Array}\n * @api public\n */\n\ncu.arrayify = function arrayify(val) {\n return val ? (Array.isArray(val) ? val : [val]) : [];\n};\n\n/**\n * Noop\n */\n\ncu.noop = function noop() {\n return;\n};\n\n/**\n * Returns the first argument passed to the function.\n */\n\ncu.identity = function identity(val) {\n return val;\n};\n\n/**\n * Returns true if a value has a `contructor`\n *\n * ```js\n * cu.hasConstructor({});\n * //=> true\n *\n * cu.hasConstructor(Object.create(null));\n * //=> false\n * ```\n * @param {Object} `value`\n * @return {Boolean}\n * @api public\n */\n\ncu.hasConstructor = function hasConstructor(val) {\n return cu.isObject(val) && typeof val.constructor !== 'undefined';\n};\n\n/**\n * Get the native `ownPropertyNames` from the constructor of the\n * given `object`. An empty array is returned if the object does\n * not have a constructor.\n *\n * ```js\n * cu.nativeKeys({a: 'b', b: 'c', c: 'd'})\n * //=> ['a', 'b', 'c']\n *\n * cu.nativeKeys(function(){})\n * //=> ['length', 'caller']\n * ```\n *\n * @param {Object} `obj` Object that has a `constructor`.\n * @return {Array} Array of keys.\n * @api public\n */\n\ncu.nativeKeys = function nativeKeys(val) {\n if (!cu.hasConstructor(val)) return [];\n var keys = Object.getOwnPropertyNames(val);\n if ('caller' in val) keys.push('caller');\n return keys;\n};\n\n/**\n * Returns property descriptor `key` if it's an \"own\" property\n * of the given object.\n *\n * ```js\n * function App() {}\n * Object.defineProperty(App.prototype, 'count', {\n * get: function() {\n * return Object.keys(this).length;\n * }\n * });\n * cu.getDescriptor(App.prototype, 'count');\n * // returns:\n * // {\n * // get: [Function],\n * // set: undefined,\n * // enumerable: false,\n * // configurable: false\n * // }\n * ```\n *\n * @param {Object} `obj`\n * @param {String} `key`\n * @return {Object} Returns descriptor `key`\n * @api public\n */\n\ncu.getDescriptor = function getDescriptor(obj, key) {\n if (!cu.isObject(obj)) {\n throw new TypeError('expected an object.');\n }\n if (typeof key !== 'string') {\n throw new TypeError('expected key to be a string.');\n }\n return Object.getOwnPropertyDescriptor(obj, key);\n};\n\n/**\n * Copy a descriptor from one object to another.\n *\n * ```js\n * function App() {}\n * Object.defineProperty(App.prototype, 'count', {\n * get: function() {\n * return Object.keys(this).length;\n * }\n * });\n * var obj = {};\n * cu.copyDescriptor(obj, App.prototype, 'count');\n * ```\n * @param {Object} `receiver`\n * @param {Object} `provider`\n * @param {String} `name`\n * @return {Object}\n * @api public\n */\n\ncu.copyDescriptor = function copyDescriptor(receiver, provider, name) {\n if (!cu.isObject(receiver)) {\n throw new TypeError('expected receiving object to be an object.');\n }\n if (!cu.isObject(provider)) {\n throw new TypeError('expected providing object to be an object.');\n }\n if (typeof name !== 'string') {\n throw new TypeError('expected name to be a string.');\n }\n\n var val = cu.getDescriptor(provider, name);\n if (val) Object.defineProperty(receiver, name, val);\n};\n\n/**\n * Copy static properties, prototype properties, and descriptors\n * from one object to another.\n *\n * @param {Object} `receiver`\n * @param {Object} `provider`\n * @param {String|Array} `omit` One or more properties to omit\n * @return {Object}\n * @api public\n */\n\ncu.copy = function copy(receiver, provider, omit) {\n if (!cu.isObject(receiver)) {\n throw new TypeError('expected receiving object to be an object.');\n }\n if (!cu.isObject(provider)) {\n throw new TypeError('expected providing object to be an object.');\n }\n var props = Object.getOwnPropertyNames(provider);\n var keys = Object.keys(provider);\n var len = props.length,\n key;\n omit = cu.arrayify(omit);\n\n while (len--) {\n key = props[len];\n\n if (cu.has(keys, key)) {\n define(receiver, key, provider[key]);\n } else if (!(key in receiver) && !cu.has(omit, key)) {\n cu.copyDescriptor(receiver, provider, key);\n }\n }\n};\n\n/**\n * Inherit the static properties, prototype properties, and descriptors\n * from of an object.\n *\n * @param {Object} `receiver`\n * @param {Object} `provider`\n * @param {String|Array} `omit` One or more properties to omit\n * @return {Object}\n * @api public\n */\n\ncu.inherit = function inherit(receiver, provider, omit) {\n if (!cu.isObject(receiver)) {\n throw new TypeError('expected receiving object to be an object.');\n }\n if (!cu.isObject(provider)) {\n throw new TypeError('expected providing object to be an object.');\n }\n\n var keys = [];\n for (var key in provider) {\n keys.push(key);\n receiver[key] = provider[key];\n }\n\n keys = keys.concat(cu.arrayify(omit));\n\n var a = provider.prototype || provider;\n var b = receiver.prototype || receiver;\n cu.copy(b, a, keys);\n};\n\n/**\n * Returns a function for extending the static properties,\n * prototype properties, and descriptors from the `Parent`\n * constructor onto `Child` constructors.\n *\n * ```js\n * var extend = cu.extend(Parent);\n * Parent.extend(Child);\n *\n * // optional methods\n * Parent.extend(Child, {\n * foo: function() {},\n * bar: function() {}\n * });\n * ```\n * @param {Function} `Parent` Parent ctor\n * @param {Function} `extend` Optional extend function to handle custom extensions. Useful when updating methods that require a specific prototype.\n * @param {Function} `Child` Child ctor\n * @param {Object} `proto` Optionally pass additional prototype properties to inherit.\n * @return {Object}\n * @api public\n */\n\ncu.extend = function() {\n // keep it lazy, instead of assigning to `cu.extend`\n return staticExtend.apply(null, arguments);\n};\n\n/**\n * Bubble up events emitted from static methods on the Parent ctor.\n *\n * @param {Object} `Parent`\n * @param {Array} `events` Event names to bubble up\n * @api public\n */\n\ncu.bubble = function(Parent, events) {\n events = events || [];\n Parent.bubble = function(Child, arr) {\n if (Array.isArray(arr)) {\n events = union([], events, arr);\n }\n var len = events.length;\n var idx = -1;\n while (++idx < len) {\n var name = events[idx];\n Parent.on(name, Child.emit.bind(Child, name));\n }\n cu.bubble(Child, events);\n };\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/class-utils/index.js?"); + +/***/ }), + +/***/ "./node_modules/collection-visit/index.js": +/*!************************************************!*\ + !*** ./node_modules/collection-visit/index.js ***! + \************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * collection-visit \n *\n * Copyright (c) 2015, 2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar visit = __webpack_require__(/*! object-visit */ \"./node_modules/object-visit/index.js\");\nvar mapVisit = __webpack_require__(/*! map-visit */ \"./node_modules/map-visit/index.js\");\n\nmodule.exports = function(collection, method, val) {\n var result;\n\n if (typeof val === 'string' && (method in collection)) {\n var args = [].slice.call(arguments, 2);\n result = collection[method].apply(collection, args);\n } else if (Array.isArray(val)) {\n result = mapVisit.apply(null, arguments);\n } else {\n result = visit.apply(null, arguments);\n }\n\n if (typeof result !== 'undefined') {\n return result;\n }\n\n return collection;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/collection-visit/index.js?"); + +/***/ }), + +/***/ "./node_modules/component-emitter/index.js": +/*!*************************************************!*\ + !*** ./node_modules/component-emitter/index.js ***! + \*************************************************/ +/***/ ((module) => { + +eval("\r\n/**\r\n * Expose `Emitter`.\r\n */\r\n\r\nif (true) {\r\n module.exports = Emitter;\r\n}\r\n\r\n/**\r\n * Initialize a new `Emitter`.\r\n *\r\n * @api public\r\n */\r\n\r\nfunction Emitter(obj) {\r\n if (obj) return mixin(obj);\r\n};\r\n\r\n/**\r\n * Mixin the emitter properties.\r\n *\r\n * @param {Object} obj\r\n * @return {Object}\r\n * @api private\r\n */\r\n\r\nfunction mixin(obj) {\r\n for (var key in Emitter.prototype) {\r\n obj[key] = Emitter.prototype[key];\r\n }\r\n return obj;\r\n}\r\n\r\n/**\r\n * Listen on the given `event` with `fn`.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.on =\r\nEmitter.prototype.addEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\r\n .push(fn);\r\n return this;\r\n};\r\n\r\n/**\r\n * Adds an `event` listener that will be invoked a single\r\n * time then automatically removed.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.once = function(event, fn){\r\n function on() {\r\n this.off(event, on);\r\n fn.apply(this, arguments);\r\n }\r\n\r\n on.fn = fn;\r\n this.on(event, on);\r\n return this;\r\n};\r\n\r\n/**\r\n * Remove the given callback for `event` or all\r\n * registered callbacks.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.off =\r\nEmitter.prototype.removeListener =\r\nEmitter.prototype.removeAllListeners =\r\nEmitter.prototype.removeEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n\r\n // all\r\n if (0 == arguments.length) {\r\n this._callbacks = {};\r\n return this;\r\n }\r\n\r\n // specific event\r\n var callbacks = this._callbacks['$' + event];\r\n if (!callbacks) return this;\r\n\r\n // remove all handlers\r\n if (1 == arguments.length) {\r\n delete this._callbacks['$' + event];\r\n return this;\r\n }\r\n\r\n // remove specific handler\r\n var cb;\r\n for (var i = 0; i < callbacks.length; i++) {\r\n cb = callbacks[i];\r\n if (cb === fn || cb.fn === fn) {\r\n callbacks.splice(i, 1);\r\n break;\r\n }\r\n }\r\n\r\n // Remove event specific arrays for event types that no\r\n // one is subscribed for to avoid memory leak.\r\n if (callbacks.length === 0) {\r\n delete this._callbacks['$' + event];\r\n }\r\n\r\n return this;\r\n};\r\n\r\n/**\r\n * Emit `event` with the given args.\r\n *\r\n * @param {String} event\r\n * @param {Mixed} ...\r\n * @return {Emitter}\r\n */\r\n\r\nEmitter.prototype.emit = function(event){\r\n this._callbacks = this._callbacks || {};\r\n\r\n var args = new Array(arguments.length - 1)\r\n , callbacks = this._callbacks['$' + event];\r\n\r\n for (var i = 1; i < arguments.length; i++) {\r\n args[i - 1] = arguments[i];\r\n }\r\n\r\n if (callbacks) {\r\n callbacks = callbacks.slice(0);\r\n for (var i = 0, len = callbacks.length; i < len; ++i) {\r\n callbacks[i].apply(this, args);\r\n }\r\n }\r\n\r\n return this;\r\n};\r\n\r\n/**\r\n * Return array of callbacks for `event`.\r\n *\r\n * @param {String} event\r\n * @return {Array}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.listeners = function(event){\r\n this._callbacks = this._callbacks || {};\r\n return this._callbacks['$' + event] || [];\r\n};\r\n\r\n/**\r\n * Check if this emitter has `event` handlers.\r\n *\r\n * @param {String} event\r\n * @return {Boolean}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.hasListeners = function(event){\r\n return !! this.listeners(event).length;\r\n};\r\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/component-emitter/index.js?"); + +/***/ }), + +/***/ "./node_modules/copy-descriptor/index.js": +/*!***********************************************!*\ + !*** ./node_modules/copy-descriptor/index.js ***! + \***********************************************/ +/***/ ((module) => { + +"use strict"; +eval("/*!\n * copy-descriptor \n *\n * Copyright (c) 2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n\n\n/**\n * Copy a descriptor from one object to another.\n *\n * ```js\n * function App() {\n * this.cache = {};\n * }\n * App.prototype.set = function(key, val) {\n * this.cache[key] = val;\n * return this;\n * };\n * Object.defineProperty(App.prototype, 'count', {\n * get: function() {\n * return Object.keys(this.cache).length;\n * }\n * });\n *\n * copy(App.prototype, 'count', 'len');\n *\n * // create an instance\n * var app = new App();\n *\n * app.set('a', true);\n * app.set('b', true);\n * app.set('c', true);\n *\n * console.log(app.count);\n * //=> 3\n * console.log(app.len);\n * //=> 3\n * ```\n * @name copy\n * @param {Object} `receiver` The target object\n * @param {Object} `provider` The provider object\n * @param {String} `from` The key to copy on provider.\n * @param {String} `to` Optionally specify a new key name to use.\n * @return {Object}\n * @api public\n */\n\nmodule.exports = function copyDescriptor(receiver, provider, from, to) {\n if (!isObject(provider) && typeof provider !== 'function') {\n to = from;\n from = provider;\n provider = receiver;\n }\n if (!isObject(receiver) && typeof receiver !== 'function') {\n throw new TypeError('expected the first argument to be an object');\n }\n if (!isObject(provider) && typeof provider !== 'function') {\n throw new TypeError('expected provider to be an object');\n }\n\n if (typeof to !== 'string') {\n to = from;\n }\n if (typeof from !== 'string') {\n throw new TypeError('expected key to be a string');\n }\n\n if (!(from in provider)) {\n throw new Error('property \"' + from + '\" does not exist');\n }\n\n var val = Object.getOwnPropertyDescriptor(provider, from);\n if (val) Object.defineProperty(receiver, to, val);\n};\n\nfunction isObject(val) {\n return {}.toString.call(val) === '[object Object]';\n}\n\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/copy-descriptor/index.js?"); + +/***/ }), + +/***/ "./node_modules/core-util-is/lib/util.js": +/*!***********************************************!*\ + !*** ./node_modules/core-util-is/lib/util.js ***! + \***********************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\n\nfunction isArray(arg) {\n if (Array.isArray) {\n return Array.isArray(arg);\n }\n return objectToString(arg) === '[object Array]';\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n return (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = __webpack_require__(/*! buffer */ \"buffer\").Buffer.isBuffer;\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/core-util-is/lib/util.js?"); + +/***/ }), + +/***/ "./node_modules/debug/src/browser.js": +/*!*******************************************!*\ + !*** ./node_modules/debug/src/browser.js ***! + \*******************************************/ +/***/ ((module, exports, __webpack_require__) => { + +eval("/**\n * This is the web browser implementation of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = __webpack_require__(/*! ./debug */ \"./node_modules/debug/src/debug.js\");\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = 'undefined' != typeof chrome\n && 'undefined' != typeof chrome.storage\n ? chrome.storage.local\n : localstorage();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n 'lightseagreen',\n 'forestgreen',\n 'goldenrod',\n 'dodgerblue',\n 'darkorchid',\n 'crimson'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\nfunction useColors() {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {\n return true;\n }\n\n // is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n // is firebug? http://stackoverflow.com/a/398120/376773\n (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n // is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n // double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nexports.formatters.j = function(v) {\n try {\n return JSON.stringify(v);\n } catch (err) {\n return '[UnexpectedJSONParseError]: ' + err.message;\n }\n};\n\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n var useColors = this.useColors;\n\n args[0] = (useColors ? '%c' : '')\n + this.namespace\n + (useColors ? ' %c' : ' ')\n + args[0]\n + (useColors ? '%c ' : ' ')\n + '+' + exports.humanize(this.diff);\n\n if (!useColors) return;\n\n var c = 'color: ' + this.color;\n args.splice(1, 0, c, 'color: inherit')\n\n // the final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n var index = 0;\n var lastC = 0;\n args[0].replace(/%[a-zA-Z%]/g, function(match) {\n if ('%%' === match) return;\n index++;\n if ('%c' === match) {\n // we only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index;\n }\n });\n\n args.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.log()` when available.\n * No-op when `console.log` is not a \"function\".\n *\n * @api public\n */\n\nfunction log() {\n // this hackery is required for IE8/9, where\n // the `console.log` function doesn't have 'apply'\n return 'object' === typeof console\n && console.log\n && Function.prototype.apply.call(console.log, console, arguments);\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\n\nfunction save(namespaces) {\n try {\n if (null == namespaces) {\n exports.storage.removeItem('debug');\n } else {\n exports.storage.debug = namespaces;\n }\n } catch(e) {}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n var r;\n try {\n r = exports.storage.debug;\n } catch(e) {}\n\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof process !== 'undefined' && 'env' in process) {\n r = process.env.DEBUG;\n }\n\n return r;\n}\n\n/**\n * Enable namespaces listed in `localStorage.debug` initially.\n */\n\nexports.enable(load());\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n try {\n return window.localStorage;\n } catch (e) {}\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/debug/src/browser.js?"); + +/***/ }), + +/***/ "./node_modules/debug/src/debug.js": +/*!*****************************************!*\ + !*** ./node_modules/debug/src/debug.js ***! + \*****************************************/ +/***/ ((module, exports, __webpack_require__) => { + +eval("\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = createDebug.debug = createDebug['default'] = createDebug;\nexports.coerce = coerce;\nexports.disable = disable;\nexports.enable = enable;\nexports.enabled = enabled;\nexports.humanize = __webpack_require__(/*! ms */ \"./node_modules/ms/index.js\");\n\n/**\n * The currently active debug mode names, and names to skip.\n */\n\nexports.names = [];\nexports.skips = [];\n\n/**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n\nexports.formatters = {};\n\n/**\n * Previous log timestamp.\n */\n\nvar prevTime;\n\n/**\n * Select a color.\n * @param {String} namespace\n * @return {Number}\n * @api private\n */\n\nfunction selectColor(namespace) {\n var hash = 0, i;\n\n for (i in namespace) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n hash |= 0; // Convert to 32bit integer\n }\n\n return exports.colors[Math.abs(hash) % exports.colors.length];\n}\n\n/**\n * Create a debugger with the given `namespace`.\n *\n * @param {String} namespace\n * @return {Function}\n * @api public\n */\n\nfunction createDebug(namespace) {\n\n function debug() {\n // disabled?\n if (!debug.enabled) return;\n\n var self = debug;\n\n // set `diff` timestamp\n var curr = +new Date();\n var ms = curr - (prevTime || curr);\n self.diff = ms;\n self.prev = prevTime;\n self.curr = curr;\n prevTime = curr;\n\n // turn the `arguments` into a proper Array\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n\n args[0] = exports.coerce(args[0]);\n\n if ('string' !== typeof args[0]) {\n // anything else let's inspect with %O\n args.unshift('%O');\n }\n\n // apply any `formatters` transformations\n var index = 0;\n args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {\n // if we encounter an escaped % then don't increase the array index\n if (match === '%%') return match;\n index++;\n var formatter = exports.formatters[format];\n if ('function' === typeof formatter) {\n var val = args[index];\n match = formatter.call(self, val);\n\n // now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1);\n index--;\n }\n return match;\n });\n\n // apply env-specific formatting (colors, etc.)\n exports.formatArgs.call(self, args);\n\n var logFn = debug.log || exports.log || console.log.bind(console);\n logFn.apply(self, args);\n }\n\n debug.namespace = namespace;\n debug.enabled = exports.enabled(namespace);\n debug.useColors = exports.useColors();\n debug.color = selectColor(namespace);\n\n // env-specific initialization logic for debug instances\n if ('function' === typeof exports.init) {\n exports.init(debug);\n }\n\n return debug;\n}\n\n/**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {String} namespaces\n * @api public\n */\n\nfunction enable(namespaces) {\n exports.save(namespaces);\n\n exports.names = [];\n exports.skips = [];\n\n var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n var len = split.length;\n\n for (var i = 0; i < len; i++) {\n if (!split[i]) continue; // ignore empty strings\n namespaces = split[i].replace(/\\*/g, '.*?');\n if (namespaces[0] === '-') {\n exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n } else {\n exports.names.push(new RegExp('^' + namespaces + '$'));\n }\n }\n}\n\n/**\n * Disable debug output.\n *\n * @api public\n */\n\nfunction disable() {\n exports.enable('');\n}\n\n/**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {String} name\n * @return {Boolean}\n * @api public\n */\n\nfunction enabled(name) {\n var i, len;\n for (i = 0, len = exports.skips.length; i < len; i++) {\n if (exports.skips[i].test(name)) {\n return false;\n }\n }\n for (i = 0, len = exports.names.length; i < len; i++) {\n if (exports.names[i].test(name)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Coerce `val`.\n *\n * @param {Mixed} val\n * @return {Mixed}\n * @api private\n */\n\nfunction coerce(val) {\n if (val instanceof Error) return val.stack || val.message;\n return val;\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/debug/src/debug.js?"); + +/***/ }), + +/***/ "./node_modules/debug/src/index.js": +/*!*****************************************!*\ + !*** ./node_modules/debug/src/index.js ***! + \*****************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("/**\n * Detect Electron renderer process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process !== 'undefined' && process.type === 'renderer') {\n module.exports = __webpack_require__(/*! ./browser.js */ \"./node_modules/debug/src/browser.js\");\n} else {\n module.exports = __webpack_require__(/*! ./node.js */ \"./node_modules/debug/src/node.js\");\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/debug/src/index.js?"); + +/***/ }), + +/***/ "./node_modules/debug/src/node.js": +/*!****************************************!*\ + !*** ./node_modules/debug/src/node.js ***! + \****************************************/ +/***/ ((module, exports, __webpack_require__) => { + +eval("/**\n * Module dependencies.\n */\n\nvar tty = __webpack_require__(/*! tty */ \"tty\");\nvar util = __webpack_require__(/*! util */ \"util\");\n\n/**\n * This is the Node.js implementation of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = __webpack_require__(/*! ./debug */ \"./node_modules/debug/src/debug.js\");\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\n\n/**\n * Colors.\n */\n\nexports.colors = [6, 2, 3, 4, 5, 1];\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(function (key) {\n return /^debug_/i.test(key);\n}).reduce(function (obj, key) {\n // camel-case\n var prop = key\n .substring(6)\n .toLowerCase()\n .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });\n\n // coerce string value into JS value\n var val = process.env[key];\n if (/^(yes|on|true|enabled)$/i.test(val)) val = true;\n else if (/^(no|off|false|disabled)$/i.test(val)) val = false;\n else if (val === 'null') val = null;\n else val = Number(val);\n\n obj[prop] = val;\n return obj;\n}, {});\n\n/**\n * The file descriptor to write the `debug()` calls to.\n * Set the `DEBUG_FD` env variable to override with another value. i.e.:\n *\n * $ DEBUG_FD=3 node script.js 3>debug.log\n */\n\nvar fd = parseInt(process.env.DEBUG_FD, 10) || 2;\n\nif (1 !== fd && 2 !== fd) {\n util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')()\n}\n\nvar stream = 1 === fd ? process.stdout :\n 2 === fd ? process.stderr :\n createWritableStdioStream(fd);\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n return 'colors' in exports.inspectOpts\n ? Boolean(exports.inspectOpts.colors)\n : tty.isatty(fd);\n}\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nexports.formatters.o = function(v) {\n this.inspectOpts.colors = this.useColors;\n return util.inspect(v, this.inspectOpts)\n .split('\\n').map(function(str) {\n return str.trim()\n }).join(' ');\n};\n\n/**\n * Map %o to `util.inspect()`, allowing multiple lines if needed.\n */\n\nexports.formatters.O = function(v) {\n this.inspectOpts.colors = this.useColors;\n return util.inspect(v, this.inspectOpts);\n};\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n var name = this.namespace;\n var useColors = this.useColors;\n\n if (useColors) {\n var c = this.color;\n var prefix = ' \\u001b[3' + c + ';1m' + name + ' ' + '\\u001b[0m';\n\n args[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n args.push('\\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\\u001b[0m');\n } else {\n args[0] = new Date().toUTCString()\n + ' ' + name + ' ' + args[0];\n }\n}\n\n/**\n * Invokes `util.format()` with the specified arguments and writes to `stream`.\n */\n\nfunction log() {\n return stream.write(util.format.apply(util, arguments) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\n\nfunction save(namespaces) {\n if (null == namespaces) {\n // If you set a process.env field to null or undefined, it gets cast to the\n // string 'null' or 'undefined'. Just delete instead.\n delete process.env.DEBUG;\n } else {\n process.env.DEBUG = namespaces;\n }\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n return process.env.DEBUG;\n}\n\n/**\n * Copied from `node/src/node.js`.\n *\n * XXX: It's lame that node doesn't expose this API out-of-the-box. It also\n * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.\n */\n\nfunction createWritableStdioStream (fd) {\n var stream;\n var tty_wrap = process.binding('tty_wrap');\n\n // Note stream._type is used for test-module-load-list.js\n\n switch (tty_wrap.guessHandleType(fd)) {\n case 'TTY':\n stream = new tty.WriteStream(fd);\n stream._type = 'tty';\n\n // Hack to have stream not keep the event loop alive.\n // See https://github.com/joyent/node/issues/1726\n if (stream._handle && stream._handle.unref) {\n stream._handle.unref();\n }\n break;\n\n case 'FILE':\n var fs = __webpack_require__(/*! fs */ \"fs\");\n stream = new fs.SyncWriteStream(fd, { autoClose: false });\n stream._type = 'fs';\n break;\n\n case 'PIPE':\n case 'TCP':\n var net = __webpack_require__(/*! net */ \"net\");\n stream = new net.Socket({\n fd: fd,\n readable: false,\n writable: true\n });\n\n // FIXME Should probably have an option in net.Socket to create a\n // stream from an existing fd which is writable only. But for now\n // we'll just add this hack and set the `readable` member to false.\n // Test: ./node test/fixtures/echo.js < /etc/passwd\n stream.readable = false;\n stream.read = null;\n stream._type = 'pipe';\n\n // FIXME Hack to have stream not keep the event loop alive.\n // See https://github.com/joyent/node/issues/1726\n if (stream._handle && stream._handle.unref) {\n stream._handle.unref();\n }\n break;\n\n default:\n // Probably an error on in uv_guess_handle()\n throw new Error('Implement me. Unknown stream file type!');\n }\n\n // For supporting legacy API we put the FD here.\n stream.fd = fd;\n\n stream._isStdio = true;\n\n return stream;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init (debug) {\n debug.inspectOpts = {};\n\n var keys = Object.keys(exports.inspectOpts);\n for (var i = 0; i < keys.length; i++) {\n debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n }\n}\n\n/**\n * Enable namespaces listed in `process.env.DEBUG` initially.\n */\n\nexports.enable(load());\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/debug/src/node.js?"); + +/***/ }), + +/***/ "./node_modules/decode-uri-component/index.js": +/*!****************************************************!*\ + !*** ./node_modules/decode-uri-component/index.js ***! + \****************************************************/ +/***/ ((module) => { + +"use strict"; +eval("\nvar token = '%[a-f0-9]{2}';\nvar singleMatcher = new RegExp(token, 'gi');\nvar multiMatcher = new RegExp('(' + token + ')+', 'gi');\n\nfunction decodeComponents(components, split) {\n\ttry {\n\t\t// Try to decode the entire string first\n\t\treturn decodeURIComponent(components.join(''));\n\t} catch (err) {\n\t\t// Do nothing\n\t}\n\n\tif (components.length === 1) {\n\t\treturn components;\n\t}\n\n\tsplit = split || 1;\n\n\t// Split the array in 2 parts\n\tvar left = components.slice(0, split);\n\tvar right = components.slice(split);\n\n\treturn Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right));\n}\n\nfunction decode(input) {\n\ttry {\n\t\treturn decodeURIComponent(input);\n\t} catch (err) {\n\t\tvar tokens = input.match(singleMatcher);\n\n\t\tfor (var i = 1; i < tokens.length; i++) {\n\t\t\tinput = decodeComponents(tokens, i).join('');\n\n\t\t\ttokens = input.match(singleMatcher);\n\t\t}\n\n\t\treturn input;\n\t}\n}\n\nfunction customDecodeURIComponent(input) {\n\t// Keep track of all the replacements and prefill the map with the `BOM`\n\tvar replaceMap = {\n\t\t'%FE%FF': '\\uFFFD\\uFFFD',\n\t\t'%FF%FE': '\\uFFFD\\uFFFD'\n\t};\n\n\tvar match = multiMatcher.exec(input);\n\twhile (match) {\n\t\ttry {\n\t\t\t// Decode as big chunks as possible\n\t\t\treplaceMap[match[0]] = decodeURIComponent(match[0]);\n\t\t} catch (err) {\n\t\t\tvar result = decode(match[0]);\n\n\t\t\tif (result !== match[0]) {\n\t\t\t\treplaceMap[match[0]] = result;\n\t\t\t}\n\t\t}\n\n\t\tmatch = multiMatcher.exec(input);\n\t}\n\n\t// Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else\n\treplaceMap['%C2'] = '\\uFFFD';\n\n\tvar entries = Object.keys(replaceMap);\n\n\tfor (var i = 0; i < entries.length; i++) {\n\t\t// Replace all decoded components\n\t\tvar key = entries[i];\n\t\tinput = input.replace(new RegExp(key, 'g'), replaceMap[key]);\n\t}\n\n\treturn input;\n}\n\nmodule.exports = function (encodedURI) {\n\tif (typeof encodedURI !== 'string') {\n\t\tthrow new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`');\n\t}\n\n\ttry {\n\t\tencodedURI = encodedURI.replace(/\\+/g, ' ');\n\n\t\t// Try the built in decoder first\n\t\treturn decodeURIComponent(encodedURI);\n\t} catch (err) {\n\t\t// Fallback to a more advanced decoder\n\t\treturn customDecodeURIComponent(encodedURI);\n\t}\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/decode-uri-component/index.js?"); + +/***/ }), + +/***/ "./node_modules/define-property/index.js": +/*!***********************************************!*\ + !*** ./node_modules/define-property/index.js ***! + \***********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * define-property \n *\n * Copyright (c) 2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n\n\nvar isDescriptor = __webpack_require__(/*! is-descriptor */ \"./node_modules/define-property/node_modules/is-descriptor/index.js\");\n\nmodule.exports = function defineProperty(obj, prop, val) {\n if (typeof obj !== 'object' && typeof obj !== 'function') {\n throw new TypeError('expected an object or function.');\n }\n\n if (typeof prop !== 'string') {\n throw new TypeError('expected `prop` to be a string.');\n }\n\n if (isDescriptor(val) && ('set' in val || 'get' in val)) {\n return Object.defineProperty(obj, prop, val);\n }\n\n return Object.defineProperty(obj, prop, {\n configurable: true,\n enumerable: false,\n writable: true,\n value: val\n });\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/define-property/index.js?"); + +/***/ }), + +/***/ "./node_modules/define-property/node_modules/is-accessor-descriptor/index.js": +/*!***********************************************************************************!*\ + !*** ./node_modules/define-property/node_modules/is-accessor-descriptor/index.js ***! + \***********************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * is-accessor-descriptor \n *\n * Copyright (c) 2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n\n\nvar typeOf = __webpack_require__(/*! kind-of */ \"./node_modules/define-property/node_modules/is-accessor-descriptor/node_modules/kind-of/index.js\");\n\n// accessor descriptor properties\nvar accessor = {\n get: 'function',\n set: 'function',\n configurable: 'boolean',\n enumerable: 'boolean'\n};\n\nfunction isAccessorDescriptor(obj, prop) {\n if (typeof prop === 'string') {\n var val = Object.getOwnPropertyDescriptor(obj, prop);\n return typeof val !== 'undefined';\n }\n\n if (typeOf(obj) !== 'object') {\n return false;\n }\n\n if (has(obj, 'value') || has(obj, 'writable')) {\n return false;\n }\n\n if (!has(obj, 'get') || typeof obj.get !== 'function') {\n return false;\n }\n\n // tldr: it's valid to have \"set\" be undefined\n // \"set\" might be undefined if `Object.getOwnPropertyDescriptor`\n // was used to get the value, and only `get` was defined by the user\n if (has(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') {\n return false;\n }\n\n for (var key in obj) {\n if (!accessor.hasOwnProperty(key)) {\n continue;\n }\n\n if (typeOf(obj[key]) === accessor[key]) {\n continue;\n }\n\n if (typeof obj[key] !== 'undefined') {\n return false;\n }\n }\n return true;\n}\n\nfunction has(obj, key) {\n return {}.hasOwnProperty.call(obj, key);\n}\n\n/**\n * Expose `isAccessorDescriptor`\n */\n\nmodule.exports = isAccessorDescriptor;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/define-property/node_modules/is-accessor-descriptor/index.js?"); + +/***/ }), + +/***/ "./node_modules/define-property/node_modules/is-accessor-descriptor/node_modules/kind-of/index.js": +/*!********************************************************************************************************!*\ + !*** ./node_modules/define-property/node_modules/is-accessor-descriptor/node_modules/kind-of/index.js ***! + \********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var isBuffer = __webpack_require__(/*! is-buffer */ \"./node_modules/is-buffer/index.js\");\nvar toString = Object.prototype.toString;\n\n/**\n * Get the native `typeof` a value.\n *\n * @param {*} `val`\n * @return {*} Native javascript type\n */\n\nmodule.exports = function kindOf(val) {\n // primitivies\n if (typeof val === 'undefined') {\n return 'undefined';\n }\n if (val === null) {\n return 'null';\n }\n if (val === true || val === false || val instanceof Boolean) {\n return 'boolean';\n }\n if (typeof val === 'string' || val instanceof String) {\n return 'string';\n }\n if (typeof val === 'number' || val instanceof Number) {\n return 'number';\n }\n\n // functions\n if (typeof val === 'function' || val instanceof Function) {\n return 'function';\n }\n\n // array\n if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {\n return 'array';\n }\n\n // check for instances of RegExp and Date before calling `toString`\n if (val instanceof RegExp) {\n return 'regexp';\n }\n if (val instanceof Date) {\n return 'date';\n }\n\n // other objects\n var type = toString.call(val);\n\n if (type === '[object RegExp]') {\n return 'regexp';\n }\n if (type === '[object Date]') {\n return 'date';\n }\n if (type === '[object Arguments]') {\n return 'arguments';\n }\n if (type === '[object Error]') {\n return 'error';\n }\n\n // buffer\n if (isBuffer(val)) {\n return 'buffer';\n }\n\n // es6: Map, WeakMap, Set, WeakSet\n if (type === '[object Set]') {\n return 'set';\n }\n if (type === '[object WeakSet]') {\n return 'weakset';\n }\n if (type === '[object Map]') {\n return 'map';\n }\n if (type === '[object WeakMap]') {\n return 'weakmap';\n }\n if (type === '[object Symbol]') {\n return 'symbol';\n }\n\n // typed arrays\n if (type === '[object Int8Array]') {\n return 'int8array';\n }\n if (type === '[object Uint8Array]') {\n return 'uint8array';\n }\n if (type === '[object Uint8ClampedArray]') {\n return 'uint8clampedarray';\n }\n if (type === '[object Int16Array]') {\n return 'int16array';\n }\n if (type === '[object Uint16Array]') {\n return 'uint16array';\n }\n if (type === '[object Int32Array]') {\n return 'int32array';\n }\n if (type === '[object Uint32Array]') {\n return 'uint32array';\n }\n if (type === '[object Float32Array]') {\n return 'float32array';\n }\n if (type === '[object Float64Array]') {\n return 'float64array';\n }\n\n // must be a plain object\n return 'object';\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/define-property/node_modules/is-accessor-descriptor/node_modules/kind-of/index.js?"); + +/***/ }), + +/***/ "./node_modules/define-property/node_modules/is-data-descriptor/index.js": +/*!*******************************************************************************!*\ + !*** ./node_modules/define-property/node_modules/is-data-descriptor/index.js ***! + \*******************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * is-data-descriptor \n *\n * Copyright (c) 2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n\n\nvar typeOf = __webpack_require__(/*! kind-of */ \"./node_modules/define-property/node_modules/is-data-descriptor/node_modules/kind-of/index.js\");\n\n// data descriptor properties\nvar data = {\n configurable: 'boolean',\n enumerable: 'boolean',\n writable: 'boolean'\n};\n\nfunction isDataDescriptor(obj, prop) {\n if (typeOf(obj) !== 'object') {\n return false;\n }\n\n if (typeof prop === 'string') {\n var val = Object.getOwnPropertyDescriptor(obj, prop);\n return typeof val !== 'undefined';\n }\n\n if (!('value' in obj) && !('writable' in obj)) {\n return false;\n }\n\n for (var key in obj) {\n if (key === 'value') continue;\n\n if (!data.hasOwnProperty(key)) {\n continue;\n }\n\n if (typeOf(obj[key]) === data[key]) {\n continue;\n }\n\n if (typeof obj[key] !== 'undefined') {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Expose `isDataDescriptor`\n */\n\nmodule.exports = isDataDescriptor;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/define-property/node_modules/is-data-descriptor/index.js?"); + +/***/ }), + +/***/ "./node_modules/define-property/node_modules/is-data-descriptor/node_modules/kind-of/index.js": +/*!****************************************************************************************************!*\ + !*** ./node_modules/define-property/node_modules/is-data-descriptor/node_modules/kind-of/index.js ***! + \****************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var isBuffer = __webpack_require__(/*! is-buffer */ \"./node_modules/is-buffer/index.js\");\nvar toString = Object.prototype.toString;\n\n/**\n * Get the native `typeof` a value.\n *\n * @param {*} `val`\n * @return {*} Native javascript type\n */\n\nmodule.exports = function kindOf(val) {\n // primitivies\n if (typeof val === 'undefined') {\n return 'undefined';\n }\n if (val === null) {\n return 'null';\n }\n if (val === true || val === false || val instanceof Boolean) {\n return 'boolean';\n }\n if (typeof val === 'string' || val instanceof String) {\n return 'string';\n }\n if (typeof val === 'number' || val instanceof Number) {\n return 'number';\n }\n\n // functions\n if (typeof val === 'function' || val instanceof Function) {\n return 'function';\n }\n\n // array\n if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {\n return 'array';\n }\n\n // check for instances of RegExp and Date before calling `toString`\n if (val instanceof RegExp) {\n return 'regexp';\n }\n if (val instanceof Date) {\n return 'date';\n }\n\n // other objects\n var type = toString.call(val);\n\n if (type === '[object RegExp]') {\n return 'regexp';\n }\n if (type === '[object Date]') {\n return 'date';\n }\n if (type === '[object Arguments]') {\n return 'arguments';\n }\n if (type === '[object Error]') {\n return 'error';\n }\n\n // buffer\n if (isBuffer(val)) {\n return 'buffer';\n }\n\n // es6: Map, WeakMap, Set, WeakSet\n if (type === '[object Set]') {\n return 'set';\n }\n if (type === '[object WeakSet]') {\n return 'weakset';\n }\n if (type === '[object Map]') {\n return 'map';\n }\n if (type === '[object WeakMap]') {\n return 'weakmap';\n }\n if (type === '[object Symbol]') {\n return 'symbol';\n }\n\n // typed arrays\n if (type === '[object Int8Array]') {\n return 'int8array';\n }\n if (type === '[object Uint8Array]') {\n return 'uint8array';\n }\n if (type === '[object Uint8ClampedArray]') {\n return 'uint8clampedarray';\n }\n if (type === '[object Int16Array]') {\n return 'int16array';\n }\n if (type === '[object Uint16Array]') {\n return 'uint16array';\n }\n if (type === '[object Int32Array]') {\n return 'int32array';\n }\n if (type === '[object Uint32Array]') {\n return 'uint32array';\n }\n if (type === '[object Float32Array]') {\n return 'float32array';\n }\n if (type === '[object Float64Array]') {\n return 'float64array';\n }\n\n // must be a plain object\n return 'object';\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/define-property/node_modules/is-data-descriptor/node_modules/kind-of/index.js?"); + +/***/ }), + +/***/ "./node_modules/define-property/node_modules/is-descriptor/index.js": +/*!**************************************************************************!*\ + !*** ./node_modules/define-property/node_modules/is-descriptor/index.js ***! + \**************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * is-descriptor \n *\n * Copyright (c) 2015-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar typeOf = __webpack_require__(/*! kind-of */ \"./node_modules/define-property/node_modules/kind-of/index.js\");\nvar isAccessor = __webpack_require__(/*! is-accessor-descriptor */ \"./node_modules/define-property/node_modules/is-accessor-descriptor/index.js\");\nvar isData = __webpack_require__(/*! is-data-descriptor */ \"./node_modules/define-property/node_modules/is-data-descriptor/index.js\");\n\nmodule.exports = function isDescriptor(obj, key) {\n if (typeOf(obj) !== 'object') {\n return false;\n }\n if ('get' in obj) {\n return isAccessor(obj, key);\n }\n return isData(obj, key);\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/define-property/node_modules/is-descriptor/index.js?"); + +/***/ }), + +/***/ "./node_modules/define-property/node_modules/kind-of/index.js": +/*!********************************************************************!*\ + !*** ./node_modules/define-property/node_modules/kind-of/index.js ***! + \********************************************************************/ +/***/ ((module) => { + +eval("var toString = Object.prototype.toString;\n\n/**\n * Get the native `typeof` a value.\n *\n * @param {*} `val`\n * @return {*} Native javascript type\n */\n\nmodule.exports = function kindOf(val) {\n var type = typeof val;\n\n // primitivies\n if (type === 'undefined') {\n return 'undefined';\n }\n if (val === null) {\n return 'null';\n }\n if (val === true || val === false || val instanceof Boolean) {\n return 'boolean';\n }\n if (type === 'string' || val instanceof String) {\n return 'string';\n }\n if (type === 'number' || val instanceof Number) {\n return 'number';\n }\n\n // functions\n if (type === 'function' || val instanceof Function) {\n if (typeof val.constructor.name !== 'undefined' && val.constructor.name.slice(0, 9) === 'Generator') {\n return 'generatorfunction';\n }\n return 'function';\n }\n\n // array\n if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {\n return 'array';\n }\n\n // check for instances of RegExp and Date before calling `toString`\n if (val instanceof RegExp) {\n return 'regexp';\n }\n if (val instanceof Date) {\n return 'date';\n }\n\n // other objects\n type = toString.call(val);\n\n if (type === '[object RegExp]') {\n return 'regexp';\n }\n if (type === '[object Date]') {\n return 'date';\n }\n if (type === '[object Arguments]') {\n return 'arguments';\n }\n if (type === '[object Error]') {\n return 'error';\n }\n if (type === '[object Promise]') {\n return 'promise';\n }\n\n // buffer\n if (isBuffer(val)) {\n return 'buffer';\n }\n\n // es6: Map, WeakMap, Set, WeakSet\n if (type === '[object Set]') {\n return 'set';\n }\n if (type === '[object WeakSet]') {\n return 'weakset';\n }\n if (type === '[object Map]') {\n return 'map';\n }\n if (type === '[object WeakMap]') {\n return 'weakmap';\n }\n if (type === '[object Symbol]') {\n return 'symbol';\n }\n \n if (type === '[object Map Iterator]') {\n return 'mapiterator';\n }\n if (type === '[object Set Iterator]') {\n return 'setiterator';\n }\n if (type === '[object String Iterator]') {\n return 'stringiterator';\n }\n if (type === '[object Array Iterator]') {\n return 'arrayiterator';\n }\n \n // typed arrays\n if (type === '[object Int8Array]') {\n return 'int8array';\n }\n if (type === '[object Uint8Array]') {\n return 'uint8array';\n }\n if (type === '[object Uint8ClampedArray]') {\n return 'uint8clampedarray';\n }\n if (type === '[object Int16Array]') {\n return 'int16array';\n }\n if (type === '[object Uint16Array]') {\n return 'uint16array';\n }\n if (type === '[object Int32Array]') {\n return 'int32array';\n }\n if (type === '[object Uint32Array]') {\n return 'uint32array';\n }\n if (type === '[object Float32Array]') {\n return 'float32array';\n }\n if (type === '[object Float64Array]') {\n return 'float64array';\n }\n\n // must be a plain object\n return 'object';\n};\n\n/**\n * If you need to support Safari 5-7 (8-10 yr-old browser),\n * take a look at https://github.com/feross/is-buffer\n */\n\nfunction isBuffer(val) {\n return val.constructor\n && typeof val.constructor.isBuffer === 'function'\n && val.constructor.isBuffer(val);\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/define-property/node_modules/kind-of/index.js?"); + +/***/ }), + +/***/ "./node_modules/expand-brackets/index.js": +/*!***********************************************!*\ + !*** ./node_modules/expand-brackets/index.js ***! + \***********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\n/**\n * Local dependencies\n */\n\nvar compilers = __webpack_require__(/*! ./lib/compilers */ \"./node_modules/expand-brackets/lib/compilers.js\");\nvar parsers = __webpack_require__(/*! ./lib/parsers */ \"./node_modules/expand-brackets/lib/parsers.js\");\n\n/**\n * Module dependencies\n */\n\nvar debug = __webpack_require__(/*! debug */ \"./node_modules/debug/src/index.js\")('expand-brackets');\nvar extend = __webpack_require__(/*! extend-shallow */ \"./node_modules/extend-shallow/index.js\");\nvar Snapdragon = __webpack_require__(/*! snapdragon */ \"./node_modules/snapdragon/index.js\");\nvar toRegex = __webpack_require__(/*! to-regex */ \"./node_modules/to-regex/index.js\");\n\n/**\n * Parses the given POSIX character class `pattern` and returns a\n * string that can be used for creating regular expressions for matching.\n *\n * @param {String} `pattern`\n * @param {Object} `options`\n * @return {Object}\n * @api public\n */\n\nfunction brackets(pattern, options) {\n debug('initializing from <%s>', __filename);\n var res = brackets.create(pattern, options);\n return res.output;\n}\n\n/**\n * Takes an array of strings and a POSIX character class pattern, and returns a new\n * array with only the strings that matched the pattern.\n *\n * ```js\n * var brackets = require('expand-brackets');\n * console.log(brackets.match(['1', 'a', 'ab'], '[[:alpha:]]'));\n * //=> ['a']\n *\n * console.log(brackets.match(['1', 'a', 'ab'], '[[:alpha:]]+'));\n * //=> ['a', 'ab']\n * ```\n * @param {Array} `arr` Array of strings to match\n * @param {String} `pattern` POSIX character class pattern(s)\n * @param {Object} `options`\n * @return {Array}\n * @api public\n */\n\nbrackets.match = function(arr, pattern, options) {\n arr = [].concat(arr);\n var opts = extend({}, options);\n var isMatch = brackets.matcher(pattern, opts);\n var len = arr.length;\n var idx = -1;\n var res = [];\n\n while (++idx < len) {\n var ele = arr[idx];\n if (isMatch(ele)) {\n res.push(ele);\n }\n }\n\n if (res.length === 0) {\n if (opts.failglob === true) {\n throw new Error('no matches found for \"' + pattern + '\"');\n }\n\n if (opts.nonull === true || opts.nullglob === true) {\n return [pattern.split('\\\\').join('')];\n }\n }\n return res;\n};\n\n/**\n * Returns true if the specified `string` matches the given\n * brackets `pattern`.\n *\n * ```js\n * var brackets = require('expand-brackets');\n *\n * console.log(brackets.isMatch('a.a', '[[:alpha:]].[[:alpha:]]'));\n * //=> true\n * console.log(brackets.isMatch('1.2', '[[:alpha:]].[[:alpha:]]'));\n * //=> false\n * ```\n * @param {String} `string` String to match\n * @param {String} `pattern` Poxis pattern\n * @param {String} `options`\n * @return {Boolean}\n * @api public\n */\n\nbrackets.isMatch = function(str, pattern, options) {\n return brackets.matcher(pattern, options)(str);\n};\n\n/**\n * Takes a POSIX character class pattern and returns a matcher function. The returned\n * function takes the string to match as its only argument.\n *\n * ```js\n * var brackets = require('expand-brackets');\n * var isMatch = brackets.matcher('[[:lower:]].[[:upper:]]');\n *\n * console.log(isMatch('a.a'));\n * //=> false\n * console.log(isMatch('a.A'));\n * //=> true\n * ```\n * @param {String} `pattern` Poxis pattern\n * @param {String} `options`\n * @return {Boolean}\n * @api public\n */\n\nbrackets.matcher = function(pattern, options) {\n var re = brackets.makeRe(pattern, options);\n return function(str) {\n return re.test(str);\n };\n};\n\n/**\n * Create a regular expression from the given `pattern`.\n *\n * ```js\n * var brackets = require('expand-brackets');\n * var re = brackets.makeRe('[[:alpha:]]');\n * console.log(re);\n * //=> /^(?:[a-zA-Z])$/\n * ```\n * @param {String} `pattern` The pattern to convert to regex.\n * @param {Object} `options`\n * @return {RegExp}\n * @api public\n */\n\nbrackets.makeRe = function(pattern, options) {\n var res = brackets.create(pattern, options);\n var opts = extend({strictErrors: false}, options);\n return toRegex(res.output, opts);\n};\n\n/**\n * Parses the given POSIX character class `pattern` and returns an object\n * with the compiled `output` and optional source `map`.\n *\n * ```js\n * var brackets = require('expand-brackets');\n * console.log(brackets('[[:alpha:]]'));\n * // { options: { source: 'string' },\n * // input: '[[:alpha:]]',\n * // state: {},\n * // compilers:\n * // { eos: [Function],\n * // noop: [Function],\n * // bos: [Function],\n * // not: [Function],\n * // escape: [Function],\n * // text: [Function],\n * // posix: [Function],\n * // bracket: [Function],\n * // 'bracket.open': [Function],\n * // 'bracket.inner': [Function],\n * // 'bracket.literal': [Function],\n * // 'bracket.close': [Function] },\n * // output: '[a-zA-Z]',\n * // ast:\n * // { type: 'root',\n * // errors: [],\n * // nodes: [ [Object], [Object], [Object] ] },\n * // parsingErrors: [] }\n * ```\n * @param {String} `pattern`\n * @param {Object} `options`\n * @return {Object}\n * @api public\n */\n\nbrackets.create = function(pattern, options) {\n var snapdragon = (options && options.snapdragon) || new Snapdragon(options);\n compilers(snapdragon);\n parsers(snapdragon);\n\n var ast = snapdragon.parse(pattern, options);\n ast.input = pattern;\n var res = snapdragon.compile(ast, options);\n res.input = pattern;\n return res;\n};\n\n/**\n * Expose `brackets` constructor, parsers and compilers\n */\n\nbrackets.compilers = compilers;\nbrackets.parsers = parsers;\n\n/**\n * Expose `brackets`\n * @type {Function}\n */\n\nmodule.exports = brackets;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/expand-brackets/index.js?"); + +/***/ }), + +/***/ "./node_modules/expand-brackets/lib/compilers.js": +/*!*******************************************************!*\ + !*** ./node_modules/expand-brackets/lib/compilers.js ***! + \*******************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar posix = __webpack_require__(/*! posix-character-classes */ \"./node_modules/posix-character-classes/index.js\");\n\nmodule.exports = function(brackets) {\n brackets.compiler\n\n /**\n * Escaped characters\n */\n\n .set('escape', function(node) {\n return this.emit('\\\\' + node.val.replace(/^\\\\/, ''), node);\n })\n\n /**\n * Text\n */\n\n .set('text', function(node) {\n return this.emit(node.val.replace(/([{}])/g, '\\\\$1'), node);\n })\n\n /**\n * POSIX character classes\n */\n\n .set('posix', function(node) {\n if (node.val === '[::]') {\n return this.emit('\\\\[::\\\\]', node);\n }\n\n var val = posix[node.inner];\n if (typeof val === 'undefined') {\n val = '[' + node.inner + ']';\n }\n return this.emit(val, node);\n })\n\n /**\n * Non-posix brackets\n */\n\n .set('bracket', function(node) {\n return this.mapVisit(node.nodes);\n })\n .set('bracket.open', function(node) {\n return this.emit(node.val, node);\n })\n .set('bracket.inner', function(node) {\n var inner = node.val;\n\n if (inner === '[' || inner === ']') {\n return this.emit('\\\\' + node.val, node);\n }\n if (inner === '^]') {\n return this.emit('^\\\\]', node);\n }\n if (inner === '^') {\n return this.emit('^', node);\n }\n\n if (/-/.test(inner) && !/(\\d-\\d|\\w-\\w)/.test(inner)) {\n inner = inner.split('-').join('\\\\-');\n }\n\n var isNegated = inner.charAt(0) === '^';\n // add slashes to negated brackets, per spec\n if (isNegated && inner.indexOf('/') === -1) {\n inner += '/';\n }\n if (isNegated && inner.indexOf('.') === -1) {\n inner += '.';\n }\n\n // don't unescape `0` (octal literal)\n inner = inner.replace(/\\\\([1-9])/g, '$1');\n return this.emit(inner, node);\n })\n .set('bracket.close', function(node) {\n var val = node.val.replace(/^\\\\/, '');\n if (node.parent.escaped === true) {\n return this.emit('\\\\' + val, node);\n }\n return this.emit(val, node);\n });\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/expand-brackets/lib/compilers.js?"); + +/***/ }), + +/***/ "./node_modules/expand-brackets/lib/parsers.js": +/*!*****************************************************!*\ + !*** ./node_modules/expand-brackets/lib/parsers.js ***! + \*****************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar utils = __webpack_require__(/*! ./utils */ \"./node_modules/expand-brackets/lib/utils.js\");\nvar define = __webpack_require__(/*! define-property */ \"./node_modules/define-property/index.js\");\n\n/**\n * Text regex\n */\n\nvar TEXT_REGEX = '(\\\\[(?=.*\\\\])|\\\\])+';\nvar not = utils.createRegex(TEXT_REGEX);\n\n/**\n * Brackets parsers\n */\n\nfunction parsers(brackets) {\n brackets.state = brackets.state || {};\n brackets.parser.sets.bracket = brackets.parser.sets.bracket || [];\n brackets.parser\n\n .capture('escape', function() {\n if (this.isInside('bracket')) return;\n var pos = this.position();\n var m = this.match(/^\\\\(.)/);\n if (!m) return;\n\n return pos({\n type: 'escape',\n val: m[0]\n });\n })\n\n /**\n * Text parser\n */\n\n .capture('text', function() {\n if (this.isInside('bracket')) return;\n var pos = this.position();\n var m = this.match(not);\n if (!m || !m[0]) return;\n\n return pos({\n type: 'text',\n val: m[0]\n });\n })\n\n /**\n * POSIX character classes: \"[[:alpha:][:digits:]]\"\n */\n\n .capture('posix', function() {\n var pos = this.position();\n var m = this.match(/^\\[:(.*?):\\](?=.*\\])/);\n if (!m) return;\n\n var inside = this.isInside('bracket');\n if (inside) {\n brackets.posix++;\n }\n\n return pos({\n type: 'posix',\n insideBracket: inside,\n inner: m[1],\n val: m[0]\n });\n })\n\n /**\n * Bracket (noop)\n */\n\n .capture('bracket', function() {})\n\n /**\n * Open: '['\n */\n\n .capture('bracket.open', function() {\n var parsed = this.parsed;\n var pos = this.position();\n var m = this.match(/^\\[(?=.*\\])/);\n if (!m) return;\n\n var prev = this.prev();\n var last = utils.last(prev.nodes);\n\n if (parsed.slice(-1) === '\\\\' && !this.isInside('bracket')) {\n last.val = last.val.slice(0, last.val.length - 1);\n return pos({\n type: 'escape',\n val: m[0]\n });\n }\n\n var open = pos({\n type: 'bracket.open',\n val: m[0]\n });\n\n if (last.type === 'bracket.open' || this.isInside('bracket')) {\n open.val = '\\\\' + open.val;\n open.type = 'bracket.inner';\n open.escaped = true;\n return open;\n }\n\n var node = pos({\n type: 'bracket',\n nodes: [open]\n });\n\n define(node, 'parent', prev);\n define(open, 'parent', node);\n this.push('bracket', node);\n prev.nodes.push(node);\n })\n\n /**\n * Bracket text\n */\n\n .capture('bracket.inner', function() {\n if (!this.isInside('bracket')) return;\n var pos = this.position();\n var m = this.match(not);\n if (!m || !m[0]) return;\n\n var next = this.input.charAt(0);\n var val = m[0];\n\n var node = pos({\n type: 'bracket.inner',\n val: val\n });\n\n if (val === '\\\\\\\\') {\n return node;\n }\n\n var first = val.charAt(0);\n var last = val.slice(-1);\n\n if (first === '!') {\n val = '^' + val.slice(1);\n }\n\n if (last === '\\\\' || (val === '^' && next === ']')) {\n val += this.input[0];\n this.consume(1);\n }\n\n node.val = val;\n return node;\n })\n\n /**\n * Close: ']'\n */\n\n .capture('bracket.close', function() {\n var parsed = this.parsed;\n var pos = this.position();\n var m = this.match(/^\\]/);\n if (!m) return;\n\n var prev = this.prev();\n var last = utils.last(prev.nodes);\n\n if (parsed.slice(-1) === '\\\\' && !this.isInside('bracket')) {\n last.val = last.val.slice(0, last.val.length - 1);\n\n return pos({\n type: 'escape',\n val: m[0]\n });\n }\n\n var node = pos({\n type: 'bracket.close',\n rest: this.input,\n val: m[0]\n });\n\n if (last.type === 'bracket.open') {\n node.type = 'bracket.inner';\n node.escaped = true;\n return node;\n }\n\n var bracket = this.pop('bracket');\n if (!this.isType(bracket, 'bracket')) {\n if (this.options.strict) {\n throw new Error('missing opening \"[\"');\n }\n node.type = 'bracket.inner';\n node.escaped = true;\n return node;\n }\n\n bracket.nodes.push(node);\n define(node, 'parent', bracket);\n });\n}\n\n/**\n * Brackets parsers\n */\n\nmodule.exports = parsers;\n\n/**\n * Expose text regex\n */\n\nmodule.exports.TEXT_REGEX = TEXT_REGEX;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/expand-brackets/lib/parsers.js?"); + +/***/ }), + +/***/ "./node_modules/expand-brackets/lib/utils.js": +/*!***************************************************!*\ + !*** ./node_modules/expand-brackets/lib/utils.js ***! + \***************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar toRegex = __webpack_require__(/*! to-regex */ \"./node_modules/to-regex/index.js\");\nvar regexNot = __webpack_require__(/*! regex-not */ \"./node_modules/regex-not/index.js\");\nvar cached;\n\n/**\n * Get the last element from `array`\n * @param {Array} `array`\n * @return {*}\n */\n\nexports.last = function(arr) {\n return arr[arr.length - 1];\n};\n\n/**\n * Create and cache regex to use for text nodes\n */\n\nexports.createRegex = function(pattern, include) {\n if (cached) return cached;\n var opts = {contains: true, strictClose: false};\n var not = regexNot.create(pattern, opts);\n var re;\n\n if (typeof include === 'string') {\n re = toRegex('^(?:' + include + '|' + not + ')', opts);\n } else {\n re = toRegex(not, opts);\n }\n\n return (cached = re);\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/expand-brackets/lib/utils.js?"); + +/***/ }), + +/***/ "./node_modules/extend-shallow/index.js": +/*!**********************************************!*\ + !*** ./node_modules/extend-shallow/index.js ***! + \**********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar isObject = __webpack_require__(/*! is-extendable */ \"./node_modules/is-extendable/index.js\");\n\nmodule.exports = function extend(o/*, objects*/) {\n if (!isObject(o)) { o = {}; }\n\n var len = arguments.length;\n for (var i = 1; i < len; i++) {\n var obj = arguments[i];\n\n if (isObject(obj)) {\n assign(o, obj);\n }\n }\n return o;\n};\n\nfunction assign(a, b) {\n for (var key in b) {\n if (hasOwn(b, key)) {\n a[key] = b[key];\n }\n }\n}\n\n/**\n * Returns true if the given `key` is an own property of `obj`.\n */\n\nfunction hasOwn(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/extend-shallow/index.js?"); + +/***/ }), + +/***/ "./node_modules/extglob/index.js": +/*!***************************************!*\ + !*** ./node_modules/extglob/index.js ***! + \***************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\n/**\n * Module dependencies\n */\n\nvar extend = __webpack_require__(/*! extend-shallow */ \"./node_modules/extend-shallow/index.js\");\nvar unique = __webpack_require__(/*! array-unique */ \"./node_modules/array-unique/index.js\");\nvar toRegex = __webpack_require__(/*! to-regex */ \"./node_modules/to-regex/index.js\");\n\n/**\n * Local dependencies\n */\n\nvar compilers = __webpack_require__(/*! ./lib/compilers */ \"./node_modules/extglob/lib/compilers.js\");\nvar parsers = __webpack_require__(/*! ./lib/parsers */ \"./node_modules/extglob/lib/parsers.js\");\nvar Extglob = __webpack_require__(/*! ./lib/extglob */ \"./node_modules/extglob/lib/extglob.js\");\nvar utils = __webpack_require__(/*! ./lib/utils */ \"./node_modules/extglob/lib/utils.js\");\nvar MAX_LENGTH = 1024 * 64;\n\n/**\n * Convert the given `extglob` pattern into a regex-compatible string. Returns\n * an object with the compiled result and the parsed AST.\n *\n * ```js\n * var extglob = require('extglob');\n * console.log(extglob('*.!(*a)'));\n * //=> '(?!\\\\.)[^/]*?\\\\.(?!(?!\\\\.)[^/]*?a\\\\b).*?'\n * ```\n * @param {String} `pattern`\n * @param {Object} `options`\n * @return {String}\n * @api public\n */\n\nfunction extglob(pattern, options) {\n return extglob.create(pattern, options).output;\n}\n\n/**\n * Takes an array of strings and an extglob pattern and returns a new\n * array that contains only the strings that match the pattern.\n *\n * ```js\n * var extglob = require('extglob');\n * console.log(extglob.match(['a.a', 'a.b', 'a.c'], '*.!(*a)'));\n * //=> ['a.b', 'a.c']\n * ```\n * @param {Array} `list` Array of strings to match\n * @param {String} `pattern` Extglob pattern\n * @param {Object} `options`\n * @return {Array} Returns an array of matches\n * @api public\n */\n\nextglob.match = function(list, pattern, options) {\n if (typeof pattern !== 'string') {\n throw new TypeError('expected pattern to be a string');\n }\n\n list = utils.arrayify(list);\n var isMatch = extglob.matcher(pattern, options);\n var len = list.length;\n var idx = -1;\n var matches = [];\n\n while (++idx < len) {\n var ele = list[idx];\n\n if (isMatch(ele)) {\n matches.push(ele);\n }\n }\n\n // if no options were passed, uniquify results and return\n if (typeof options === 'undefined') {\n return unique(matches);\n }\n\n if (matches.length === 0) {\n if (options.failglob === true) {\n throw new Error('no matches found for \"' + pattern + '\"');\n }\n if (options.nonull === true || options.nullglob === true) {\n return [pattern.split('\\\\').join('')];\n }\n }\n\n return options.nodupes !== false ? unique(matches) : matches;\n};\n\n/**\n * Returns true if the specified `string` matches the given\n * extglob `pattern`.\n *\n * ```js\n * var extglob = require('extglob');\n *\n * console.log(extglob.isMatch('a.a', '*.!(*a)'));\n * //=> false\n * console.log(extglob.isMatch('a.b', '*.!(*a)'));\n * //=> true\n * ```\n * @param {String} `string` String to match\n * @param {String} `pattern` Extglob pattern\n * @param {String} `options`\n * @return {Boolean}\n * @api public\n */\n\nextglob.isMatch = function(str, pattern, options) {\n if (typeof pattern !== 'string') {\n throw new TypeError('expected pattern to be a string');\n }\n\n if (typeof str !== 'string') {\n throw new TypeError('expected a string');\n }\n\n if (pattern === str) {\n return true;\n }\n\n if (pattern === '' || pattern === ' ' || pattern === '.') {\n return pattern === str;\n }\n\n var isMatch = utils.memoize('isMatch', pattern, options, extglob.matcher);\n return isMatch(str);\n};\n\n/**\n * Returns true if the given `string` contains the given pattern. Similar to `.isMatch` but\n * the pattern can match any part of the string.\n *\n * ```js\n * var extglob = require('extglob');\n * console.log(extglob.contains('aa/bb/cc', '*b'));\n * //=> true\n * console.log(extglob.contains('aa/bb/cc', '*d'));\n * //=> false\n * ```\n * @param {String} `str` The string to match.\n * @param {String} `pattern` Glob pattern to use for matching.\n * @param {Object} `options`\n * @return {Boolean} Returns true if the patter matches any part of `str`.\n * @api public\n */\n\nextglob.contains = function(str, pattern, options) {\n if (typeof str !== 'string') {\n throw new TypeError('expected a string');\n }\n\n if (pattern === '' || pattern === ' ' || pattern === '.') {\n return pattern === str;\n }\n\n var opts = extend({}, options, {contains: true});\n opts.strictClose = false;\n opts.strictOpen = false;\n return extglob.isMatch(str, pattern, opts);\n};\n\n/**\n * Takes an extglob pattern and returns a matcher function. The returned\n * function takes the string to match as its only argument.\n *\n * ```js\n * var extglob = require('extglob');\n * var isMatch = extglob.matcher('*.!(*a)');\n *\n * console.log(isMatch('a.a'));\n * //=> false\n * console.log(isMatch('a.b'));\n * //=> true\n * ```\n * @param {String} `pattern` Extglob pattern\n * @param {String} `options`\n * @return {Boolean}\n * @api public\n */\n\nextglob.matcher = function(pattern, options) {\n if (typeof pattern !== 'string') {\n throw new TypeError('expected pattern to be a string');\n }\n\n function matcher() {\n var re = extglob.makeRe(pattern, options);\n return function(str) {\n return re.test(str);\n };\n }\n\n return utils.memoize('matcher', pattern, options, matcher);\n};\n\n/**\n * Convert the given `extglob` pattern into a regex-compatible string. Returns\n * an object with the compiled result and the parsed AST.\n *\n * ```js\n * var extglob = require('extglob');\n * console.log(extglob.create('*.!(*a)').output);\n * //=> '(?!\\\\.)[^/]*?\\\\.(?!(?!\\\\.)[^/]*?a\\\\b).*?'\n * ```\n * @param {String} `str`\n * @param {Object} `options`\n * @return {String}\n * @api public\n */\n\nextglob.create = function(pattern, options) {\n if (typeof pattern !== 'string') {\n throw new TypeError('expected pattern to be a string');\n }\n\n function create() {\n var ext = new Extglob(options);\n var ast = ext.parse(pattern, options);\n return ext.compile(ast, options);\n }\n\n return utils.memoize('create', pattern, options, create);\n};\n\n/**\n * Returns an array of matches captured by `pattern` in `string`, or `null`\n * if the pattern did not match.\n *\n * ```js\n * var extglob = require('extglob');\n * extglob.capture(pattern, string[, options]);\n *\n * console.log(extglob.capture('test/*.js', 'test/foo.js'));\n * //=> ['foo']\n * console.log(extglob.capture('test/*.js', 'foo/bar.css'));\n * //=> null\n * ```\n * @param {String} `pattern` Glob pattern to use for matching.\n * @param {String} `string` String to match\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`.\n * @api public\n */\n\nextglob.capture = function(pattern, str, options) {\n var re = extglob.makeRe(pattern, extend({capture: true}, options));\n\n function match() {\n return function(string) {\n var match = re.exec(string);\n if (!match) {\n return null;\n }\n\n return match.slice(1);\n };\n }\n\n var capture = utils.memoize('capture', pattern, options, match);\n return capture(str);\n};\n\n/**\n * Create a regular expression from the given `pattern` and `options`.\n *\n * ```js\n * var extglob = require('extglob');\n * var re = extglob.makeRe('*.!(*a)');\n * console.log(re);\n * //=> /^[^\\/]*?\\.(?![^\\/]*?a)[^\\/]*?$/\n * ```\n * @param {String} `pattern` The pattern to convert to regex.\n * @param {Object} `options`\n * @return {RegExp}\n * @api public\n */\n\nextglob.makeRe = function(pattern, options) {\n if (pattern instanceof RegExp) {\n return pattern;\n }\n\n if (typeof pattern !== 'string') {\n throw new TypeError('expected pattern to be a string');\n }\n\n if (pattern.length > MAX_LENGTH) {\n throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters');\n }\n\n function makeRe() {\n var opts = extend({strictErrors: false}, options);\n if (opts.strictErrors === true) opts.strict = true;\n var res = extglob.create(pattern, opts);\n return toRegex(res.output, opts);\n }\n\n var regex = utils.memoize('makeRe', pattern, options, makeRe);\n if (regex.source.length > MAX_LENGTH) {\n throw new SyntaxError('potentially malicious regex detected');\n }\n\n return regex;\n};\n\n/**\n * Cache\n */\n\nextglob.cache = utils.cache;\nextglob.clearCache = function() {\n extglob.cache.__data__ = {};\n};\n\n/**\n * Expose `Extglob` constructor, parsers and compilers\n */\n\nextglob.Extglob = Extglob;\nextglob.compilers = compilers;\nextglob.parsers = parsers;\n\n/**\n * Expose `extglob`\n * @type {Function}\n */\n\nmodule.exports = extglob;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/extglob/index.js?"); + +/***/ }), + +/***/ "./node_modules/extglob/lib/compilers.js": +/*!***********************************************!*\ + !*** ./node_modules/extglob/lib/compilers.js ***! + \***********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar brackets = __webpack_require__(/*! expand-brackets */ \"./node_modules/expand-brackets/index.js\");\n\n/**\n * Extglob compilers\n */\n\nmodule.exports = function(extglob) {\n function star() {\n if (typeof extglob.options.star === 'function') {\n return extglob.options.star.apply(this, arguments);\n }\n if (typeof extglob.options.star === 'string') {\n return extglob.options.star;\n }\n return '.*?';\n }\n\n /**\n * Use `expand-brackets` compilers\n */\n\n extglob.use(brackets.compilers);\n extglob.compiler\n\n /**\n * Escaped: \"\\\\*\"\n */\n\n .set('escape', function(node) {\n return this.emit(node.val, node);\n })\n\n /**\n * Dot: \".\"\n */\n\n .set('dot', function(node) {\n return this.emit('\\\\' + node.val, node);\n })\n\n /**\n * Question mark: \"?\"\n */\n\n .set('qmark', function(node) {\n var val = '[^\\\\\\\\/.]';\n var prev = this.prev();\n\n if (node.parsed.slice(-1) === '(') {\n var ch = node.rest.charAt(0);\n if (ch !== '!' && ch !== '=' && ch !== ':') {\n return this.emit(val, node);\n }\n return this.emit(node.val, node);\n }\n\n if (prev.type === 'text' && prev.val) {\n return this.emit(val, node);\n }\n\n if (node.val.length > 1) {\n val += '{' + node.val.length + '}';\n }\n return this.emit(val, node);\n })\n\n /**\n * Plus: \"+\"\n */\n\n .set('plus', function(node) {\n var prev = node.parsed.slice(-1);\n if (prev === ']' || prev === ')') {\n return this.emit(node.val, node);\n }\n var ch = this.output.slice(-1);\n if (!this.output || (/[?*+]/.test(ch) && node.parent.type !== 'bracket')) {\n return this.emit('\\\\+', node);\n }\n if (/\\w/.test(ch) && !node.inside) {\n return this.emit('+\\\\+?', node);\n }\n return this.emit('+', node);\n })\n\n /**\n * Star: \"*\"\n */\n\n .set('star', function(node) {\n var prev = this.prev();\n var prefix = prev.type !== 'text' && prev.type !== 'escape'\n ? '(?!\\\\.)'\n : '';\n\n return this.emit(prefix + star.call(this, node), node);\n })\n\n /**\n * Parens\n */\n\n .set('paren', function(node) {\n return this.mapVisit(node.nodes);\n })\n .set('paren.open', function(node) {\n var capture = this.options.capture ? '(' : '';\n\n switch (node.parent.prefix) {\n case '!':\n case '^':\n return this.emit(capture + '(?:(?!(?:', node);\n case '*':\n case '+':\n case '?':\n case '@':\n return this.emit(capture + '(?:', node);\n default: {\n var val = node.val;\n if (this.options.bash === true) {\n val = '\\\\' + val;\n } else if (!this.options.capture && val === '(' && node.parent.rest[0] !== '?') {\n val += '?:';\n }\n\n return this.emit(val, node);\n }\n }\n })\n .set('paren.close', function(node) {\n var capture = this.options.capture ? ')' : '';\n\n switch (node.prefix) {\n case '!':\n case '^':\n var prefix = /^(\\)|$)/.test(node.rest) ? '$' : '';\n var str = star.call(this, node);\n\n // if the extglob has a slash explicitly defined, we know the user wants\n // to match slashes, so we need to ensure the \"star\" regex allows for it\n if (node.parent.hasSlash && !this.options.star && this.options.slash !== false) {\n str = '.*?';\n }\n\n return this.emit(prefix + ('))' + str + ')') + capture, node);\n case '*':\n case '+':\n case '?':\n return this.emit(')' + node.prefix + capture, node);\n case '@':\n return this.emit(')' + capture, node);\n default: {\n var val = (this.options.bash === true ? '\\\\' : '') + ')';\n return this.emit(val, node);\n }\n }\n })\n\n /**\n * Text\n */\n\n .set('text', function(node) {\n var val = node.val.replace(/[\\[\\]]/g, '\\\\$&');\n return this.emit(val, node);\n });\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/extglob/lib/compilers.js?"); + +/***/ }), + +/***/ "./node_modules/extglob/lib/extglob.js": +/*!*********************************************!*\ + !*** ./node_modules/extglob/lib/extglob.js ***! + \*********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\n/**\n * Module dependencies\n */\n\nvar Snapdragon = __webpack_require__(/*! snapdragon */ \"./node_modules/snapdragon/index.js\");\nvar define = __webpack_require__(/*! define-property */ \"./node_modules/extglob/node_modules/define-property/index.js\");\nvar extend = __webpack_require__(/*! extend-shallow */ \"./node_modules/extend-shallow/index.js\");\n\n/**\n * Local dependencies\n */\n\nvar compilers = __webpack_require__(/*! ./compilers */ \"./node_modules/extglob/lib/compilers.js\");\nvar parsers = __webpack_require__(/*! ./parsers */ \"./node_modules/extglob/lib/parsers.js\");\n\n/**\n * Customize Snapdragon parser and renderer\n */\n\nfunction Extglob(options) {\n this.options = extend({source: 'extglob'}, options);\n this.snapdragon = this.options.snapdragon || new Snapdragon(this.options);\n this.snapdragon.patterns = this.snapdragon.patterns || {};\n this.compiler = this.snapdragon.compiler;\n this.parser = this.snapdragon.parser;\n\n compilers(this.snapdragon);\n parsers(this.snapdragon);\n\n /**\n * Override Snapdragon `.parse` method\n */\n\n define(this.snapdragon, 'parse', function(str, options) {\n var parsed = Snapdragon.prototype.parse.apply(this, arguments);\n parsed.input = str;\n\n // escape unmatched brace/bracket/parens\n var last = this.parser.stack.pop();\n if (last && this.options.strict !== true) {\n var node = last.nodes[0];\n node.val = '\\\\' + node.val;\n var sibling = node.parent.nodes[1];\n if (sibling.type === 'star') {\n sibling.loose = true;\n }\n }\n\n // add non-enumerable parser reference\n define(parsed, 'parser', this.parser);\n return parsed;\n });\n\n /**\n * Decorate `.parse` method\n */\n\n define(this, 'parse', function(ast, options) {\n return this.snapdragon.parse.apply(this.snapdragon, arguments);\n });\n\n /**\n * Decorate `.compile` method\n */\n\n define(this, 'compile', function(ast, options) {\n return this.snapdragon.compile.apply(this.snapdragon, arguments);\n });\n\n}\n\n/**\n * Expose `Extglob`\n */\n\nmodule.exports = Extglob;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/extglob/lib/extglob.js?"); + +/***/ }), + +/***/ "./node_modules/extglob/lib/parsers.js": +/*!*********************************************!*\ + !*** ./node_modules/extglob/lib/parsers.js ***! + \*********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar brackets = __webpack_require__(/*! expand-brackets */ \"./node_modules/expand-brackets/index.js\");\nvar define = __webpack_require__(/*! define-property */ \"./node_modules/extglob/node_modules/define-property/index.js\");\nvar utils = __webpack_require__(/*! ./utils */ \"./node_modules/extglob/lib/utils.js\");\n\n/**\n * Characters to use in text regex (we want to \"not\" match\n * characters that are matched by other parsers)\n */\n\nvar TEXT_REGEX = '([!@*?+]?\\\\(|\\\\)|[*?.+\\\\\\\\]|\\\\[:?(?=.*\\\\])|:?\\\\])+';\nvar not = utils.createRegex(TEXT_REGEX);\n\n/**\n * Extglob parsers\n */\n\nfunction parsers(extglob) {\n extglob.state = extglob.state || {};\n\n /**\n * Use `expand-brackets` parsers\n */\n\n extglob.use(brackets.parsers);\n extglob.parser.sets.paren = extglob.parser.sets.paren || [];\n extglob.parser\n\n /**\n * Extglob open: \"*(\"\n */\n\n .capture('paren.open', function() {\n var parsed = this.parsed;\n var pos = this.position();\n var m = this.match(/^([!@*?+])?\\(/);\n if (!m) return;\n\n var prev = this.prev();\n var prefix = m[1];\n var val = m[0];\n\n var open = pos({\n type: 'paren.open',\n parsed: parsed,\n val: val\n });\n\n var node = pos({\n type: 'paren',\n prefix: prefix,\n nodes: [open]\n });\n\n // if nested negation extglobs, just cancel them out to simplify\n if (prefix === '!' && prev.type === 'paren' && prev.prefix === '!') {\n prev.prefix = '@';\n node.prefix = '@';\n }\n\n define(node, 'rest', this.input);\n define(node, 'parsed', parsed);\n define(node, 'parent', prev);\n define(open, 'parent', node);\n\n this.push('paren', node);\n prev.nodes.push(node);\n })\n\n /**\n * Extglob close: \")\"\n */\n\n .capture('paren.close', function() {\n var parsed = this.parsed;\n var pos = this.position();\n var m = this.match(/^\\)/);\n if (!m) return;\n\n var parent = this.pop('paren');\n var node = pos({\n type: 'paren.close',\n rest: this.input,\n parsed: parsed,\n val: m[0]\n });\n\n if (!this.isType(parent, 'paren')) {\n if (this.options.strict) {\n throw new Error('missing opening paren: \"(\"');\n }\n node.escaped = true;\n return node;\n }\n\n node.prefix = parent.prefix;\n parent.nodes.push(node);\n define(node, 'parent', parent);\n })\n\n /**\n * Escape: \"\\\\.\"\n */\n\n .capture('escape', function() {\n var pos = this.position();\n var m = this.match(/^\\\\(.)/);\n if (!m) return;\n\n return pos({\n type: 'escape',\n val: m[0],\n ch: m[1]\n });\n })\n\n /**\n * Question marks: \"?\"\n */\n\n .capture('qmark', function() {\n var parsed = this.parsed;\n var pos = this.position();\n var m = this.match(/^\\?+(?!\\()/);\n if (!m) return;\n extglob.state.metachar = true;\n return pos({\n type: 'qmark',\n rest: this.input,\n parsed: parsed,\n val: m[0]\n });\n })\n\n /**\n * Character parsers\n */\n\n .capture('star', /^\\*(?!\\()/)\n .capture('plus', /^\\+(?!\\()/)\n .capture('dot', /^\\./)\n .capture('text', not);\n};\n\n/**\n * Expose text regex string\n */\n\nmodule.exports.TEXT_REGEX = TEXT_REGEX;\n\n/**\n * Extglob parsers\n */\n\nmodule.exports = parsers;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/extglob/lib/parsers.js?"); + +/***/ }), + +/***/ "./node_modules/extglob/lib/utils.js": +/*!*******************************************!*\ + !*** ./node_modules/extglob/lib/utils.js ***! + \*******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar regex = __webpack_require__(/*! regex-not */ \"./node_modules/regex-not/index.js\");\nvar Cache = __webpack_require__(/*! fragment-cache */ \"./node_modules/fragment-cache/index.js\");\n\n/**\n * Utils\n */\n\nvar utils = module.exports;\nvar cache = utils.cache = new Cache();\n\n/**\n * Cast `val` to an array\n * @return {Array}\n */\n\nutils.arrayify = function(val) {\n if (!Array.isArray(val)) {\n return [val];\n }\n return val;\n};\n\n/**\n * Memoize a generated regex or function\n */\n\nutils.memoize = function(type, pattern, options, fn) {\n var key = utils.createKey(type + pattern, options);\n\n if (cache.has(type, key)) {\n return cache.get(type, key);\n }\n\n var val = fn(pattern, options);\n if (options && options.cache === false) {\n return val;\n }\n\n cache.set(type, key, val);\n return val;\n};\n\n/**\n * Create the key to use for memoization. The key is generated\n * by iterating over the options and concatenating key-value pairs\n * to the pattern string.\n */\n\nutils.createKey = function(pattern, options) {\n var key = pattern;\n if (typeof options === 'undefined') {\n return key;\n }\n for (var prop in options) {\n key += ';' + prop + '=' + String(options[prop]);\n }\n return key;\n};\n\n/**\n * Create the regex to use for matching text\n */\n\nutils.createRegex = function(str) {\n var opts = {contains: true, strictClose: false};\n return regex(str, opts);\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/extglob/lib/utils.js?"); + +/***/ }), + +/***/ "./node_modules/extglob/node_modules/define-property/index.js": +/*!********************************************************************!*\ + !*** ./node_modules/extglob/node_modules/define-property/index.js ***! + \********************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * define-property \n *\n * Copyright (c) 2015, 2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar isDescriptor = __webpack_require__(/*! is-descriptor */ \"./node_modules/is-descriptor/index.js\");\n\nmodule.exports = function defineProperty(obj, prop, val) {\n if (typeof obj !== 'object' && typeof obj !== 'function') {\n throw new TypeError('expected an object or function.');\n }\n\n if (typeof prop !== 'string') {\n throw new TypeError('expected `prop` to be a string.');\n }\n\n if (isDescriptor(val) && ('set' in val || 'get' in val)) {\n return Object.defineProperty(obj, prop, val);\n }\n\n return Object.defineProperty(obj, prop, {\n configurable: true,\n enumerable: false,\n writable: true,\n value: val\n });\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/extglob/node_modules/define-property/index.js?"); + +/***/ }), + +/***/ "./node_modules/fill-range/index.js": +/*!******************************************!*\ + !*** ./node_modules/fill-range/index.js ***! + \******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * fill-range \n *\n * Copyright (c) 2014-2015, 2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar util = __webpack_require__(/*! util */ \"util\");\nvar isNumber = __webpack_require__(/*! is-number */ \"./node_modules/is-number/index.js\");\nvar extend = __webpack_require__(/*! extend-shallow */ \"./node_modules/extend-shallow/index.js\");\nvar repeat = __webpack_require__(/*! repeat-string */ \"./node_modules/repeat-string/index.js\");\nvar toRegex = __webpack_require__(/*! to-regex-range */ \"./node_modules/to-regex-range/index.js\");\n\n/**\n * Return a range of numbers or letters.\n *\n * @param {String} `start` Start of the range\n * @param {String} `stop` End of the range\n * @param {String} `step` Increment or decrement to use.\n * @param {Function} `fn` Custom function to modify each element in the range.\n * @return {Array}\n */\n\nfunction fillRange(start, stop, step, options) {\n if (typeof start === 'undefined') {\n return [];\n }\n\n if (typeof stop === 'undefined' || start === stop) {\n // special case, for handling negative zero\n var isString = typeof start === 'string';\n if (isNumber(start) && !toNumber(start)) {\n return [isString ? '0' : 0];\n }\n return [start];\n }\n\n if (typeof step !== 'number' && typeof step !== 'string') {\n options = step;\n step = undefined;\n }\n\n if (typeof options === 'function') {\n options = { transform: options };\n }\n\n var opts = extend({step: step}, options);\n if (opts.step && !isValidNumber(opts.step)) {\n if (opts.strictRanges === true) {\n throw new TypeError('expected options.step to be a number');\n }\n return [];\n }\n\n opts.isNumber = isValidNumber(start) && isValidNumber(stop);\n if (!opts.isNumber && !isValid(start, stop)) {\n if (opts.strictRanges === true) {\n throw new RangeError('invalid range arguments: ' + util.inspect([start, stop]));\n }\n return [];\n }\n\n opts.isPadded = isPadded(start) || isPadded(stop);\n opts.toString = opts.stringify\n || typeof opts.step === 'string'\n || typeof start === 'string'\n || typeof stop === 'string'\n || !opts.isNumber;\n\n if (opts.isPadded) {\n opts.maxLength = Math.max(String(start).length, String(stop).length);\n }\n\n // support legacy minimatch/fill-range options\n if (typeof opts.optimize === 'boolean') opts.toRegex = opts.optimize;\n if (typeof opts.makeRe === 'boolean') opts.toRegex = opts.makeRe;\n return expand(start, stop, opts);\n}\n\nfunction expand(start, stop, options) {\n var a = options.isNumber ? toNumber(start) : start.charCodeAt(0);\n var b = options.isNumber ? toNumber(stop) : stop.charCodeAt(0);\n\n var step = Math.abs(toNumber(options.step)) || 1;\n if (options.toRegex && step === 1) {\n return toRange(a, b, start, stop, options);\n }\n\n var zero = {greater: [], lesser: []};\n var asc = a < b;\n var arr = new Array(Math.round((asc ? b - a : a - b) / step));\n var idx = 0;\n\n while (asc ? a <= b : a >= b) {\n var val = options.isNumber ? a : String.fromCharCode(a);\n if (options.toRegex && (val >= 0 || !options.isNumber)) {\n zero.greater.push(val);\n } else {\n zero.lesser.push(Math.abs(val));\n }\n\n if (options.isPadded) {\n val = zeros(val, options);\n }\n\n if (options.toString) {\n val = String(val);\n }\n\n if (typeof options.transform === 'function') {\n arr[idx++] = options.transform(val, a, b, step, idx, arr, options);\n } else {\n arr[idx++] = val;\n }\n\n if (asc) {\n a += step;\n } else {\n a -= step;\n }\n }\n\n if (options.toRegex === true) {\n return toSequence(arr, zero, options);\n }\n return arr;\n}\n\nfunction toRange(a, b, start, stop, options) {\n if (options.isPadded) {\n return toRegex(start, stop, options);\n }\n\n if (options.isNumber) {\n return toRegex(Math.min(a, b), Math.max(a, b), options);\n }\n\n var start = String.fromCharCode(Math.min(a, b));\n var stop = String.fromCharCode(Math.max(a, b));\n return '[' + start + '-' + stop + ']';\n}\n\nfunction toSequence(arr, zeros, options) {\n var greater = '', lesser = '';\n if (zeros.greater.length) {\n greater = zeros.greater.join('|');\n }\n if (zeros.lesser.length) {\n lesser = '-(' + zeros.lesser.join('|') + ')';\n }\n var res = greater && lesser\n ? greater + '|' + lesser\n : greater || lesser;\n\n if (options.capture) {\n return '(' + res + ')';\n }\n return res;\n}\n\nfunction zeros(val, options) {\n if (options.isPadded) {\n var str = String(val);\n var len = str.length;\n var dash = '';\n if (str.charAt(0) === '-') {\n dash = '-';\n str = str.slice(1);\n }\n var diff = options.maxLength - len;\n var pad = repeat('0', diff);\n val = (dash + pad + str);\n }\n if (options.stringify) {\n return String(val);\n }\n return val;\n}\n\nfunction toNumber(val) {\n return Number(val) || 0;\n}\n\nfunction isPadded(str) {\n return /^-?0\\d/.test(str);\n}\n\nfunction isValid(min, max) {\n return (isValidNumber(min) || isValidLetter(min))\n && (isValidNumber(max) || isValidLetter(max));\n}\n\nfunction isValidLetter(ch) {\n return typeof ch === 'string' && ch.length === 1 && /^\\w+$/.test(ch);\n}\n\nfunction isValidNumber(n) {\n return isNumber(n) && !/\\./.test(n);\n}\n\n/**\n * Expose `fillRange`\n * @type {Function}\n */\n\nmodule.exports = fillRange;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/fill-range/index.js?"); + +/***/ }), + +/***/ "./node_modules/for-in/index.js": +/*!**************************************!*\ + !*** ./node_modules/for-in/index.js ***! + \**************************************/ +/***/ ((module) => { + +"use strict"; +eval("/*!\n * for-in \n *\n * Copyright (c) 2014-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nmodule.exports = function forIn(obj, fn, thisArg) {\n for (var key in obj) {\n if (fn.call(thisArg, obj[key], key, obj) === false) {\n break;\n }\n }\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/for-in/index.js?"); + +/***/ }), + +/***/ "./node_modules/fragment-cache/index.js": +/*!**********************************************!*\ + !*** ./node_modules/fragment-cache/index.js ***! + \**********************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * fragment-cache \n *\n * Copyright (c) 2016-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar MapCache = __webpack_require__(/*! map-cache */ \"./node_modules/map-cache/index.js\");\n\n/**\n * Create a new `FragmentCache` with an optional object to use for `caches`.\n *\n * ```js\n * var fragment = new FragmentCache();\n * ```\n * @name FragmentCache\n * @param {String} `cacheName`\n * @return {Object} Returns the [map-cache][] instance.\n * @api public\n */\n\nfunction FragmentCache(caches) {\n this.caches = caches || {};\n}\n\n/**\n * Prototype\n */\n\nFragmentCache.prototype = {\n\n /**\n * Get cache `name` from the `fragment.caches` object. Creates a new\n * `MapCache` if it doesn't already exist.\n *\n * ```js\n * var cache = fragment.cache('files');\n * console.log(fragment.caches.hasOwnProperty('files'));\n * //=> true\n * ```\n * @name .cache\n * @param {String} `cacheName`\n * @return {Object} Returns the [map-cache][] instance.\n * @api public\n */\n\n cache: function(cacheName) {\n return this.caches[cacheName] || (this.caches[cacheName] = new MapCache());\n },\n\n /**\n * Set a value for property `key` on cache `name`\n *\n * ```js\n * fragment.set('files', 'somefile.js', new File({path: 'somefile.js'}));\n * ```\n * @name .set\n * @param {String} `name`\n * @param {String} `key` Property name to set\n * @param {any} `val` The value of `key`\n * @return {Object} The cache instance for chaining\n * @api public\n */\n\n set: function(cacheName, key, val) {\n var cache = this.cache(cacheName);\n cache.set(key, val);\n return cache;\n },\n\n /**\n * Returns true if a non-undefined value is set for `key` on fragment cache `name`.\n *\n * ```js\n * var cache = fragment.cache('files');\n * cache.set('somefile.js');\n *\n * console.log(cache.has('somefile.js'));\n * //=> true\n *\n * console.log(cache.has('some-other-file.js'));\n * //=> false\n * ```\n * @name .has\n * @param {String} `name` Cache name\n * @param {String} `key` Optionally specify a property to check for on cache `name`\n * @return {Boolean}\n * @api public\n */\n\n has: function(cacheName, key) {\n return typeof this.get(cacheName, key) !== 'undefined';\n },\n\n /**\n * Get `name`, or if specified, the value of `key`. Invokes the [cache]() method,\n * so that cache `name` will be created it doesn't already exist. If `key` is not passed,\n * the entire cache (`name`) is returned.\n *\n * ```js\n * var Vinyl = require('vinyl');\n * var cache = fragment.cache('files');\n * cache.set('somefile.js', new Vinyl({path: 'somefile.js'}));\n * console.log(cache.get('somefile.js'));\n * //=> \n * ```\n * @name .get\n * @param {String} `name`\n * @return {Object} Returns cache `name`, or the value of `key` if specified\n * @api public\n */\n\n get: function(name, key) {\n var cache = this.cache(name);\n if (typeof key === 'string') {\n return cache.get(key);\n }\n return cache;\n }\n};\n\n/**\n * Expose `FragmentCache`\n */\n\nexports = module.exports = FragmentCache;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/fragment-cache/index.js?"); + +/***/ }), + +/***/ "./node_modules/get-value/index.js": +/*!*****************************************!*\ + !*** ./node_modules/get-value/index.js ***! + \*****************************************/ +/***/ ((module) => { + +eval("/*!\n * get-value \n *\n * Copyright (c) 2014-2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\nmodule.exports = function(obj, prop, a, b, c) {\n if (!isObject(obj) || !prop) {\n return obj;\n }\n\n prop = toString(prop);\n\n // allowing for multiple properties to be passed as\n // a string or array, but much faster (3-4x) than doing\n // `[].slice.call(arguments)`\n if (a) prop += '.' + toString(a);\n if (b) prop += '.' + toString(b);\n if (c) prop += '.' + toString(c);\n\n if (prop in obj) {\n return obj[prop];\n }\n\n var segs = prop.split('.');\n var len = segs.length;\n var i = -1;\n\n while (obj && (++i < len)) {\n var key = segs[i];\n while (key[key.length - 1] === '\\\\') {\n key = key.slice(0, -1) + '.' + segs[++i];\n }\n obj = obj[key];\n }\n return obj;\n};\n\nfunction isObject(val) {\n return val !== null && (typeof val === 'object' || typeof val === 'function');\n}\n\nfunction toString(val) {\n if (!val) return '';\n if (Array.isArray(val)) {\n return val.join('.');\n }\n return val;\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/get-value/index.js?"); + +/***/ }), + +/***/ "./node_modules/glob-parent/index.js": +/*!*******************************************!*\ + !*** ./node_modules/glob-parent/index.js ***! + \*******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar isGlob = __webpack_require__(/*! is-glob */ \"./node_modules/is-glob/index.js\");\nvar pathPosixDirname = __webpack_require__(/*! path */ \"path\").posix.dirname;\nvar isWin32 = __webpack_require__(/*! os */ \"os\").platform() === 'win32';\n\nvar slash = '/';\nvar backslash = /\\\\/g;\nvar enclosure = /[\\{\\[].*[\\}\\]]$/;\nvar globby = /(^|[^\\\\])([\\{\\[]|\\([^\\)]+$)/;\nvar escaped = /\\\\([\\!\\*\\?\\|\\[\\]\\(\\)\\{\\}])/g;\n\n/**\n * @param {string} str\n * @param {Object} opts\n * @param {boolean} [opts.flipBackslashes=true]\n * @returns {string}\n */\nmodule.exports = function globParent(str, opts) {\n var options = Object.assign({ flipBackslashes: true }, opts);\n\n // flip windows path separators\n if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {\n str = str.replace(backslash, slash);\n }\n\n // special case for strings ending in enclosure containing path separator\n if (enclosure.test(str)) {\n str += slash;\n }\n\n // preserves full path in case of trailing path separator\n str += 'a';\n\n // remove path parts that are globby\n do {\n str = pathPosixDirname(str);\n } while (isGlob(str) || globby.test(str));\n\n // remove escape chars and return result\n return str.replace(escaped, '$1');\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/glob-parent/index.js?"); + +/***/ }), + +/***/ "./node_modules/graceful-fs/clone.js": +/*!*******************************************!*\ + !*** ./node_modules/graceful-fs/clone.js ***! + \*******************************************/ +/***/ ((module) => { + +"use strict"; +eval("\n\nmodule.exports = clone\n\nvar getPrototypeOf = Object.getPrototypeOf || function (obj) {\n return obj.__proto__\n}\n\nfunction clone (obj) {\n if (obj === null || typeof obj !== 'object')\n return obj\n\n if (obj instanceof Object)\n var copy = { __proto__: getPrototypeOf(obj) }\n else\n var copy = Object.create(null)\n\n Object.getOwnPropertyNames(obj).forEach(function (key) {\n Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key))\n })\n\n return copy\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/graceful-fs/clone.js?"); + +/***/ }), + +/***/ "./node_modules/graceful-fs/graceful-fs.js": +/*!*************************************************!*\ + !*** ./node_modules/graceful-fs/graceful-fs.js ***! + \*************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var fs = __webpack_require__(/*! fs */ \"fs\")\nvar polyfills = __webpack_require__(/*! ./polyfills.js */ \"./node_modules/graceful-fs/polyfills.js\")\nvar legacy = __webpack_require__(/*! ./legacy-streams.js */ \"./node_modules/graceful-fs/legacy-streams.js\")\nvar clone = __webpack_require__(/*! ./clone.js */ \"./node_modules/graceful-fs/clone.js\")\n\nvar util = __webpack_require__(/*! util */ \"util\")\n\n/* istanbul ignore next - node 0.x polyfill */\nvar gracefulQueue\nvar previousSymbol\n\n/* istanbul ignore else - node 0.x polyfill */\nif (typeof Symbol === 'function' && typeof Symbol.for === 'function') {\n gracefulQueue = Symbol.for('graceful-fs.queue')\n // This is used in testing by future versions\n previousSymbol = Symbol.for('graceful-fs.previous')\n} else {\n gracefulQueue = '___graceful-fs.queue'\n previousSymbol = '___graceful-fs.previous'\n}\n\nfunction noop () {}\n\nfunction publishQueue(context, queue) {\n Object.defineProperty(context, gracefulQueue, {\n get: function() {\n return queue\n }\n })\n}\n\nvar debug = noop\nif (util.debuglog)\n debug = util.debuglog('gfs4')\nelse if (/\\bgfs4\\b/i.test(process.env.NODE_DEBUG || ''))\n debug = function() {\n var m = util.format.apply(util, arguments)\n m = 'GFS4: ' + m.split(/\\n/).join('\\nGFS4: ')\n console.error(m)\n }\n\n// Once time initialization\nif (!fs[gracefulQueue]) {\n // This queue can be shared by multiple loaded instances\n var queue = global[gracefulQueue] || []\n publishQueue(fs, queue)\n\n // Patch fs.close/closeSync to shared queue version, because we need\n // to retry() whenever a close happens *anywhere* in the program.\n // This is essential when multiple graceful-fs instances are\n // in play at the same time.\n fs.close = (function (fs$close) {\n function close (fd, cb) {\n return fs$close.call(fs, fd, function (err) {\n // This function uses the graceful-fs shared queue\n if (!err) {\n resetQueue()\n }\n\n if (typeof cb === 'function')\n cb.apply(this, arguments)\n })\n }\n\n Object.defineProperty(close, previousSymbol, {\n value: fs$close\n })\n return close\n })(fs.close)\n\n fs.closeSync = (function (fs$closeSync) {\n function closeSync (fd) {\n // This function uses the graceful-fs shared queue\n fs$closeSync.apply(fs, arguments)\n resetQueue()\n }\n\n Object.defineProperty(closeSync, previousSymbol, {\n value: fs$closeSync\n })\n return closeSync\n })(fs.closeSync)\n\n if (/\\bgfs4\\b/i.test(process.env.NODE_DEBUG || '')) {\n process.on('exit', function() {\n debug(fs[gracefulQueue])\n __webpack_require__(/*! assert */ \"assert\").equal(fs[gracefulQueue].length, 0)\n })\n }\n}\n\nif (!global[gracefulQueue]) {\n publishQueue(global, fs[gracefulQueue]);\n}\n\nmodule.exports = patch(clone(fs))\nif (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {\n module.exports = patch(fs)\n fs.__patched = true;\n}\n\nfunction patch (fs) {\n // Everything that references the open() function needs to be in here\n polyfills(fs)\n fs.gracefulify = patch\n\n fs.createReadStream = createReadStream\n fs.createWriteStream = createWriteStream\n var fs$readFile = fs.readFile\n fs.readFile = readFile\n function readFile (path, options, cb) {\n if (typeof options === 'function')\n cb = options, options = null\n\n return go$readFile(path, options, cb)\n\n function go$readFile (path, options, cb, startTime) {\n return fs$readFile(path, options, function (err) {\n if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))\n enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()])\n else {\n if (typeof cb === 'function')\n cb.apply(this, arguments)\n }\n })\n }\n }\n\n var fs$writeFile = fs.writeFile\n fs.writeFile = writeFile\n function writeFile (path, data, options, cb) {\n if (typeof options === 'function')\n cb = options, options = null\n\n return go$writeFile(path, data, options, cb)\n\n function go$writeFile (path, data, options, cb, startTime) {\n return fs$writeFile(path, data, options, function (err) {\n if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))\n enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()])\n else {\n if (typeof cb === 'function')\n cb.apply(this, arguments)\n }\n })\n }\n }\n\n var fs$appendFile = fs.appendFile\n if (fs$appendFile)\n fs.appendFile = appendFile\n function appendFile (path, data, options, cb) {\n if (typeof options === 'function')\n cb = options, options = null\n\n return go$appendFile(path, data, options, cb)\n\n function go$appendFile (path, data, options, cb, startTime) {\n return fs$appendFile(path, data, options, function (err) {\n if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))\n enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()])\n else {\n if (typeof cb === 'function')\n cb.apply(this, arguments)\n }\n })\n }\n }\n\n var fs$copyFile = fs.copyFile\n if (fs$copyFile)\n fs.copyFile = copyFile\n function copyFile (src, dest, flags, cb) {\n if (typeof flags === 'function') {\n cb = flags\n flags = 0\n }\n return go$copyFile(src, dest, flags, cb)\n\n function go$copyFile (src, dest, flags, cb, startTime) {\n return fs$copyFile(src, dest, flags, function (err) {\n if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))\n enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()])\n else {\n if (typeof cb === 'function')\n cb.apply(this, arguments)\n }\n })\n }\n }\n\n var fs$readdir = fs.readdir\n fs.readdir = readdir\n function readdir (path, options, cb) {\n if (typeof options === 'function')\n cb = options, options = null\n\n return go$readdir(path, options, cb)\n\n function go$readdir (path, options, cb, startTime) {\n return fs$readdir(path, options, function (err, files) {\n if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))\n enqueue([go$readdir, [path, options, cb], err, startTime || Date.now(), Date.now()])\n else {\n if (files && files.sort)\n files.sort()\n\n if (typeof cb === 'function')\n cb.call(this, err, files)\n }\n })\n }\n }\n\n if (process.version.substr(0, 4) === 'v0.8') {\n var legStreams = legacy(fs)\n ReadStream = legStreams.ReadStream\n WriteStream = legStreams.WriteStream\n }\n\n var fs$ReadStream = fs.ReadStream\n if (fs$ReadStream) {\n ReadStream.prototype = Object.create(fs$ReadStream.prototype)\n ReadStream.prototype.open = ReadStream$open\n }\n\n var fs$WriteStream = fs.WriteStream\n if (fs$WriteStream) {\n WriteStream.prototype = Object.create(fs$WriteStream.prototype)\n WriteStream.prototype.open = WriteStream$open\n }\n\n Object.defineProperty(fs, 'ReadStream', {\n get: function () {\n return ReadStream\n },\n set: function (val) {\n ReadStream = val\n },\n enumerable: true,\n configurable: true\n })\n Object.defineProperty(fs, 'WriteStream', {\n get: function () {\n return WriteStream\n },\n set: function (val) {\n WriteStream = val\n },\n enumerable: true,\n configurable: true\n })\n\n // legacy names\n var FileReadStream = ReadStream\n Object.defineProperty(fs, 'FileReadStream', {\n get: function () {\n return FileReadStream\n },\n set: function (val) {\n FileReadStream = val\n },\n enumerable: true,\n configurable: true\n })\n var FileWriteStream = WriteStream\n Object.defineProperty(fs, 'FileWriteStream', {\n get: function () {\n return FileWriteStream\n },\n set: function (val) {\n FileWriteStream = val\n },\n enumerable: true,\n configurable: true\n })\n\n function ReadStream (path, options) {\n if (this instanceof ReadStream)\n return fs$ReadStream.apply(this, arguments), this\n else\n return ReadStream.apply(Object.create(ReadStream.prototype), arguments)\n }\n\n function ReadStream$open () {\n var that = this\n open(that.path, that.flags, that.mode, function (err, fd) {\n if (err) {\n if (that.autoClose)\n that.destroy()\n\n that.emit('error', err)\n } else {\n that.fd = fd\n that.emit('open', fd)\n that.read()\n }\n })\n }\n\n function WriteStream (path, options) {\n if (this instanceof WriteStream)\n return fs$WriteStream.apply(this, arguments), this\n else\n return WriteStream.apply(Object.create(WriteStream.prototype), arguments)\n }\n\n function WriteStream$open () {\n var that = this\n open(that.path, that.flags, that.mode, function (err, fd) {\n if (err) {\n that.destroy()\n that.emit('error', err)\n } else {\n that.fd = fd\n that.emit('open', fd)\n }\n })\n }\n\n function createReadStream (path, options) {\n return new fs.ReadStream(path, options)\n }\n\n function createWriteStream (path, options) {\n return new fs.WriteStream(path, options)\n }\n\n var fs$open = fs.open\n fs.open = open\n function open (path, flags, mode, cb) {\n if (typeof mode === 'function')\n cb = mode, mode = null\n\n return go$open(path, flags, mode, cb)\n\n function go$open (path, flags, mode, cb, startTime) {\n return fs$open(path, flags, mode, function (err, fd) {\n if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))\n enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()])\n else {\n if (typeof cb === 'function')\n cb.apply(this, arguments)\n }\n })\n }\n }\n\n return fs\n}\n\nfunction enqueue (elem) {\n debug('ENQUEUE', elem[0].name, elem[1])\n fs[gracefulQueue].push(elem)\n retry()\n}\n\n// keep track of the timeout between retry() calls\nvar retryTimer\n\n// reset the startTime and lastTime to now\n// this resets the start of the 60 second overall timeout as well as the\n// delay between attempts so that we'll retry these jobs sooner\nfunction resetQueue () {\n var now = Date.now()\n for (var i = 0; i < fs[gracefulQueue].length; ++i) {\n // entries that are only a length of 2 are from an older version, don't\n // bother modifying those since they'll be retried anyway.\n if (fs[gracefulQueue][i].length > 2) {\n fs[gracefulQueue][i][3] = now // startTime\n fs[gracefulQueue][i][4] = now // lastTime\n }\n }\n // call retry to make sure we're actively processing the queue\n retry()\n}\n\nfunction retry () {\n // clear the timer and remove it to help prevent unintended concurrency\n clearTimeout(retryTimer)\n retryTimer = undefined\n\n if (fs[gracefulQueue].length === 0)\n return\n\n var elem = fs[gracefulQueue].shift()\n var fn = elem[0]\n var args = elem[1]\n // these items may be unset if they were added by an older graceful-fs\n var err = elem[2]\n var startTime = elem[3]\n var lastTime = elem[4]\n\n // if we don't have a startTime we have no way of knowing if we've waited\n // long enough, so go ahead and retry this item now\n if (startTime === undefined) {\n debug('RETRY', fn.name, args)\n fn.apply(null, args)\n } else if (Date.now() - startTime >= 60000) {\n // it's been more than 60 seconds total, bail now\n debug('TIMEOUT', fn.name, args)\n var cb = args.pop()\n if (typeof cb === 'function')\n cb.call(null, err)\n } else {\n // the amount of time between the last attempt and right now\n var sinceAttempt = Date.now() - lastTime\n // the amount of time between when we first tried, and when we last tried\n // rounded up to at least 1\n var sinceStart = Math.max(lastTime - startTime, 1)\n // backoff. wait longer than the total time we've been retrying, but only\n // up to a maximum of 100ms\n var desiredDelay = Math.min(sinceStart * 1.2, 100)\n // it's been long enough since the last retry, do it again\n if (sinceAttempt >= desiredDelay) {\n debug('RETRY', fn.name, args)\n fn.apply(null, args.concat([startTime]))\n } else {\n // if we can't do this job yet, push it to the end of the queue\n // and let the next iteration check again\n fs[gracefulQueue].push(elem)\n }\n }\n\n // schedule our next run if one isn't already scheduled\n if (retryTimer === undefined) {\n retryTimer = setTimeout(retry, 0)\n }\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/graceful-fs/graceful-fs.js?"); + +/***/ }), + +/***/ "./node_modules/graceful-fs/legacy-streams.js": +/*!****************************************************!*\ + !*** ./node_modules/graceful-fs/legacy-streams.js ***! + \****************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var Stream = __webpack_require__(/*! stream */ \"stream\").Stream\n\nmodule.exports = legacy\n\nfunction legacy (fs) {\n return {\n ReadStream: ReadStream,\n WriteStream: WriteStream\n }\n\n function ReadStream (path, options) {\n if (!(this instanceof ReadStream)) return new ReadStream(path, options);\n\n Stream.call(this);\n\n var self = this;\n\n this.path = path;\n this.fd = null;\n this.readable = true;\n this.paused = false;\n\n this.flags = 'r';\n this.mode = 438; /*=0666*/\n this.bufferSize = 64 * 1024;\n\n options = options || {};\n\n // Mixin options into this\n var keys = Object.keys(options);\n for (var index = 0, length = keys.length; index < length; index++) {\n var key = keys[index];\n this[key] = options[key];\n }\n\n if (this.encoding) this.setEncoding(this.encoding);\n\n if (this.start !== undefined) {\n if ('number' !== typeof this.start) {\n throw TypeError('start must be a Number');\n }\n if (this.end === undefined) {\n this.end = Infinity;\n } else if ('number' !== typeof this.end) {\n throw TypeError('end must be a Number');\n }\n\n if (this.start > this.end) {\n throw new Error('start must be <= end');\n }\n\n this.pos = this.start;\n }\n\n if (this.fd !== null) {\n process.nextTick(function() {\n self._read();\n });\n return;\n }\n\n fs.open(this.path, this.flags, this.mode, function (err, fd) {\n if (err) {\n self.emit('error', err);\n self.readable = false;\n return;\n }\n\n self.fd = fd;\n self.emit('open', fd);\n self._read();\n })\n }\n\n function WriteStream (path, options) {\n if (!(this instanceof WriteStream)) return new WriteStream(path, options);\n\n Stream.call(this);\n\n this.path = path;\n this.fd = null;\n this.writable = true;\n\n this.flags = 'w';\n this.encoding = 'binary';\n this.mode = 438; /*=0666*/\n this.bytesWritten = 0;\n\n options = options || {};\n\n // Mixin options into this\n var keys = Object.keys(options);\n for (var index = 0, length = keys.length; index < length; index++) {\n var key = keys[index];\n this[key] = options[key];\n }\n\n if (this.start !== undefined) {\n if ('number' !== typeof this.start) {\n throw TypeError('start must be a Number');\n }\n if (this.start < 0) {\n throw new Error('start must be >= zero');\n }\n\n this.pos = this.start;\n }\n\n this.busy = false;\n this._queue = [];\n\n if (this.fd === null) {\n this._open = fs.open;\n this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);\n this.flush();\n }\n }\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/graceful-fs/legacy-streams.js?"); + +/***/ }), + +/***/ "./node_modules/graceful-fs/polyfills.js": +/*!***********************************************!*\ + !*** ./node_modules/graceful-fs/polyfills.js ***! + \***********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var constants = __webpack_require__(/*! constants */ \"constants\")\n\nvar origCwd = process.cwd\nvar cwd = null\n\nvar platform = process.env.GRACEFUL_FS_PLATFORM || process.platform\n\nprocess.cwd = function() {\n if (!cwd)\n cwd = origCwd.call(process)\n return cwd\n}\ntry {\n process.cwd()\n} catch (er) {}\n\n// This check is needed until node.js 12 is required\nif (typeof process.chdir === 'function') {\n var chdir = process.chdir\n process.chdir = function (d) {\n cwd = null\n chdir.call(process, d)\n }\n if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir)\n}\n\nmodule.exports = patch\n\nfunction patch (fs) {\n // (re-)implement some things that are known busted or missing.\n\n // lchmod, broken prior to 0.6.2\n // back-port the fix here.\n if (constants.hasOwnProperty('O_SYMLINK') &&\n process.version.match(/^v0\\.6\\.[0-2]|^v0\\.5\\./)) {\n patchLchmod(fs)\n }\n\n // lutimes implementation, or no-op\n if (!fs.lutimes) {\n patchLutimes(fs)\n }\n\n // https://github.com/isaacs/node-graceful-fs/issues/4\n // Chown should not fail on einval or eperm if non-root.\n // It should not fail on enosys ever, as this just indicates\n // that a fs doesn't support the intended operation.\n\n fs.chown = chownFix(fs.chown)\n fs.fchown = chownFix(fs.fchown)\n fs.lchown = chownFix(fs.lchown)\n\n fs.chmod = chmodFix(fs.chmod)\n fs.fchmod = chmodFix(fs.fchmod)\n fs.lchmod = chmodFix(fs.lchmod)\n\n fs.chownSync = chownFixSync(fs.chownSync)\n fs.fchownSync = chownFixSync(fs.fchownSync)\n fs.lchownSync = chownFixSync(fs.lchownSync)\n\n fs.chmodSync = chmodFixSync(fs.chmodSync)\n fs.fchmodSync = chmodFixSync(fs.fchmodSync)\n fs.lchmodSync = chmodFixSync(fs.lchmodSync)\n\n fs.stat = statFix(fs.stat)\n fs.fstat = statFix(fs.fstat)\n fs.lstat = statFix(fs.lstat)\n\n fs.statSync = statFixSync(fs.statSync)\n fs.fstatSync = statFixSync(fs.fstatSync)\n fs.lstatSync = statFixSync(fs.lstatSync)\n\n // if lchmod/lchown do not exist, then make them no-ops\n if (!fs.lchmod) {\n fs.lchmod = function (path, mode, cb) {\n if (cb) process.nextTick(cb)\n }\n fs.lchmodSync = function () {}\n }\n if (!fs.lchown) {\n fs.lchown = function (path, uid, gid, cb) {\n if (cb) process.nextTick(cb)\n }\n fs.lchownSync = function () {}\n }\n\n // on Windows, A/V software can lock the directory, causing this\n // to fail with an EACCES or EPERM if the directory contains newly\n // created files. Try again on failure, for up to 60 seconds.\n\n // Set the timeout this long because some Windows Anti-Virus, such as Parity\n // bit9, may lock files for up to a minute, causing npm package install\n // failures. Also, take care to yield the scheduler. Windows scheduling gives\n // CPU to a busy looping process, which can cause the program causing the lock\n // contention to be starved of CPU by node, so the contention doesn't resolve.\n if (platform === \"win32\") {\n fs.rename = (function (fs$rename) { return function (from, to, cb) {\n var start = Date.now()\n var backoff = 0;\n fs$rename(from, to, function CB (er) {\n if (er\n && (er.code === \"EACCES\" || er.code === \"EPERM\")\n && Date.now() - start < 60000) {\n setTimeout(function() {\n fs.stat(to, function (stater, st) {\n if (stater && stater.code === \"ENOENT\")\n fs$rename(from, to, CB);\n else\n cb(er)\n })\n }, backoff)\n if (backoff < 100)\n backoff += 10;\n return;\n }\n if (cb) cb(er)\n })\n }})(fs.rename)\n }\n\n // if read() returns EAGAIN, then just try it again.\n fs.read = (function (fs$read) {\n function read (fd, buffer, offset, length, position, callback_) {\n var callback\n if (callback_ && typeof callback_ === 'function') {\n var eagCounter = 0\n callback = function (er, _, __) {\n if (er && er.code === 'EAGAIN' && eagCounter < 10) {\n eagCounter ++\n return fs$read.call(fs, fd, buffer, offset, length, position, callback)\n }\n callback_.apply(this, arguments)\n }\n }\n return fs$read.call(fs, fd, buffer, offset, length, position, callback)\n }\n\n // This ensures `util.promisify` works as it does for native `fs.read`.\n if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read)\n return read\n })(fs.read)\n\n fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) {\n var eagCounter = 0\n while (true) {\n try {\n return fs$readSync.call(fs, fd, buffer, offset, length, position)\n } catch (er) {\n if (er.code === 'EAGAIN' && eagCounter < 10) {\n eagCounter ++\n continue\n }\n throw er\n }\n }\n }})(fs.readSync)\n\n function patchLchmod (fs) {\n fs.lchmod = function (path, mode, callback) {\n fs.open( path\n , constants.O_WRONLY | constants.O_SYMLINK\n , mode\n , function (err, fd) {\n if (err) {\n if (callback) callback(err)\n return\n }\n // prefer to return the chmod error, if one occurs,\n // but still try to close, and report closing errors if they occur.\n fs.fchmod(fd, mode, function (err) {\n fs.close(fd, function(err2) {\n if (callback) callback(err || err2)\n })\n })\n })\n }\n\n fs.lchmodSync = function (path, mode) {\n var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode)\n\n // prefer to return the chmod error, if one occurs,\n // but still try to close, and report closing errors if they occur.\n var threw = true\n var ret\n try {\n ret = fs.fchmodSync(fd, mode)\n threw = false\n } finally {\n if (threw) {\n try {\n fs.closeSync(fd)\n } catch (er) {}\n } else {\n fs.closeSync(fd)\n }\n }\n return ret\n }\n }\n\n function patchLutimes (fs) {\n if (constants.hasOwnProperty(\"O_SYMLINK\")) {\n fs.lutimes = function (path, at, mt, cb) {\n fs.open(path, constants.O_SYMLINK, function (er, fd) {\n if (er) {\n if (cb) cb(er)\n return\n }\n fs.futimes(fd, at, mt, function (er) {\n fs.close(fd, function (er2) {\n if (cb) cb(er || er2)\n })\n })\n })\n }\n\n fs.lutimesSync = function (path, at, mt) {\n var fd = fs.openSync(path, constants.O_SYMLINK)\n var ret\n var threw = true\n try {\n ret = fs.futimesSync(fd, at, mt)\n threw = false\n } finally {\n if (threw) {\n try {\n fs.closeSync(fd)\n } catch (er) {}\n } else {\n fs.closeSync(fd)\n }\n }\n return ret\n }\n\n } else {\n fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) }\n fs.lutimesSync = function () {}\n }\n }\n\n function chmodFix (orig) {\n if (!orig) return orig\n return function (target, mode, cb) {\n return orig.call(fs, target, mode, function (er) {\n if (chownErOk(er)) er = null\n if (cb) cb.apply(this, arguments)\n })\n }\n }\n\n function chmodFixSync (orig) {\n if (!orig) return orig\n return function (target, mode) {\n try {\n return orig.call(fs, target, mode)\n } catch (er) {\n if (!chownErOk(er)) throw er\n }\n }\n }\n\n\n function chownFix (orig) {\n if (!orig) return orig\n return function (target, uid, gid, cb) {\n return orig.call(fs, target, uid, gid, function (er) {\n if (chownErOk(er)) er = null\n if (cb) cb.apply(this, arguments)\n })\n }\n }\n\n function chownFixSync (orig) {\n if (!orig) return orig\n return function (target, uid, gid) {\n try {\n return orig.call(fs, target, uid, gid)\n } catch (er) {\n if (!chownErOk(er)) throw er\n }\n }\n }\n\n function statFix (orig) {\n if (!orig) return orig\n // Older versions of Node erroneously returned signed integers for\n // uid + gid.\n return function (target, options, cb) {\n if (typeof options === 'function') {\n cb = options\n options = null\n }\n function callback (er, stats) {\n if (stats) {\n if (stats.uid < 0) stats.uid += 0x100000000\n if (stats.gid < 0) stats.gid += 0x100000000\n }\n if (cb) cb.apply(this, arguments)\n }\n return options ? orig.call(fs, target, options, callback)\n : orig.call(fs, target, callback)\n }\n }\n\n function statFixSync (orig) {\n if (!orig) return orig\n // Older versions of Node erroneously returned signed integers for\n // uid + gid.\n return function (target, options) {\n var stats = options ? orig.call(fs, target, options)\n : orig.call(fs, target)\n if (stats.uid < 0) stats.uid += 0x100000000\n if (stats.gid < 0) stats.gid += 0x100000000\n return stats;\n }\n }\n\n // ENOSYS means that the fs doesn't support the op. Just ignore\n // that, because it doesn't matter.\n //\n // if there's no getuid, or if getuid() is something other\n // than 0, and the error is EINVAL or EPERM, then just ignore\n // it.\n //\n // This specific case is a silent failure in cp, install, tar,\n // and most other unix tools that manage permissions.\n //\n // When running as root, or if other types of errors are\n // encountered, then it's strict.\n function chownErOk (er) {\n if (!er)\n return true\n\n if (er.code === \"ENOSYS\")\n return true\n\n var nonroot = !process.getuid || process.getuid() !== 0\n if (nonroot) {\n if (er.code === \"EINVAL\" || er.code === \"EPERM\")\n return true\n }\n\n return false\n }\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/graceful-fs/polyfills.js?"); + +/***/ }), + +/***/ "./node_modules/has-value/index.js": +/*!*****************************************!*\ + !*** ./node_modules/has-value/index.js ***! + \*****************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * has-value \n *\n * Copyright (c) 2014-2017, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n\n\nvar isObject = __webpack_require__(/*! isobject */ \"./node_modules/isobject/index.js\");\nvar hasValues = __webpack_require__(/*! has-values */ \"./node_modules/has-values/index.js\");\nvar get = __webpack_require__(/*! get-value */ \"./node_modules/get-value/index.js\");\n\nmodule.exports = function(val, prop) {\n return hasValues(isObject(val) && prop ? get(val, prop) : val);\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/has-value/index.js?"); + +/***/ }), + +/***/ "./node_modules/has-values/index.js": +/*!******************************************!*\ + !*** ./node_modules/has-values/index.js ***! + \******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * has-values \n *\n * Copyright (c) 2014-2015, 2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar typeOf = __webpack_require__(/*! kind-of */ \"./node_modules/has-values/node_modules/kind-of/index.js\");\nvar isNumber = __webpack_require__(/*! is-number */ \"./node_modules/is-number/index.js\");\n\nmodule.exports = function hasValue(val) {\n // is-number checks for NaN and other edge cases\n if (isNumber(val)) {\n return true;\n }\n\n switch (typeOf(val)) {\n case 'null':\n case 'boolean':\n case 'function':\n return true;\n case 'string':\n case 'arguments':\n return val.length !== 0;\n case 'error':\n return val.message !== '';\n case 'array':\n var len = val.length;\n if (len === 0) {\n return false;\n }\n for (var i = 0; i < len; i++) {\n if (hasValue(val[i])) {\n return true;\n }\n }\n return false;\n case 'file':\n case 'map':\n case 'set':\n return val.size !== 0;\n case 'object':\n var keys = Object.keys(val);\n if (keys.length === 0) {\n return false;\n }\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n if (hasValue(val[key])) {\n return true;\n }\n }\n return false;\n default: {\n return false;\n }\n }\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/has-values/index.js?"); + +/***/ }), + +/***/ "./node_modules/has-values/node_modules/kind-of/index.js": +/*!***************************************************************!*\ + !*** ./node_modules/has-values/node_modules/kind-of/index.js ***! + \***************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var isBuffer = __webpack_require__(/*! is-buffer */ \"./node_modules/is-buffer/index.js\");\nvar toString = Object.prototype.toString;\n\n/**\n * Get the native `typeof` a value.\n *\n * @param {*} `val`\n * @return {*} Native javascript type\n */\n\nmodule.exports = function kindOf(val) {\n // primitivies\n if (typeof val === 'undefined') {\n return 'undefined';\n }\n if (val === null) {\n return 'null';\n }\n if (val === true || val === false || val instanceof Boolean) {\n return 'boolean';\n }\n if (typeof val === 'string' || val instanceof String) {\n return 'string';\n }\n if (typeof val === 'number' || val instanceof Number) {\n return 'number';\n }\n\n // functions\n if (typeof val === 'function' || val instanceof Function) {\n return 'function';\n }\n\n // array\n if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {\n return 'array';\n }\n\n // check for instances of RegExp and Date before calling `toString`\n if (val instanceof RegExp) {\n return 'regexp';\n }\n if (val instanceof Date) {\n return 'date';\n }\n\n // other objects\n var type = toString.call(val);\n\n if (type === '[object RegExp]') {\n return 'regexp';\n }\n if (type === '[object Date]') {\n return 'date';\n }\n if (type === '[object Arguments]') {\n return 'arguments';\n }\n if (type === '[object Error]') {\n return 'error';\n }\n if (type === '[object Promise]') {\n return 'promise';\n }\n\n // buffer\n if (isBuffer(val)) {\n return 'buffer';\n }\n\n // es6: Map, WeakMap, Set, WeakSet\n if (type === '[object Set]') {\n return 'set';\n }\n if (type === '[object WeakSet]') {\n return 'weakset';\n }\n if (type === '[object Map]') {\n return 'map';\n }\n if (type === '[object WeakMap]') {\n return 'weakmap';\n }\n if (type === '[object Symbol]') {\n return 'symbol';\n }\n\n // typed arrays\n if (type === '[object Int8Array]') {\n return 'int8array';\n }\n if (type === '[object Uint8Array]') {\n return 'uint8array';\n }\n if (type === '[object Uint8ClampedArray]') {\n return 'uint8clampedarray';\n }\n if (type === '[object Int16Array]') {\n return 'int16array';\n }\n if (type === '[object Uint16Array]') {\n return 'uint16array';\n }\n if (type === '[object Int32Array]') {\n return 'int32array';\n }\n if (type === '[object Uint32Array]') {\n return 'uint32array';\n }\n if (type === '[object Float32Array]') {\n return 'float32array';\n }\n if (type === '[object Float64Array]') {\n return 'float64array';\n }\n\n // must be a plain object\n return 'object';\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/has-values/node_modules/kind-of/index.js?"); + +/***/ }), + +/***/ "./node_modules/inherits/inherits.js": +/*!*******************************************!*\ + !*** ./node_modules/inherits/inherits.js ***! + \*******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("try {\n var util = __webpack_require__(/*! util */ \"util\");\n /* istanbul ignore next */\n if (typeof util.inherits !== 'function') throw '';\n module.exports = util.inherits;\n} catch (e) {\n /* istanbul ignore next */\n module.exports = __webpack_require__(/*! ./inherits_browser.js */ \"./node_modules/inherits/inherits_browser.js\");\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/inherits/inherits.js?"); + +/***/ }), + +/***/ "./node_modules/inherits/inherits_browser.js": +/*!***************************************************!*\ + !*** ./node_modules/inherits/inherits_browser.js ***! + \***************************************************/ +/***/ ((module) => { + +eval("if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/inherits/inherits_browser.js?"); + +/***/ }), + +/***/ "./node_modules/is-accessor-descriptor/index.js": +/*!******************************************************!*\ + !*** ./node_modules/is-accessor-descriptor/index.js ***! + \******************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * is-accessor-descriptor \n *\n * Copyright (c) 2015-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar typeOf = __webpack_require__(/*! kind-of */ \"./node_modules/kind-of/index.js\");\n\n// accessor descriptor properties\nvar accessor = {\n get: 'function',\n set: 'function',\n configurable: 'boolean',\n enumerable: 'boolean'\n};\n\nfunction isAccessorDescriptor(obj, prop) {\n if (typeof prop === 'string') {\n var val = Object.getOwnPropertyDescriptor(obj, prop);\n return typeof val !== 'undefined';\n }\n\n if (typeOf(obj) !== 'object') {\n return false;\n }\n\n if (has(obj, 'value') || has(obj, 'writable')) {\n return false;\n }\n\n if (!has(obj, 'get') || typeof obj.get !== 'function') {\n return false;\n }\n\n // tldr: it's valid to have \"set\" be undefined\n // \"set\" might be undefined if `Object.getOwnPropertyDescriptor`\n // was used to get the value, and only `get` was defined by the user\n if (has(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') {\n return false;\n }\n\n for (var key in obj) {\n if (!accessor.hasOwnProperty(key)) {\n continue;\n }\n\n if (typeOf(obj[key]) === accessor[key]) {\n continue;\n }\n\n if (typeof obj[key] !== 'undefined') {\n return false;\n }\n }\n return true;\n}\n\nfunction has(obj, key) {\n return {}.hasOwnProperty.call(obj, key);\n}\n\n/**\n * Expose `isAccessorDescriptor`\n */\n\nmodule.exports = isAccessorDescriptor;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/is-accessor-descriptor/index.js?"); + +/***/ }), + +/***/ "./node_modules/is-binary-path/index.js": +/*!**********************************************!*\ + !*** ./node_modules/is-binary-path/index.js ***! + \**********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\nvar path = __webpack_require__(/*! path */ \"path\");\nvar binaryExtensions = __webpack_require__(/*! binary-extensions */ \"./node_modules/binary-extensions/binary-extensions.json\");\nvar exts = Object.create(null);\n\nbinaryExtensions.forEach(function (el) {\n\texts[el] = true;\n});\n\nmodule.exports = function (filepath) {\n\treturn path.extname(filepath).slice(1).toLowerCase() in exts;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/is-binary-path/index.js?"); + +/***/ }), + +/***/ "./node_modules/is-buffer/index.js": +/*!*****************************************!*\ + !*** ./node_modules/is-buffer/index.js ***! + \*****************************************/ +/***/ ((module) => { + +eval("/*!\n * Determine if an object is a Buffer\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n\n// The _isBuffer check is for Safari 5-7 support, because it's missing\n// Object.prototype.constructor. Remove this eventually\nmodule.exports = function (obj) {\n return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)\n}\n\nfunction isBuffer (obj) {\n return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)\n}\n\n// For Node v0.10 support. Remove this eventually.\nfunction isSlowBuffer (obj) {\n return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/is-buffer/index.js?"); + +/***/ }), + +/***/ "./node_modules/is-data-descriptor/index.js": +/*!**************************************************!*\ + !*** ./node_modules/is-data-descriptor/index.js ***! + \**************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * is-data-descriptor \n *\n * Copyright (c) 2015-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar typeOf = __webpack_require__(/*! kind-of */ \"./node_modules/kind-of/index.js\");\n\nmodule.exports = function isDataDescriptor(obj, prop) {\n // data descriptor properties\n var data = {\n configurable: 'boolean',\n enumerable: 'boolean',\n writable: 'boolean'\n };\n\n if (typeOf(obj) !== 'object') {\n return false;\n }\n\n if (typeof prop === 'string') {\n var val = Object.getOwnPropertyDescriptor(obj, prop);\n return typeof val !== 'undefined';\n }\n\n if (!('value' in obj) && !('writable' in obj)) {\n return false;\n }\n\n for (var key in obj) {\n if (key === 'value') continue;\n\n if (!data.hasOwnProperty(key)) {\n continue;\n }\n\n if (typeOf(obj[key]) === data[key]) {\n continue;\n }\n\n if (typeof obj[key] !== 'undefined') {\n return false;\n }\n }\n return true;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/is-data-descriptor/index.js?"); + +/***/ }), + +/***/ "./node_modules/is-descriptor/index.js": +/*!*********************************************!*\ + !*** ./node_modules/is-descriptor/index.js ***! + \*********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * is-descriptor \n *\n * Copyright (c) 2015-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar typeOf = __webpack_require__(/*! kind-of */ \"./node_modules/kind-of/index.js\");\nvar isAccessor = __webpack_require__(/*! is-accessor-descriptor */ \"./node_modules/is-accessor-descriptor/index.js\");\nvar isData = __webpack_require__(/*! is-data-descriptor */ \"./node_modules/is-data-descriptor/index.js\");\n\nmodule.exports = function isDescriptor(obj, key) {\n if (typeOf(obj) !== 'object') {\n return false;\n }\n if ('get' in obj) {\n return isAccessor(obj, key);\n }\n return isData(obj, key);\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/is-descriptor/index.js?"); + +/***/ }), + +/***/ "./node_modules/is-extendable/index.js": +/*!*********************************************!*\ + !*** ./node_modules/is-extendable/index.js ***! + \*********************************************/ +/***/ ((module) => { + +"use strict"; +eval("/*!\n * is-extendable \n *\n * Copyright (c) 2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n\n\nmodule.exports = function isExtendable(val) {\n return typeof val !== 'undefined' && val !== null\n && (typeof val === 'object' || typeof val === 'function');\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/is-extendable/index.js?"); + +/***/ }), + +/***/ "./node_modules/is-extglob/index.js": +/*!******************************************!*\ + !*** ./node_modules/is-extglob/index.js ***! + \******************************************/ +/***/ ((module) => { + +eval("/*!\n * is-extglob \n *\n * Copyright (c) 2014-2016, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\nmodule.exports = function isExtglob(str) {\n if (typeof str !== 'string' || str === '') {\n return false;\n }\n\n var match;\n while ((match = /(\\\\).|([@?!+*]\\(.*\\))/g.exec(str))) {\n if (match[2]) return true;\n str = str.slice(match.index + match[0].length);\n }\n\n return false;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/is-extglob/index.js?"); + +/***/ }), + +/***/ "./node_modules/is-glob/index.js": +/*!***************************************!*\ + !*** ./node_modules/is-glob/index.js ***! + \***************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("/*!\n * is-glob \n *\n * Copyright (c) 2014-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\nvar isExtglob = __webpack_require__(/*! is-extglob */ \"./node_modules/is-extglob/index.js\");\nvar chars = { '{': '}', '(': ')', '[': ']'};\nvar strictRegex = /\\\\(.)|(^!|\\*|[\\].+)]\\?|\\[[^\\\\\\]]+\\]|\\{[^\\\\}]+\\}|\\(\\?[:!=][^\\\\)]+\\)|\\([^|]+\\|[^\\\\)]+\\))/;\nvar relaxedRegex = /\\\\(.)|(^!|[*?{}()[\\]]|\\(\\?)/;\n\nmodule.exports = function isGlob(str, options) {\n if (typeof str !== 'string' || str === '') {\n return false;\n }\n\n if (isExtglob(str)) {\n return true;\n }\n\n var regex = strictRegex;\n var match;\n\n // optionally relax regex\n if (options && options.strict === false) {\n regex = relaxedRegex;\n }\n\n while ((match = regex.exec(str))) {\n if (match[2]) return true;\n var idx = match.index + match[0].length;\n\n // if an open bracket/brace/paren is escaped,\n // set the index to the next closing character\n var open = match[1];\n var close = open ? chars[open] : null;\n if (open && close) {\n var n = str.indexOf(close, idx);\n if (n !== -1) {\n idx = n + 1;\n }\n }\n\n str = str.slice(idx);\n }\n return false;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/is-glob/index.js?"); + +/***/ }), + +/***/ "./node_modules/is-number/index.js": +/*!*****************************************!*\ + !*** ./node_modules/is-number/index.js ***! + \*****************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * is-number \n *\n * Copyright (c) 2014-2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n\n\nvar typeOf = __webpack_require__(/*! kind-of */ \"./node_modules/is-number/node_modules/kind-of/index.js\");\n\nmodule.exports = function isNumber(num) {\n var type = typeOf(num);\n\n if (type === 'string') {\n if (!num.trim()) return false;\n } else if (type !== 'number') {\n return false;\n }\n\n return (num - num + 1) >= 0;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/is-number/index.js?"); + +/***/ }), + +/***/ "./node_modules/is-number/node_modules/kind-of/index.js": +/*!**************************************************************!*\ + !*** ./node_modules/is-number/node_modules/kind-of/index.js ***! + \**************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var isBuffer = __webpack_require__(/*! is-buffer */ \"./node_modules/is-buffer/index.js\");\nvar toString = Object.prototype.toString;\n\n/**\n * Get the native `typeof` a value.\n *\n * @param {*} `val`\n * @return {*} Native javascript type\n */\n\nmodule.exports = function kindOf(val) {\n // primitivies\n if (typeof val === 'undefined') {\n return 'undefined';\n }\n if (val === null) {\n return 'null';\n }\n if (val === true || val === false || val instanceof Boolean) {\n return 'boolean';\n }\n if (typeof val === 'string' || val instanceof String) {\n return 'string';\n }\n if (typeof val === 'number' || val instanceof Number) {\n return 'number';\n }\n\n // functions\n if (typeof val === 'function' || val instanceof Function) {\n return 'function';\n }\n\n // array\n if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {\n return 'array';\n }\n\n // check for instances of RegExp and Date before calling `toString`\n if (val instanceof RegExp) {\n return 'regexp';\n }\n if (val instanceof Date) {\n return 'date';\n }\n\n // other objects\n var type = toString.call(val);\n\n if (type === '[object RegExp]') {\n return 'regexp';\n }\n if (type === '[object Date]') {\n return 'date';\n }\n if (type === '[object Arguments]') {\n return 'arguments';\n }\n if (type === '[object Error]') {\n return 'error';\n }\n\n // buffer\n if (isBuffer(val)) {\n return 'buffer';\n }\n\n // es6: Map, WeakMap, Set, WeakSet\n if (type === '[object Set]') {\n return 'set';\n }\n if (type === '[object WeakSet]') {\n return 'weakset';\n }\n if (type === '[object Map]') {\n return 'map';\n }\n if (type === '[object WeakMap]') {\n return 'weakmap';\n }\n if (type === '[object Symbol]') {\n return 'symbol';\n }\n\n // typed arrays\n if (type === '[object Int8Array]') {\n return 'int8array';\n }\n if (type === '[object Uint8Array]') {\n return 'uint8array';\n }\n if (type === '[object Uint8ClampedArray]') {\n return 'uint8clampedarray';\n }\n if (type === '[object Int16Array]') {\n return 'int16array';\n }\n if (type === '[object Uint16Array]') {\n return 'uint16array';\n }\n if (type === '[object Int32Array]') {\n return 'int32array';\n }\n if (type === '[object Uint32Array]') {\n return 'uint32array';\n }\n if (type === '[object Float32Array]') {\n return 'float32array';\n }\n if (type === '[object Float64Array]') {\n return 'float64array';\n }\n\n // must be a plain object\n return 'object';\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/is-number/node_modules/kind-of/index.js?"); + +/***/ }), + +/***/ "./node_modules/is-plain-object/index.js": +/*!***********************************************!*\ + !*** ./node_modules/is-plain-object/index.js ***! + \***********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * is-plain-object \n *\n * Copyright (c) 2014-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar isObject = __webpack_require__(/*! isobject */ \"./node_modules/isobject/index.js\");\n\nfunction isObjectObject(o) {\n return isObject(o) === true\n && Object.prototype.toString.call(o) === '[object Object]';\n}\n\nmodule.exports = function isPlainObject(o) {\n var ctor,prot;\n\n if (isObjectObject(o) === false) return false;\n\n // If has modified constructor\n ctor = o.constructor;\n if (typeof ctor !== 'function') return false;\n\n // If has modified prototype\n prot = ctor.prototype;\n if (isObjectObject(prot) === false) return false;\n\n // If constructor does not have an Object-specific method\n if (prot.hasOwnProperty('isPrototypeOf') === false) {\n return false;\n }\n\n // Most likely a plain Object\n return true;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/is-plain-object/index.js?"); + +/***/ }), + +/***/ "./node_modules/is-windows/index.js": +/*!******************************************!*\ + !*** ./node_modules/is-windows/index.js ***! + \******************************************/ +/***/ ((module, exports) => { + +eval("var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!\n * is-windows \n *\n * Copyright © 2015-2018, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n(function(factory) {\n if (exports && typeof exports === 'object' && \"object\" !== 'undefined') {\n module.exports = factory();\n } else if (true) {\n !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),\n\t\t__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?\n\t\t(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),\n\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n } else {}\n})(function() {\n 'use strict';\n return function isWindows() {\n return process && (process.platform === 'win32' || /^(msys|cygwin)$/.test(process.env.OSTYPE));\n };\n});\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/is-windows/index.js?"); + +/***/ }), + +/***/ "./node_modules/isarray/index.js": +/*!***************************************!*\ + !*** ./node_modules/isarray/index.js ***! + \***************************************/ +/***/ ((module) => { + +eval("var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/isarray/index.js?"); + +/***/ }), + +/***/ "./node_modules/isobject/index.js": +/*!****************************************!*\ + !*** ./node_modules/isobject/index.js ***! + \****************************************/ +/***/ ((module) => { + +"use strict"; +eval("/*!\n * isobject \n *\n * Copyright (c) 2014-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nmodule.exports = function isObject(val) {\n return val != null && typeof val === 'object' && Array.isArray(val) === false;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/isobject/index.js?"); + +/***/ }), + +/***/ "./node_modules/kind-of/index.js": +/*!***************************************!*\ + !*** ./node_modules/kind-of/index.js ***! + \***************************************/ +/***/ ((module) => { + +eval("var toString = Object.prototype.toString;\n\nmodule.exports = function kindOf(val) {\n if (val === void 0) return 'undefined';\n if (val === null) return 'null';\n\n var type = typeof val;\n if (type === 'boolean') return 'boolean';\n if (type === 'string') return 'string';\n if (type === 'number') return 'number';\n if (type === 'symbol') return 'symbol';\n if (type === 'function') {\n return isGeneratorFn(val) ? 'generatorfunction' : 'function';\n }\n\n if (isArray(val)) return 'array';\n if (isBuffer(val)) return 'buffer';\n if (isArguments(val)) return 'arguments';\n if (isDate(val)) return 'date';\n if (isError(val)) return 'error';\n if (isRegexp(val)) return 'regexp';\n\n switch (ctorName(val)) {\n case 'Symbol': return 'symbol';\n case 'Promise': return 'promise';\n\n // Set, Map, WeakSet, WeakMap\n case 'WeakMap': return 'weakmap';\n case 'WeakSet': return 'weakset';\n case 'Map': return 'map';\n case 'Set': return 'set';\n\n // 8-bit typed arrays\n case 'Int8Array': return 'int8array';\n case 'Uint8Array': return 'uint8array';\n case 'Uint8ClampedArray': return 'uint8clampedarray';\n\n // 16-bit typed arrays\n case 'Int16Array': return 'int16array';\n case 'Uint16Array': return 'uint16array';\n\n // 32-bit typed arrays\n case 'Int32Array': return 'int32array';\n case 'Uint32Array': return 'uint32array';\n case 'Float32Array': return 'float32array';\n case 'Float64Array': return 'float64array';\n }\n\n if (isGeneratorObj(val)) {\n return 'generator';\n }\n\n // Non-plain objects\n type = toString.call(val);\n switch (type) {\n case '[object Object]': return 'object';\n // iterators\n case '[object Map Iterator]': return 'mapiterator';\n case '[object Set Iterator]': return 'setiterator';\n case '[object String Iterator]': return 'stringiterator';\n case '[object Array Iterator]': return 'arrayiterator';\n }\n\n // other\n return type.slice(8, -1).toLowerCase().replace(/\\s/g, '');\n};\n\nfunction ctorName(val) {\n return typeof val.constructor === 'function' ? val.constructor.name : null;\n}\n\nfunction isArray(val) {\n if (Array.isArray) return Array.isArray(val);\n return val instanceof Array;\n}\n\nfunction isError(val) {\n return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number');\n}\n\nfunction isDate(val) {\n if (val instanceof Date) return true;\n return typeof val.toDateString === 'function'\n && typeof val.getDate === 'function'\n && typeof val.setDate === 'function';\n}\n\nfunction isRegexp(val) {\n if (val instanceof RegExp) return true;\n return typeof val.flags === 'string'\n && typeof val.ignoreCase === 'boolean'\n && typeof val.multiline === 'boolean'\n && typeof val.global === 'boolean';\n}\n\nfunction isGeneratorFn(name, val) {\n return ctorName(name) === 'GeneratorFunction';\n}\n\nfunction isGeneratorObj(val) {\n return typeof val.throw === 'function'\n && typeof val.return === 'function'\n && typeof val.next === 'function';\n}\n\nfunction isArguments(val) {\n try {\n if (typeof val.length === 'number' && typeof val.callee === 'function') {\n return true;\n }\n } catch (err) {\n if (err.message.indexOf('callee') !== -1) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * If you need to support Safari 5-7 (8-10 yr-old browser),\n * take a look at https://github.com/feross/is-buffer\n */\n\nfunction isBuffer(val) {\n if (val.constructor && typeof val.constructor.isBuffer === 'function') {\n return val.constructor.isBuffer(val);\n }\n return false;\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/kind-of/index.js?"); + +/***/ }), + +/***/ "./node_modules/map-cache/index.js": +/*!*****************************************!*\ + !*** ./node_modules/map-cache/index.js ***! + \*****************************************/ +/***/ ((module) => { + +"use strict"; +eval("/*!\n * map-cache \n *\n * Copyright (c) 2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n\n\nvar hasOwn = Object.prototype.hasOwnProperty;\n\n/**\n * Expose `MapCache`\n */\n\nmodule.exports = MapCache;\n\n/**\n * Creates a cache object to store key/value pairs.\n *\n * ```js\n * var cache = new MapCache();\n * ```\n *\n * @api public\n */\n\nfunction MapCache(data) {\n this.__data__ = data || {};\n}\n\n/**\n * Adds `value` to `key` on the cache.\n *\n * ```js\n * cache.set('foo', 'bar');\n * ```\n *\n * @param {String} `key` The key of the value to cache.\n * @param {*} `value` The value to cache.\n * @returns {Object} Returns the `Cache` object for chaining.\n * @api public\n */\n\nMapCache.prototype.set = function mapSet(key, value) {\n if (key !== '__proto__') {\n this.__data__[key] = value;\n }\n return this;\n};\n\n/**\n * Gets the cached value for `key`.\n *\n * ```js\n * cache.get('foo');\n * //=> 'bar'\n * ```\n *\n * @param {String} `key` The key of the value to get.\n * @returns {*} Returns the cached value.\n * @api public\n */\n\nMapCache.prototype.get = function mapGet(key) {\n return key === '__proto__' ? undefined : this.__data__[key];\n};\n\n/**\n * Checks if a cached value for `key` exists.\n *\n * ```js\n * cache.has('foo');\n * //=> true\n * ```\n *\n * @param {String} `key` The key of the entry to check.\n * @returns {Boolean} Returns `true` if an entry for `key` exists, else `false`.\n * @api public\n */\n\nMapCache.prototype.has = function mapHas(key) {\n return key !== '__proto__' && hasOwn.call(this.__data__, key);\n};\n\n/**\n * Removes `key` and its value from the cache.\n *\n * ```js\n * cache.del('foo');\n * ```\n * @title .del\n * @param {String} `key` The key of the value to remove.\n * @returns {Boolean} Returns `true` if the entry was removed successfully, else `false`.\n * @api public\n */\n\nMapCache.prototype.del = function mapDelete(key) {\n return this.has(key) && delete this.__data__[key];\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/map-cache/index.js?"); + +/***/ }), + +/***/ "./node_modules/map-visit/index.js": +/*!*****************************************!*\ + !*** ./node_modules/map-visit/index.js ***! + \*****************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar util = __webpack_require__(/*! util */ \"util\");\nvar visit = __webpack_require__(/*! object-visit */ \"./node_modules/object-visit/index.js\");\n\n/**\n * Map `visit` over an array of objects.\n *\n * @param {Object} `collection` The context in which to invoke `method`\n * @param {String} `method` Name of the method to call on `collection`\n * @param {Object} `arr` Array of objects.\n */\n\nmodule.exports = function mapVisit(collection, method, val) {\n if (isObject(val)) {\n return visit.apply(null, arguments);\n }\n\n if (!Array.isArray(val)) {\n throw new TypeError('expected an array: ' + util.inspect(val));\n }\n\n var args = [].slice.call(arguments, 3);\n\n for (var i = 0; i < val.length; i++) {\n var ele = val[i];\n if (isObject(ele)) {\n visit.apply(null, [collection, method, ele].concat(args));\n } else {\n collection[method].apply(collection, [ele].concat(args));\n }\n }\n};\n\nfunction isObject(val) {\n return val && (typeof val === 'function' || (!Array.isArray(val) && typeof val === 'object'));\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/map-visit/index.js?"); + +/***/ }), + +/***/ "./node_modules/micromatch/index.js": +/*!******************************************!*\ + !*** ./node_modules/micromatch/index.js ***! + \******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\n/**\n * Module dependencies\n */\n\nvar util = __webpack_require__(/*! util */ \"util\");\nvar braces = __webpack_require__(/*! braces */ \"./node_modules/braces/index.js\");\nvar toRegex = __webpack_require__(/*! to-regex */ \"./node_modules/to-regex/index.js\");\nvar extend = __webpack_require__(/*! extend-shallow */ \"./node_modules/micromatch/node_modules/extend-shallow/index.js\");\n\n/**\n * Local dependencies\n */\n\nvar compilers = __webpack_require__(/*! ./lib/compilers */ \"./node_modules/micromatch/lib/compilers.js\");\nvar parsers = __webpack_require__(/*! ./lib/parsers */ \"./node_modules/micromatch/lib/parsers.js\");\nvar cache = __webpack_require__(/*! ./lib/cache */ \"./node_modules/micromatch/lib/cache.js\");\nvar utils = __webpack_require__(/*! ./lib/utils */ \"./node_modules/micromatch/lib/utils.js\");\nvar MAX_LENGTH = 1024 * 64;\n\n/**\n * The main function takes a list of strings and one or more\n * glob patterns to use for matching.\n *\n * ```js\n * var mm = require('micromatch');\n * mm(list, patterns[, options]);\n *\n * console.log(mm(['a.js', 'a.txt'], ['*.js']));\n * //=> [ 'a.js' ]\n * ```\n * @param {Array} `list` A list of strings to match\n * @param {String|Array} `patterns` One or more glob patterns to use for matching.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Array} Returns an array of matches\n * @summary false\n * @api public\n */\n\nfunction micromatch(list, patterns, options) {\n patterns = utils.arrayify(patterns);\n list = utils.arrayify(list);\n\n var len = patterns.length;\n if (list.length === 0 || len === 0) {\n return [];\n }\n\n if (len === 1) {\n return micromatch.match(list, patterns[0], options);\n }\n\n var omit = [];\n var keep = [];\n var idx = -1;\n\n while (++idx < len) {\n var pattern = patterns[idx];\n\n if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) {\n omit.push.apply(omit, micromatch.match(list, pattern.slice(1), options));\n } else {\n keep.push.apply(keep, micromatch.match(list, pattern, options));\n }\n }\n\n var matches = utils.diff(keep, omit);\n if (!options || options.nodupes !== false) {\n return utils.unique(matches);\n }\n\n return matches;\n}\n\n/**\n * Similar to the main function, but `pattern` must be a string.\n *\n * ```js\n * var mm = require('micromatch');\n * mm.match(list, pattern[, options]);\n *\n * console.log(mm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a'));\n * //=> ['a.a', 'a.aa']\n * ```\n * @param {Array} `list` Array of strings to match\n * @param {String} `pattern` Glob pattern to use for matching.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Array} Returns an array of matches\n * @api public\n */\n\nmicromatch.match = function(list, pattern, options) {\n if (Array.isArray(pattern)) {\n throw new TypeError('expected pattern to be a string');\n }\n\n var unixify = utils.unixify(options);\n var isMatch = memoize('match', pattern, options, micromatch.matcher);\n var matches = [];\n\n list = utils.arrayify(list);\n var len = list.length;\n var idx = -1;\n\n while (++idx < len) {\n var ele = list[idx];\n if (ele === pattern || isMatch(ele)) {\n matches.push(utils.value(ele, unixify, options));\n }\n }\n\n // if no options were passed, uniquify results and return\n if (typeof options === 'undefined') {\n return utils.unique(matches);\n }\n\n if (matches.length === 0) {\n if (options.failglob === true) {\n throw new Error('no matches found for \"' + pattern + '\"');\n }\n if (options.nonull === true || options.nullglob === true) {\n return [options.unescape ? utils.unescape(pattern) : pattern];\n }\n }\n\n // if `opts.ignore` was defined, diff ignored list\n if (options.ignore) {\n matches = micromatch.not(matches, options.ignore, options);\n }\n\n return options.nodupes !== false ? utils.unique(matches) : matches;\n};\n\n/**\n * Returns true if the specified `string` matches the given glob `pattern`.\n *\n * ```js\n * var mm = require('micromatch');\n * mm.isMatch(string, pattern[, options]);\n *\n * console.log(mm.isMatch('a.a', '*.a'));\n * //=> true\n * console.log(mm.isMatch('a.b', '*.a'));\n * //=> false\n * ```\n * @param {String} `string` String to match\n * @param {String} `pattern` Glob pattern to use for matching.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Boolean} Returns true if the string matches the glob pattern.\n * @api public\n */\n\nmicromatch.isMatch = function(str, pattern, options) {\n if (typeof str !== 'string') {\n throw new TypeError('expected a string: \"' + util.inspect(str) + '\"');\n }\n\n if (isEmptyString(str) || isEmptyString(pattern)) {\n return false;\n }\n\n var equals = utils.equalsPattern(options);\n if (equals(str)) {\n return true;\n }\n\n var isMatch = memoize('isMatch', pattern, options, micromatch.matcher);\n return isMatch(str);\n};\n\n/**\n * Returns true if some of the strings in the given `list` match any of the\n * given glob `patterns`.\n *\n * ```js\n * var mm = require('micromatch');\n * mm.some(list, patterns[, options]);\n *\n * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));\n * // true\n * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));\n * // false\n * ```\n * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.\n * @param {String|Array} `patterns` One or more glob patterns to use for matching.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Boolean} Returns true if any patterns match `str`\n * @api public\n */\n\nmicromatch.some = function(list, patterns, options) {\n if (typeof list === 'string') {\n list = [list];\n }\n for (var i = 0; i < list.length; i++) {\n if (micromatch(list[i], patterns, options).length === 1) {\n return true;\n }\n }\n return false;\n};\n\n/**\n * Returns true if every string in the given `list` matches\n * any of the given glob `patterns`.\n *\n * ```js\n * var mm = require('micromatch');\n * mm.every(list, patterns[, options]);\n *\n * console.log(mm.every('foo.js', ['foo.js']));\n * // true\n * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));\n * // true\n * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));\n * // false\n * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));\n * // false\n * ```\n * @param {String|Array} `list` The string or array of strings to test.\n * @param {String|Array} `patterns` One or more glob patterns to use for matching.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Boolean} Returns true if any patterns match `str`\n * @api public\n */\n\nmicromatch.every = function(list, patterns, options) {\n if (typeof list === 'string') {\n list = [list];\n }\n for (var i = 0; i < list.length; i++) {\n if (micromatch(list[i], patterns, options).length !== 1) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Returns true if **any** of the given glob `patterns`\n * match the specified `string`.\n *\n * ```js\n * var mm = require('micromatch');\n * mm.any(string, patterns[, options]);\n *\n * console.log(mm.any('a.a', ['b.*', '*.a']));\n * //=> true\n * console.log(mm.any('a.a', 'b.*'));\n * //=> false\n * ```\n * @param {String|Array} `str` The string to test.\n * @param {String|Array} `patterns` One or more glob patterns to use for matching.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Boolean} Returns true if any patterns match `str`\n * @api public\n */\n\nmicromatch.any = function(str, patterns, options) {\n if (typeof str !== 'string') {\n throw new TypeError('expected a string: \"' + util.inspect(str) + '\"');\n }\n\n if (isEmptyString(str) || isEmptyString(patterns)) {\n return false;\n }\n\n if (typeof patterns === 'string') {\n patterns = [patterns];\n }\n\n for (var i = 0; i < patterns.length; i++) {\n if (micromatch.isMatch(str, patterns[i], options)) {\n return true;\n }\n }\n return false;\n};\n\n/**\n * Returns true if **all** of the given `patterns` match\n * the specified string.\n *\n * ```js\n * var mm = require('micromatch');\n * mm.all(string, patterns[, options]);\n *\n * console.log(mm.all('foo.js', ['foo.js']));\n * // true\n *\n * console.log(mm.all('foo.js', ['*.js', '!foo.js']));\n * // false\n *\n * console.log(mm.all('foo.js', ['*.js', 'foo.js']));\n * // true\n *\n * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));\n * // true\n * ```\n * @param {String|Array} `str` The string to test.\n * @param {String|Array} `patterns` One or more glob patterns to use for matching.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Boolean} Returns true if any patterns match `str`\n * @api public\n */\n\nmicromatch.all = function(str, patterns, options) {\n if (typeof str !== 'string') {\n throw new TypeError('expected a string: \"' + util.inspect(str) + '\"');\n }\n if (typeof patterns === 'string') {\n patterns = [patterns];\n }\n for (var i = 0; i < patterns.length; i++) {\n if (!micromatch.isMatch(str, patterns[i], options)) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Returns a list of strings that _**do not match any**_ of the given `patterns`.\n *\n * ```js\n * var mm = require('micromatch');\n * mm.not(list, patterns[, options]);\n *\n * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));\n * //=> ['b.b', 'c.c']\n * ```\n * @param {Array} `list` Array of strings to match.\n * @param {String|Array} `patterns` One or more glob pattern to use for matching.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Array} Returns an array of strings that **do not match** the given patterns.\n * @api public\n */\n\nmicromatch.not = function(list, patterns, options) {\n var opts = extend({}, options);\n var ignore = opts.ignore;\n delete opts.ignore;\n\n var unixify = utils.unixify(opts);\n list = utils.arrayify(list).map(unixify);\n\n var matches = utils.diff(list, micromatch(list, patterns, opts));\n if (ignore) {\n matches = utils.diff(matches, micromatch(list, ignore));\n }\n\n return opts.nodupes !== false ? utils.unique(matches) : matches;\n};\n\n/**\n * Returns true if the given `string` contains the given pattern. Similar\n * to [.isMatch](#isMatch) but the pattern can match any part of the string.\n *\n * ```js\n * var mm = require('micromatch');\n * mm.contains(string, pattern[, options]);\n *\n * console.log(mm.contains('aa/bb/cc', '*b'));\n * //=> true\n * console.log(mm.contains('aa/bb/cc', '*d'));\n * //=> false\n * ```\n * @param {String} `str` The string to match.\n * @param {String|Array} `patterns` Glob pattern to use for matching.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Boolean} Returns true if the patter matches any part of `str`.\n * @api public\n */\n\nmicromatch.contains = function(str, patterns, options) {\n if (typeof str !== 'string') {\n throw new TypeError('expected a string: \"' + util.inspect(str) + '\"');\n }\n\n if (typeof patterns === 'string') {\n if (isEmptyString(str) || isEmptyString(patterns)) {\n return false;\n }\n\n var equals = utils.equalsPattern(patterns, options);\n if (equals(str)) {\n return true;\n }\n var contains = utils.containsPattern(patterns, options);\n if (contains(str)) {\n return true;\n }\n }\n\n var opts = extend({}, options, {contains: true});\n return micromatch.any(str, patterns, opts);\n};\n\n/**\n * Returns true if the given pattern and options should enable\n * the `matchBase` option.\n * @return {Boolean}\n * @api private\n */\n\nmicromatch.matchBase = function(pattern, options) {\n if (pattern && pattern.indexOf('/') !== -1 || !options) return false;\n return options.basename === true || options.matchBase === true;\n};\n\n/**\n * Filter the keys of the given object with the given `glob` pattern\n * and `options`. Does not attempt to match nested keys. If you need this feature,\n * use [glob-object][] instead.\n *\n * ```js\n * var mm = require('micromatch');\n * mm.matchKeys(object, patterns[, options]);\n *\n * var obj = { aa: 'a', ab: 'b', ac: 'c' };\n * console.log(mm.matchKeys(obj, '*b'));\n * //=> { ab: 'b' }\n * ```\n * @param {Object} `object` The object with keys to filter.\n * @param {String|Array} `patterns` One or more glob patterns to use for matching.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Object} Returns an object with only keys that match the given patterns.\n * @api public\n */\n\nmicromatch.matchKeys = function(obj, patterns, options) {\n if (!utils.isObject(obj)) {\n throw new TypeError('expected the first argument to be an object');\n }\n var keys = micromatch(Object.keys(obj), patterns, options);\n return utils.pick(obj, keys);\n};\n\n/**\n * Returns a memoized matcher function from the given glob `pattern` and `options`.\n * The returned function takes a string to match as its only argument and returns\n * true if the string is a match.\n *\n * ```js\n * var mm = require('micromatch');\n * mm.matcher(pattern[, options]);\n *\n * var isMatch = mm.matcher('*.!(*a)');\n * console.log(isMatch('a.a'));\n * //=> false\n * console.log(isMatch('a.b'));\n * //=> true\n * ```\n * @param {String} `pattern` Glob pattern\n * @param {Object} `options` See available [options](#options) for changing how matches are performed.\n * @return {Function} Returns a matcher function.\n * @api public\n */\n\nmicromatch.matcher = function matcher(pattern, options) {\n if (Array.isArray(pattern)) {\n return compose(pattern, options, matcher);\n }\n\n // if pattern is a regex\n if (pattern instanceof RegExp) {\n return test(pattern);\n }\n\n // if pattern is invalid\n if (!utils.isString(pattern)) {\n throw new TypeError('expected pattern to be an array, string or regex');\n }\n\n // if pattern is a non-glob string\n if (!utils.hasSpecialChars(pattern)) {\n if (options && options.nocase === true) {\n pattern = pattern.toLowerCase();\n }\n return utils.matchPath(pattern, options);\n }\n\n // if pattern is a glob string\n var re = micromatch.makeRe(pattern, options);\n\n // if `options.matchBase` or `options.basename` is defined\n if (micromatch.matchBase(pattern, options)) {\n return utils.matchBasename(re, options);\n }\n\n function test(regex) {\n var equals = utils.equalsPattern(options);\n var unixify = utils.unixify(options);\n\n return function(str) {\n if (equals(str)) {\n return true;\n }\n\n if (regex.test(unixify(str))) {\n return true;\n }\n return false;\n };\n }\n\n var fn = test(re);\n Object.defineProperty(fn, 'result', {\n configurable: true,\n enumerable: false,\n value: re.result\n });\n return fn;\n};\n\n/**\n * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.\n *\n * ```js\n * var mm = require('micromatch');\n * mm.capture(pattern, string[, options]);\n *\n * console.log(mm.capture('test/*.js', 'test/foo.js'));\n * //=> ['foo']\n * console.log(mm.capture('test/*.js', 'foo/bar.css'));\n * //=> null\n * ```\n * @param {String} `pattern` Glob pattern to use for matching.\n * @param {String} `string` String to match\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`.\n * @api public\n */\n\nmicromatch.capture = function(pattern, str, options) {\n var re = micromatch.makeRe(pattern, extend({capture: true}, options));\n var unixify = utils.unixify(options);\n\n function match() {\n return function(string) {\n var match = re.exec(unixify(string));\n if (!match) {\n return null;\n }\n\n return match.slice(1);\n };\n }\n\n var capture = memoize('capture', pattern, options, match);\n return capture(str);\n};\n\n/**\n * Create a regular expression from the given glob `pattern`.\n *\n * ```js\n * var mm = require('micromatch');\n * mm.makeRe(pattern[, options]);\n *\n * console.log(mm.makeRe('*.js'));\n * //=> /^(?:(\\.[\\\\\\/])?(?!\\.)(?=.)[^\\/]*?\\.js)$/\n * ```\n * @param {String} `pattern` A glob pattern to convert to regex.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed.\n * @return {RegExp} Returns a regex created from the given pattern.\n * @api public\n */\n\nmicromatch.makeRe = function(pattern, options) {\n if (typeof pattern !== 'string') {\n throw new TypeError('expected pattern to be a string');\n }\n\n if (pattern.length > MAX_LENGTH) {\n throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters');\n }\n\n function makeRe() {\n var result = micromatch.create(pattern, options);\n var ast_array = [];\n var output = result.map(function(obj) {\n obj.ast.state = obj.state;\n ast_array.push(obj.ast);\n return obj.output;\n });\n\n var regex = toRegex(output.join('|'), options);\n Object.defineProperty(regex, 'result', {\n configurable: true,\n enumerable: false,\n value: ast_array\n });\n return regex;\n }\n\n return memoize('makeRe', pattern, options, makeRe);\n};\n\n/**\n * Expand the given brace `pattern`.\n *\n * ```js\n * var mm = require('micromatch');\n * console.log(mm.braces('foo/{a,b}/bar'));\n * //=> ['foo/(a|b)/bar']\n *\n * console.log(mm.braces('foo/{a,b}/bar', {expand: true}));\n * //=> ['foo/(a|b)/bar']\n * ```\n * @param {String} `pattern` String with brace pattern to expand.\n * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.\n * @return {Array}\n * @api public\n */\n\nmicromatch.braces = function(pattern, options) {\n if (typeof pattern !== 'string' && !Array.isArray(pattern)) {\n throw new TypeError('expected pattern to be an array or string');\n }\n\n function expand() {\n if (options && options.nobrace === true || !/\\{.*\\}/.test(pattern)) {\n return utils.arrayify(pattern);\n }\n return braces(pattern, options);\n }\n\n return memoize('braces', pattern, options, expand);\n};\n\n/**\n * Proxy to the [micromatch.braces](#method), for parity with\n * minimatch.\n */\n\nmicromatch.braceExpand = function(pattern, options) {\n var opts = extend({}, options, {expand: true});\n return micromatch.braces(pattern, opts);\n};\n\n/**\n * Parses the given glob `pattern` and returns an array of abstract syntax\n * trees (ASTs), with the compiled `output` and optional source `map` on\n * each AST.\n *\n * ```js\n * var mm = require('micromatch');\n * mm.create(pattern[, options]);\n *\n * console.log(mm.create('abc/*.js'));\n * // [{ options: { source: 'string', sourcemap: true },\n * // state: {},\n * // compilers:\n * // { ... },\n * // output: '(\\\\.[\\\\\\\\\\\\/])?abc\\\\/(?!\\\\.)(?=.)[^\\\\/]*?\\\\.js',\n * // ast:\n * // { type: 'root',\n * // errors: [],\n * // nodes:\n * // [ ... ],\n * // dot: false,\n * // input: 'abc/*.js' },\n * // parsingErrors: [],\n * // map:\n * // { version: 3,\n * // sources: [ 'string' ],\n * // names: [],\n * // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE',\n * // sourcesContent: [ 'abc/*.js' ] },\n * // position: { line: 1, column: 28 },\n * // content: {},\n * // files: {},\n * // idx: 6 }]\n * ```\n * @param {String} `pattern` Glob pattern to parse and compile.\n * @param {Object} `options` Any [options](#options) to change how parsing and compiling is performed.\n * @return {Object} Returns an object with the parsed AST, compiled string and optional source map.\n * @api public\n */\n\nmicromatch.create = function(pattern, options) {\n return memoize('create', pattern, options, function() {\n function create(str, opts) {\n return micromatch.compile(micromatch.parse(str, opts), opts);\n }\n\n pattern = micromatch.braces(pattern, options);\n var len = pattern.length;\n var idx = -1;\n var res = [];\n\n while (++idx < len) {\n res.push(create(pattern[idx], options));\n }\n return res;\n });\n};\n\n/**\n * Parse the given `str` with the given `options`.\n *\n * ```js\n * var mm = require('micromatch');\n * mm.parse(pattern[, options]);\n *\n * var ast = mm.parse('a/{b,c}/d');\n * console.log(ast);\n * // { type: 'root',\n * // errors: [],\n * // input: 'a/{b,c}/d',\n * // nodes:\n * // [ { type: 'bos', val: '' },\n * // { type: 'text', val: 'a/' },\n * // { type: 'brace',\n * // nodes:\n * // [ { type: 'brace.open', val: '{' },\n * // { type: 'text', val: 'b,c' },\n * // { type: 'brace.close', val: '}' } ] },\n * // { type: 'text', val: '/d' },\n * // { type: 'eos', val: '' } ] }\n * ```\n * @param {String} `str`\n * @param {Object} `options`\n * @return {Object} Returns an AST\n * @api public\n */\n\nmicromatch.parse = function(pattern, options) {\n if (typeof pattern !== 'string') {\n throw new TypeError('expected a string');\n }\n\n function parse() {\n var snapdragon = utils.instantiate(null, options);\n parsers(snapdragon, options);\n\n var ast = snapdragon.parse(pattern, options);\n utils.define(ast, 'snapdragon', snapdragon);\n ast.input = pattern;\n return ast;\n }\n\n return memoize('parse', pattern, options, parse);\n};\n\n/**\n * Compile the given `ast` or string with the given `options`.\n *\n * ```js\n * var mm = require('micromatch');\n * mm.compile(ast[, options]);\n *\n * var ast = mm.parse('a/{b,c}/d');\n * console.log(mm.compile(ast));\n * // { options: { source: 'string' },\n * // state: {},\n * // compilers:\n * // { eos: [Function],\n * // noop: [Function],\n * // bos: [Function],\n * // brace: [Function],\n * // 'brace.open': [Function],\n * // text: [Function],\n * // 'brace.close': [Function] },\n * // output: [ 'a/(b|c)/d' ],\n * // ast:\n * // { ... },\n * // parsingErrors: [] }\n * ```\n * @param {Object|String} `ast`\n * @param {Object} `options`\n * @return {Object} Returns an object that has an `output` property with the compiled string.\n * @api public\n */\n\nmicromatch.compile = function(ast, options) {\n if (typeof ast === 'string') {\n ast = micromatch.parse(ast, options);\n }\n\n return memoize('compile', ast.input, options, function() {\n var snapdragon = utils.instantiate(ast, options);\n compilers(snapdragon, options);\n return snapdragon.compile(ast, options);\n });\n};\n\n/**\n * Clear the regex cache.\n *\n * ```js\n * mm.clearCache();\n * ```\n * @api public\n */\n\nmicromatch.clearCache = function() {\n micromatch.cache.caches = {};\n};\n\n/**\n * Returns true if the given value is effectively an empty string\n */\n\nfunction isEmptyString(val) {\n return String(val) === '' || String(val) === './';\n}\n\n/**\n * Compose a matcher function with the given patterns.\n * This allows matcher functions to be compiled once and\n * called multiple times.\n */\n\nfunction compose(patterns, options, matcher) {\n var matchers;\n\n return memoize('compose', String(patterns), options, function() {\n return function(file) {\n // delay composition until it's invoked the first time,\n // after that it won't be called again\n if (!matchers) {\n matchers = [];\n for (var i = 0; i < patterns.length; i++) {\n matchers.push(matcher(patterns[i], options));\n }\n }\n\n var len = matchers.length;\n while (len--) {\n if (matchers[len](file) === true) {\n return true;\n }\n }\n return false;\n };\n });\n}\n\n/**\n * Memoize a generated regex or function. A unique key is generated\n * from the `type` (usually method name), the `pattern`, and\n * user-defined options.\n */\n\nfunction memoize(type, pattern, options, fn) {\n var key = utils.createKey(type + '=' + pattern, options);\n\n if (options && options.cache === false) {\n return fn(pattern, options);\n }\n\n if (cache.has(type, key)) {\n return cache.get(type, key);\n }\n\n var val = fn(pattern, options);\n cache.set(type, key, val);\n return val;\n}\n\n/**\n * Expose compiler, parser and cache on `micromatch`\n */\n\nmicromatch.compilers = compilers;\nmicromatch.parsers = parsers;\nmicromatch.caches = cache.caches;\n\n/**\n * Expose `micromatch`\n * @type {Function}\n */\n\nmodule.exports = micromatch;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/micromatch/index.js?"); + +/***/ }), + +/***/ "./node_modules/micromatch/lib/cache.js": +/*!**********************************************!*\ + !*** ./node_modules/micromatch/lib/cache.js ***! + \**********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("module.exports = new (__webpack_require__(/*! fragment-cache */ \"./node_modules/fragment-cache/index.js\"))();\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/micromatch/lib/cache.js?"); + +/***/ }), + +/***/ "./node_modules/micromatch/lib/compilers.js": +/*!**************************************************!*\ + !*** ./node_modules/micromatch/lib/compilers.js ***! + \**************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar nanomatch = __webpack_require__(/*! nanomatch */ \"./node_modules/nanomatch/index.js\");\nvar extglob = __webpack_require__(/*! extglob */ \"./node_modules/extglob/index.js\");\n\nmodule.exports = function(snapdragon) {\n var compilers = snapdragon.compiler.compilers;\n var opts = snapdragon.options;\n\n // register nanomatch compilers\n snapdragon.use(nanomatch.compilers);\n\n // get references to some specific nanomatch compilers before they\n // are overridden by the extglob and/or custom compilers\n var escape = compilers.escape;\n var qmark = compilers.qmark;\n var slash = compilers.slash;\n var star = compilers.star;\n var text = compilers.text;\n var plus = compilers.plus;\n var dot = compilers.dot;\n\n // register extglob compilers or escape exglobs if disabled\n if (opts.extglob === false || opts.noext === true) {\n snapdragon.compiler.use(escapeExtglobs);\n } else {\n snapdragon.use(extglob.compilers);\n }\n\n snapdragon.use(function() {\n this.options.star = this.options.star || function(/*node*/) {\n return '[^\\\\\\\\/]*?';\n };\n });\n\n // custom micromatch compilers\n snapdragon.compiler\n\n // reset referenced compiler\n .set('dot', dot)\n .set('escape', escape)\n .set('plus', plus)\n .set('slash', slash)\n .set('qmark', qmark)\n .set('star', star)\n .set('text', text);\n};\n\nfunction escapeExtglobs(compiler) {\n compiler.set('paren', function(node) {\n var val = '';\n visit(node, function(tok) {\n if (tok.val) val += (/^\\W/.test(tok.val) ? '\\\\' : '') + tok.val;\n });\n return this.emit(val, node);\n });\n\n /**\n * Visit `node` with the given `fn`\n */\n\n function visit(node, fn) {\n return node.nodes ? mapVisit(node.nodes, fn) : fn(node);\n }\n\n /**\n * Map visit over array of `nodes`.\n */\n\n function mapVisit(nodes, fn) {\n var len = nodes.length;\n var idx = -1;\n while (++idx < len) {\n visit(nodes[idx], fn);\n }\n }\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/micromatch/lib/compilers.js?"); + +/***/ }), + +/***/ "./node_modules/micromatch/lib/parsers.js": +/*!************************************************!*\ + !*** ./node_modules/micromatch/lib/parsers.js ***! + \************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar extglob = __webpack_require__(/*! extglob */ \"./node_modules/extglob/index.js\");\nvar nanomatch = __webpack_require__(/*! nanomatch */ \"./node_modules/nanomatch/index.js\");\nvar regexNot = __webpack_require__(/*! regex-not */ \"./node_modules/regex-not/index.js\");\nvar toRegex = __webpack_require__(/*! to-regex */ \"./node_modules/to-regex/index.js\");\nvar not;\n\n/**\n * Characters to use in negation regex (we want to \"not\" match\n * characters that are matched by other parsers)\n */\n\nvar TEXT = '([!@*?+]?\\\\(|\\\\)|\\\\[:?(?=.*?:?\\\\])|:?\\\\]|[*+?!^$.\\\\\\\\/])+';\nvar createNotRegex = function(opts) {\n return not || (not = textRegex(TEXT));\n};\n\n/**\n * Parsers\n */\n\nmodule.exports = function(snapdragon) {\n var parsers = snapdragon.parser.parsers;\n\n // register nanomatch parsers\n snapdragon.use(nanomatch.parsers);\n\n // get references to some specific nanomatch parsers before they\n // are overridden by the extglob and/or parsers\n var escape = parsers.escape;\n var slash = parsers.slash;\n var qmark = parsers.qmark;\n var plus = parsers.plus;\n var star = parsers.star;\n var dot = parsers.dot;\n\n // register extglob parsers\n snapdragon.use(extglob.parsers);\n\n // custom micromatch parsers\n snapdragon.parser\n .use(function() {\n // override \"notRegex\" created in nanomatch parser\n this.notRegex = /^\\!+(?!\\()/;\n })\n // reset the referenced parsers\n .capture('escape', escape)\n .capture('slash', slash)\n .capture('qmark', qmark)\n .capture('star', star)\n .capture('plus', plus)\n .capture('dot', dot)\n\n /**\n * Override `text` parser\n */\n\n .capture('text', function() {\n if (this.isInside('bracket')) return;\n var pos = this.position();\n var m = this.match(createNotRegex(this.options));\n if (!m || !m[0]) return;\n\n // escape regex boundary characters and simple brackets\n var val = m[0].replace(/([[\\]^$])/g, '\\\\$1');\n\n return pos({\n type: 'text',\n val: val\n });\n });\n};\n\n/**\n * Create text regex\n */\n\nfunction textRegex(pattern) {\n var notStr = regexNot.create(pattern, {contains: true, strictClose: false});\n var prefix = '(?:[\\\\^]|\\\\\\\\|';\n return toRegex(prefix + notStr + ')', {strictClose: false});\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/micromatch/lib/parsers.js?"); + +/***/ }), + +/***/ "./node_modules/micromatch/lib/utils.js": +/*!**********************************************!*\ + !*** ./node_modules/micromatch/lib/utils.js ***! + \**********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar utils = module.exports;\nvar path = __webpack_require__(/*! path */ \"path\");\n\n/**\n * Module dependencies\n */\n\nvar Snapdragon = __webpack_require__(/*! snapdragon */ \"./node_modules/snapdragon/index.js\");\nutils.define = __webpack_require__(/*! define-property */ \"./node_modules/micromatch/node_modules/define-property/index.js\");\nutils.diff = __webpack_require__(/*! arr-diff */ \"./node_modules/arr-diff/index.js\");\nutils.extend = __webpack_require__(/*! extend-shallow */ \"./node_modules/micromatch/node_modules/extend-shallow/index.js\");\nutils.pick = __webpack_require__(/*! object.pick */ \"./node_modules/object.pick/index.js\");\nutils.typeOf = __webpack_require__(/*! kind-of */ \"./node_modules/kind-of/index.js\");\nutils.unique = __webpack_require__(/*! array-unique */ \"./node_modules/array-unique/index.js\");\n\n/**\n * Returns true if the platform is windows, or `path.sep` is `\\\\`.\n * This is defined as a function to allow `path.sep` to be set in unit tests,\n * or by the user, if there is a reason to do so.\n * @return {Boolean}\n */\n\nutils.isWindows = function() {\n return path.sep === '\\\\' || process.platform === 'win32';\n};\n\n/**\n * Get the `Snapdragon` instance to use\n */\n\nutils.instantiate = function(ast, options) {\n var snapdragon;\n // if an instance was created by `.parse`, use that instance\n if (utils.typeOf(ast) === 'object' && ast.snapdragon) {\n snapdragon = ast.snapdragon;\n // if the user supplies an instance on options, use that instance\n } else if (utils.typeOf(options) === 'object' && options.snapdragon) {\n snapdragon = options.snapdragon;\n // create a new instance\n } else {\n snapdragon = new Snapdragon(options);\n }\n\n utils.define(snapdragon, 'parse', function(str, options) {\n var parsed = Snapdragon.prototype.parse.apply(this, arguments);\n parsed.input = str;\n\n // escape unmatched brace/bracket/parens\n var last = this.parser.stack.pop();\n if (last && this.options.strictErrors !== true) {\n var open = last.nodes[0];\n var inner = last.nodes[1];\n if (last.type === 'bracket') {\n if (inner.val.charAt(0) === '[') {\n inner.val = '\\\\' + inner.val;\n }\n\n } else {\n open.val = '\\\\' + open.val;\n var sibling = open.parent.nodes[1];\n if (sibling.type === 'star') {\n sibling.loose = true;\n }\n }\n }\n\n // add non-enumerable parser reference\n utils.define(parsed, 'parser', this.parser);\n return parsed;\n });\n\n return snapdragon;\n};\n\n/**\n * Create the key to use for memoization. The key is generated\n * by iterating over the options and concatenating key-value pairs\n * to the pattern string.\n */\n\nutils.createKey = function(pattern, options) {\n if (utils.typeOf(options) !== 'object') {\n return pattern;\n }\n var val = pattern;\n var keys = Object.keys(options);\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n val += ';' + key + '=' + String(options[key]);\n }\n return val;\n};\n\n/**\n * Cast `val` to an array\n * @return {Array}\n */\n\nutils.arrayify = function(val) {\n if (typeof val === 'string') return [val];\n return val ? (Array.isArray(val) ? val : [val]) : [];\n};\n\n/**\n * Return true if `val` is a non-empty string\n */\n\nutils.isString = function(val) {\n return typeof val === 'string';\n};\n\n/**\n * Return true if `val` is a non-empty string\n */\n\nutils.isObject = function(val) {\n return utils.typeOf(val) === 'object';\n};\n\n/**\n * Returns true if the given `str` has special characters\n */\n\nutils.hasSpecialChars = function(str) {\n return /(?:(?:(^|\\/)[!.])|[*?+()|\\[\\]{}]|[+@]\\()/.test(str);\n};\n\n/**\n * Escape regex characters in the given string\n */\n\nutils.escapeRegex = function(str) {\n return str.replace(/[-[\\]{}()^$|*+?.\\\\\\/\\s]/g, '\\\\$&');\n};\n\n/**\n * Normalize slashes in the given filepath.\n *\n * @param {String} `filepath`\n * @return {String}\n */\n\nutils.toPosixPath = function(str) {\n return str.replace(/\\\\+/g, '/');\n};\n\n/**\n * Strip backslashes before special characters in a string.\n *\n * @param {String} `str`\n * @return {String}\n */\n\nutils.unescape = function(str) {\n return utils.toPosixPath(str.replace(/\\\\(?=[*+?!.])/g, ''));\n};\n\n/**\n * Strip the prefix from a filepath\n * @param {String} `fp`\n * @return {String}\n */\n\nutils.stripPrefix = function(str) {\n if (str.charAt(0) !== '.') {\n return str;\n }\n var ch = str.charAt(1);\n if (utils.isSlash(ch)) {\n return str.slice(2);\n }\n return str;\n};\n\n/**\n * Returns true if the given str is an escaped or\n * unescaped path character\n */\n\nutils.isSlash = function(str) {\n return str === '/' || str === '\\\\/' || str === '\\\\' || str === '\\\\\\\\';\n};\n\n/**\n * Returns a function that returns true if the given\n * pattern matches or contains a `filepath`\n *\n * @param {String} `pattern`\n * @return {Function}\n */\n\nutils.matchPath = function(pattern, options) {\n return (options && options.contains)\n ? utils.containsPattern(pattern, options)\n : utils.equalsPattern(pattern, options);\n};\n\n/**\n * Returns true if the given (original) filepath or unixified path are equal\n * to the given pattern.\n */\n\nutils._equals = function(filepath, unixPath, pattern) {\n return pattern === filepath || pattern === unixPath;\n};\n\n/**\n * Returns true if the given (original) filepath or unixified path contain\n * the given pattern.\n */\n\nutils._contains = function(filepath, unixPath, pattern) {\n return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1;\n};\n\n/**\n * Returns a function that returns true if the given\n * pattern is the same as a given `filepath`\n *\n * @param {String} `pattern`\n * @return {Function}\n */\n\nutils.equalsPattern = function(pattern, options) {\n var unixify = utils.unixify(options);\n options = options || {};\n\n return function fn(filepath) {\n var equal = utils._equals(filepath, unixify(filepath), pattern);\n if (equal === true || options.nocase !== true) {\n return equal;\n }\n var lower = filepath.toLowerCase();\n return utils._equals(lower, unixify(lower), pattern);\n };\n};\n\n/**\n * Returns a function that returns true if the given\n * pattern contains a `filepath`\n *\n * @param {String} `pattern`\n * @return {Function}\n */\n\nutils.containsPattern = function(pattern, options) {\n var unixify = utils.unixify(options);\n options = options || {};\n\n return function(filepath) {\n var contains = utils._contains(filepath, unixify(filepath), pattern);\n if (contains === true || options.nocase !== true) {\n return contains;\n }\n var lower = filepath.toLowerCase();\n return utils._contains(lower, unixify(lower), pattern);\n };\n};\n\n/**\n * Returns a function that returns true if the given\n * regex matches the `filename` of a file path.\n *\n * @param {RegExp} `re` Matching regex\n * @return {Function}\n */\n\nutils.matchBasename = function(re) {\n return function(filepath) {\n return re.test(path.basename(filepath));\n };\n};\n\n/**\n * Determines the filepath to return based on the provided options.\n * @return {any}\n */\n\nutils.value = function(str, unixify, options) {\n if (options && options.unixify === false) {\n return str;\n }\n return unixify(str);\n};\n\n/**\n * Returns a function that normalizes slashes in a string to forward\n * slashes, strips `./` from beginning of paths, and optionally unescapes\n * special characters.\n * @return {Function}\n */\n\nutils.unixify = function(options) {\n options = options || {};\n return function(filepath) {\n if (utils.isWindows() || options.unixify === true) {\n filepath = utils.toPosixPath(filepath);\n }\n if (options.stripPrefix !== false) {\n filepath = utils.stripPrefix(filepath);\n }\n if (options.unescape === true) {\n filepath = utils.unescape(filepath);\n }\n return filepath;\n };\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/micromatch/lib/utils.js?"); + +/***/ }), + +/***/ "./node_modules/micromatch/node_modules/define-property/index.js": +/*!***********************************************************************!*\ + !*** ./node_modules/micromatch/node_modules/define-property/index.js ***! + \***********************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * define-property \n *\n * Copyright (c) 2015-2018, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar isobject = __webpack_require__(/*! isobject */ \"./node_modules/isobject/index.js\");\nvar isDescriptor = __webpack_require__(/*! is-descriptor */ \"./node_modules/is-descriptor/index.js\");\nvar define = (typeof Reflect !== 'undefined' && Reflect.defineProperty)\n ? Reflect.defineProperty\n : Object.defineProperty;\n\nmodule.exports = function defineProperty(obj, key, val) {\n if (!isobject(obj) && typeof obj !== 'function' && !Array.isArray(obj)) {\n throw new TypeError('expected an object, function, or array');\n }\n\n if (typeof key !== 'string') {\n throw new TypeError('expected \"key\" to be a string');\n }\n\n if (isDescriptor(val)) {\n define(obj, key, val);\n return obj;\n }\n\n define(obj, key, {\n configurable: true,\n enumerable: false,\n writable: true,\n value: val\n });\n\n return obj;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/micromatch/node_modules/define-property/index.js?"); + +/***/ }), + +/***/ "./node_modules/micromatch/node_modules/extend-shallow/index.js": +/*!**********************************************************************!*\ + !*** ./node_modules/micromatch/node_modules/extend-shallow/index.js ***! + \**********************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar isExtendable = __webpack_require__(/*! is-extendable */ \"./node_modules/micromatch/node_modules/is-extendable/index.js\");\nvar assignSymbols = __webpack_require__(/*! assign-symbols */ \"./node_modules/assign-symbols/index.js\");\n\nmodule.exports = Object.assign || function(obj/*, objects*/) {\n if (obj === null || typeof obj === 'undefined') {\n throw new TypeError('Cannot convert undefined or null to object');\n }\n if (!isObject(obj)) {\n obj = {};\n }\n for (var i = 1; i < arguments.length; i++) {\n var val = arguments[i];\n if (isString(val)) {\n val = toObject(val);\n }\n if (isObject(val)) {\n assign(obj, val);\n assignSymbols(obj, val);\n }\n }\n return obj;\n};\n\nfunction assign(a, b) {\n for (var key in b) {\n if (hasOwn(b, key)) {\n a[key] = b[key];\n }\n }\n}\n\nfunction isString(val) {\n return (val && typeof val === 'string');\n}\n\nfunction toObject(str) {\n var obj = {};\n for (var i in str) {\n obj[i] = str[i];\n }\n return obj;\n}\n\nfunction isObject(val) {\n return (val && typeof val === 'object') || isExtendable(val);\n}\n\n/**\n * Returns true if the given `key` is an own property of `obj`.\n */\n\nfunction hasOwn(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nfunction isEnum(obj, key) {\n return Object.prototype.propertyIsEnumerable.call(obj, key);\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/micromatch/node_modules/extend-shallow/index.js?"); + +/***/ }), + +/***/ "./node_modules/micromatch/node_modules/is-extendable/index.js": +/*!*********************************************************************!*\ + !*** ./node_modules/micromatch/node_modules/is-extendable/index.js ***! + \*********************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * is-extendable \n *\n * Copyright (c) 2015-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar isPlainObject = __webpack_require__(/*! is-plain-object */ \"./node_modules/is-plain-object/index.js\");\n\nmodule.exports = function isExtendable(val) {\n return isPlainObject(val) || typeof val === 'function' || Array.isArray(val);\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/micromatch/node_modules/is-extendable/index.js?"); + +/***/ }), + +/***/ "./node_modules/mixin-deep/index.js": +/*!******************************************!*\ + !*** ./node_modules/mixin-deep/index.js ***! + \******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar isExtendable = __webpack_require__(/*! is-extendable */ \"./node_modules/mixin-deep/node_modules/is-extendable/index.js\");\nvar forIn = __webpack_require__(/*! for-in */ \"./node_modules/for-in/index.js\");\n\nfunction mixinDeep(target, objects) {\n var len = arguments.length, i = 0;\n while (++i < len) {\n var obj = arguments[i];\n if (isObject(obj)) {\n forIn(obj, copy, target);\n }\n }\n return target;\n}\n\n/**\n * Copy properties from the source object to the\n * target object.\n *\n * @param {*} `val`\n * @param {String} `key`\n */\n\nfunction copy(val, key) {\n if (!isValidKey(key)) {\n return;\n }\n\n var obj = this[key];\n if (isObject(val) && isObject(obj)) {\n mixinDeep(obj, val);\n } else {\n this[key] = val;\n }\n}\n\n/**\n * Returns true if `val` is an object or function.\n *\n * @param {any} val\n * @return {Boolean}\n */\n\nfunction isObject(val) {\n return isExtendable(val) && !Array.isArray(val);\n}\n\n/**\n * Returns true if `key` is a valid key to use when extending objects.\n *\n * @param {String} `key`\n * @return {Boolean}\n */\n\nfunction isValidKey(key) {\n return key !== '__proto__' && key !== 'constructor' && key !== 'prototype';\n};\n\n/**\n * Expose `mixinDeep`\n */\n\nmodule.exports = mixinDeep;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/mixin-deep/index.js?"); + +/***/ }), + +/***/ "./node_modules/mixin-deep/node_modules/is-extendable/index.js": +/*!*********************************************************************!*\ + !*** ./node_modules/mixin-deep/node_modules/is-extendable/index.js ***! + \*********************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * is-extendable \n *\n * Copyright (c) 2015-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar isPlainObject = __webpack_require__(/*! is-plain-object */ \"./node_modules/is-plain-object/index.js\");\n\nmodule.exports = function isExtendable(val) {\n return isPlainObject(val) || typeof val === 'function' || Array.isArray(val);\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/mixin-deep/node_modules/is-extendable/index.js?"); + +/***/ }), + +/***/ "./node_modules/ms/index.js": +/*!**********************************!*\ + !*** ./node_modules/ms/index.js ***! + \**********************************/ +/***/ ((module) => { + +eval("/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isNaN(val) === false) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^((?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n if (ms >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (ms >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (ms >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (ms >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n return plural(ms, d, 'day') ||\n plural(ms, h, 'hour') ||\n plural(ms, m, 'minute') ||\n plural(ms, s, 'second') ||\n ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, n, name) {\n if (ms < n) {\n return;\n }\n if (ms < n * 1.5) {\n return Math.floor(ms / n) + ' ' + name;\n }\n return Math.ceil(ms / n) + ' ' + name + 's';\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/ms/index.js?"); + +/***/ }), + +/***/ "./node_modules/nanomatch/index.js": +/*!*****************************************!*\ + !*** ./node_modules/nanomatch/index.js ***! + \*****************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\n/**\n * Module dependencies\n */\n\nvar util = __webpack_require__(/*! util */ \"util\");\nvar toRegex = __webpack_require__(/*! to-regex */ \"./node_modules/to-regex/index.js\");\nvar extend = __webpack_require__(/*! extend-shallow */ \"./node_modules/nanomatch/node_modules/extend-shallow/index.js\");\n\n/**\n * Local dependencies\n */\n\nvar compilers = __webpack_require__(/*! ./lib/compilers */ \"./node_modules/nanomatch/lib/compilers.js\");\nvar parsers = __webpack_require__(/*! ./lib/parsers */ \"./node_modules/nanomatch/lib/parsers.js\");\nvar cache = __webpack_require__(/*! ./lib/cache */ \"./node_modules/nanomatch/lib/cache.js\");\nvar utils = __webpack_require__(/*! ./lib/utils */ \"./node_modules/nanomatch/lib/utils.js\");\nvar MAX_LENGTH = 1024 * 64;\n\n/**\n * The main function takes a list of strings and one or more\n * glob patterns to use for matching.\n *\n * ```js\n * var nm = require('nanomatch');\n * nm(list, patterns[, options]);\n *\n * console.log(nm(['a.js', 'a.txt'], ['*.js']));\n * //=> [ 'a.js' ]\n * ```\n * @param {Array} `list` A list of strings to match\n * @param {String|Array} `patterns` One or more glob patterns to use for matching.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Array} Returns an array of matches\n * @summary false\n * @api public\n */\n\nfunction nanomatch(list, patterns, options) {\n patterns = utils.arrayify(patterns);\n list = utils.arrayify(list);\n\n var len = patterns.length;\n if (list.length === 0 || len === 0) {\n return [];\n }\n\n if (len === 1) {\n return nanomatch.match(list, patterns[0], options);\n }\n\n var negated = false;\n var omit = [];\n var keep = [];\n var idx = -1;\n\n while (++idx < len) {\n var pattern = patterns[idx];\n\n if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) {\n omit.push.apply(omit, nanomatch.match(list, pattern.slice(1), options));\n negated = true;\n } else {\n keep.push.apply(keep, nanomatch.match(list, pattern, options));\n }\n }\n\n // minimatch.match parity\n if (negated && keep.length === 0) {\n if (options && options.unixify === false) {\n keep = list.slice();\n } else {\n var unixify = utils.unixify(options);\n for (var i = 0; i < list.length; i++) {\n keep.push(unixify(list[i]));\n }\n }\n }\n\n var matches = utils.diff(keep, omit);\n if (!options || options.nodupes !== false) {\n return utils.unique(matches);\n }\n\n return matches;\n}\n\n/**\n * Similar to the main function, but `pattern` must be a string.\n *\n * ```js\n * var nm = require('nanomatch');\n * nm.match(list, pattern[, options]);\n *\n * console.log(nm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a'));\n * //=> ['a.a', 'a.aa']\n * ```\n * @param {Array} `list` Array of strings to match\n * @param {String} `pattern` Glob pattern to use for matching.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Array} Returns an array of matches\n * @api public\n */\n\nnanomatch.match = function(list, pattern, options) {\n if (Array.isArray(pattern)) {\n throw new TypeError('expected pattern to be a string');\n }\n\n var unixify = utils.unixify(options);\n var isMatch = memoize('match', pattern, options, nanomatch.matcher);\n var matches = [];\n\n list = utils.arrayify(list);\n var len = list.length;\n var idx = -1;\n\n while (++idx < len) {\n var ele = list[idx];\n if (ele === pattern || isMatch(ele)) {\n matches.push(utils.value(ele, unixify, options));\n }\n }\n\n // if no options were passed, uniquify results and return\n if (typeof options === 'undefined') {\n return utils.unique(matches);\n }\n\n if (matches.length === 0) {\n if (options.failglob === true) {\n throw new Error('no matches found for \"' + pattern + '\"');\n }\n if (options.nonull === true || options.nullglob === true) {\n return [options.unescape ? utils.unescape(pattern) : pattern];\n }\n }\n\n // if `opts.ignore` was defined, diff ignored list\n if (options.ignore) {\n matches = nanomatch.not(matches, options.ignore, options);\n }\n\n return options.nodupes !== false ? utils.unique(matches) : matches;\n};\n\n/**\n * Returns true if the specified `string` matches the given glob `pattern`.\n *\n * ```js\n * var nm = require('nanomatch');\n * nm.isMatch(string, pattern[, options]);\n *\n * console.log(nm.isMatch('a.a', '*.a'));\n * //=> true\n * console.log(nm.isMatch('a.b', '*.a'));\n * //=> false\n * ```\n * @param {String} `string` String to match\n * @param {String} `pattern` Glob pattern to use for matching.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Boolean} Returns true if the string matches the glob pattern.\n * @api public\n */\n\nnanomatch.isMatch = function(str, pattern, options) {\n if (typeof str !== 'string') {\n throw new TypeError('expected a string: \"' + util.inspect(str) + '\"');\n }\n\n if (utils.isEmptyString(str) || utils.isEmptyString(pattern)) {\n return false;\n }\n\n var equals = utils.equalsPattern(options);\n if (equals(str)) {\n return true;\n }\n\n var isMatch = memoize('isMatch', pattern, options, nanomatch.matcher);\n return isMatch(str);\n};\n\n/**\n * Returns true if some of the elements in the given `list` match any of the\n * given glob `patterns`.\n *\n * ```js\n * var nm = require('nanomatch');\n * nm.some(list, patterns[, options]);\n *\n * console.log(nm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));\n * // true\n * console.log(nm.some(['foo.js'], ['*.js', '!foo.js']));\n * // false\n * ```\n * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.\n * @param {String|Array} `patterns` One or more glob patterns to use for matching.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Boolean} Returns true if any patterns match `str`\n * @api public\n */\n\nnanomatch.some = function(list, patterns, options) {\n if (typeof list === 'string') {\n list = [list];\n }\n\n for (var i = 0; i < list.length; i++) {\n if (nanomatch(list[i], patterns, options).length === 1) {\n return true;\n }\n }\n\n return false;\n};\n\n/**\n * Returns true if every element in the given `list` matches\n * at least one of the given glob `patterns`.\n *\n * ```js\n * var nm = require('nanomatch');\n * nm.every(list, patterns[, options]);\n *\n * console.log(nm.every('foo.js', ['foo.js']));\n * // true\n * console.log(nm.every(['foo.js', 'bar.js'], ['*.js']));\n * // true\n * console.log(nm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));\n * // false\n * console.log(nm.every(['foo.js'], ['*.js', '!foo.js']));\n * // false\n * ```\n * @param {String|Array} `list` The string or array of strings to test.\n * @param {String|Array} `patterns` One or more glob patterns to use for matching.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Boolean} Returns true if any patterns match `str`\n * @api public\n */\n\nnanomatch.every = function(list, patterns, options) {\n if (typeof list === 'string') {\n list = [list];\n }\n\n for (var i = 0; i < list.length; i++) {\n if (nanomatch(list[i], patterns, options).length !== 1) {\n return false;\n }\n }\n\n return true;\n};\n\n/**\n * Returns true if **any** of the given glob `patterns`\n * match the specified `string`.\n *\n * ```js\n * var nm = require('nanomatch');\n * nm.any(string, patterns[, options]);\n *\n * console.log(nm.any('a.a', ['b.*', '*.a']));\n * //=> true\n * console.log(nm.any('a.a', 'b.*'));\n * //=> false\n * ```\n * @param {String|Array} `str` The string to test.\n * @param {String|Array} `patterns` One or more glob patterns to use for matching.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Boolean} Returns true if any patterns match `str`\n * @api public\n */\n\nnanomatch.any = function(str, patterns, options) {\n if (typeof str !== 'string') {\n throw new TypeError('expected a string: \"' + util.inspect(str) + '\"');\n }\n\n if (utils.isEmptyString(str) || utils.isEmptyString(patterns)) {\n return false;\n }\n\n if (typeof patterns === 'string') {\n patterns = [patterns];\n }\n\n for (var i = 0; i < patterns.length; i++) {\n if (nanomatch.isMatch(str, patterns[i], options)) {\n return true;\n }\n }\n return false;\n};\n\n/**\n * Returns true if **all** of the given `patterns`\n * match the specified string.\n *\n * ```js\n * var nm = require('nanomatch');\n * nm.all(string, patterns[, options]);\n *\n * console.log(nm.all('foo.js', ['foo.js']));\n * // true\n *\n * console.log(nm.all('foo.js', ['*.js', '!foo.js']));\n * // false\n *\n * console.log(nm.all('foo.js', ['*.js', 'foo.js']));\n * // true\n *\n * console.log(nm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));\n * // true\n * ```\n * @param {String|Array} `str` The string to test.\n * @param {String|Array} `patterns` One or more glob patterns to use for matching.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Boolean} Returns true if any patterns match `str`\n * @api public\n */\n\nnanomatch.all = function(str, patterns, options) {\n if (typeof str !== 'string') {\n throw new TypeError('expected a string: \"' + util.inspect(str) + '\"');\n }\n\n if (typeof patterns === 'string') {\n patterns = [patterns];\n }\n\n for (var i = 0; i < patterns.length; i++) {\n if (!nanomatch.isMatch(str, patterns[i], options)) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Returns a list of strings that _**do not match any**_ of the given `patterns`.\n *\n * ```js\n * var nm = require('nanomatch');\n * nm.not(list, patterns[, options]);\n *\n * console.log(nm.not(['a.a', 'b.b', 'c.c'], '*.a'));\n * //=> ['b.b', 'c.c']\n * ```\n * @param {Array} `list` Array of strings to match.\n * @param {String|Array} `patterns` One or more glob pattern to use for matching.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Array} Returns an array of strings that **do not match** the given patterns.\n * @api public\n */\n\nnanomatch.not = function(list, patterns, options) {\n var opts = extend({}, options);\n var ignore = opts.ignore;\n delete opts.ignore;\n\n list = utils.arrayify(list);\n\n var matches = utils.diff(list, nanomatch(list, patterns, opts));\n if (ignore) {\n matches = utils.diff(matches, nanomatch(list, ignore));\n }\n\n return opts.nodupes !== false ? utils.unique(matches) : matches;\n};\n\n/**\n * Returns true if the given `string` contains the given pattern. Similar\n * to [.isMatch](#isMatch) but the pattern can match any part of the string.\n *\n * ```js\n * var nm = require('nanomatch');\n * nm.contains(string, pattern[, options]);\n *\n * console.log(nm.contains('aa/bb/cc', '*b'));\n * //=> true\n * console.log(nm.contains('aa/bb/cc', '*d'));\n * //=> false\n * ```\n * @param {String} `str` The string to match.\n * @param {String|Array} `patterns` Glob pattern to use for matching.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Boolean} Returns true if the patter matches any part of `str`.\n * @api public\n */\n\nnanomatch.contains = function(str, patterns, options) {\n if (typeof str !== 'string') {\n throw new TypeError('expected a string: \"' + util.inspect(str) + '\"');\n }\n\n if (typeof patterns === 'string') {\n if (utils.isEmptyString(str) || utils.isEmptyString(patterns)) {\n return false;\n }\n\n var equals = utils.equalsPattern(patterns, options);\n if (equals(str)) {\n return true;\n }\n var contains = utils.containsPattern(patterns, options);\n if (contains(str)) {\n return true;\n }\n }\n\n var opts = extend({}, options, {contains: true});\n return nanomatch.any(str, patterns, opts);\n};\n\n/**\n * Returns true if the given pattern and options should enable\n * the `matchBase` option.\n * @return {Boolean}\n * @api private\n */\n\nnanomatch.matchBase = function(pattern, options) {\n if (pattern && pattern.indexOf('/') !== -1 || !options) return false;\n return options.basename === true || options.matchBase === true;\n};\n\n/**\n * Filter the keys of the given object with the given `glob` pattern\n * and `options`. Does not attempt to match nested keys. If you need this feature,\n * use [glob-object][] instead.\n *\n * ```js\n * var nm = require('nanomatch');\n * nm.matchKeys(object, patterns[, options]);\n *\n * var obj = { aa: 'a', ab: 'b', ac: 'c' };\n * console.log(nm.matchKeys(obj, '*b'));\n * //=> { ab: 'b' }\n * ```\n * @param {Object} `object` The object with keys to filter.\n * @param {String|Array} `patterns` One or more glob patterns to use for matching.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Object} Returns an object with only keys that match the given patterns.\n * @api public\n */\n\nnanomatch.matchKeys = function(obj, patterns, options) {\n if (!utils.isObject(obj)) {\n throw new TypeError('expected the first argument to be an object');\n }\n var keys = nanomatch(Object.keys(obj), patterns, options);\n return utils.pick(obj, keys);\n};\n\n/**\n * Returns a memoized matcher function from the given glob `pattern` and `options`.\n * The returned function takes a string to match as its only argument and returns\n * true if the string is a match.\n *\n * ```js\n * var nm = require('nanomatch');\n * nm.matcher(pattern[, options]);\n *\n * var isMatch = nm.matcher('*.!(*a)');\n * console.log(isMatch('a.a'));\n * //=> false\n * console.log(isMatch('a.b'));\n * //=> true\n * ```\n * @param {String} `pattern` Glob pattern\n * @param {Object} `options` See available [options](#options) for changing how matches are performed.\n * @return {Function} Returns a matcher function.\n * @api public\n */\n\nnanomatch.matcher = function matcher(pattern, options) {\n if (utils.isEmptyString(pattern)) {\n return function() {\n return false;\n };\n }\n\n if (Array.isArray(pattern)) {\n return compose(pattern, options, matcher);\n }\n\n // if pattern is a regex\n if (pattern instanceof RegExp) {\n return test(pattern);\n }\n\n // if pattern is invalid\n if (!utils.isString(pattern)) {\n throw new TypeError('expected pattern to be an array, string or regex');\n }\n\n // if pattern is a non-glob string\n if (!utils.hasSpecialChars(pattern)) {\n if (options && options.nocase === true) {\n pattern = pattern.toLowerCase();\n }\n return utils.matchPath(pattern, options);\n }\n\n // if pattern is a glob string\n var re = nanomatch.makeRe(pattern, options);\n\n // if `options.matchBase` or `options.basename` is defined\n if (nanomatch.matchBase(pattern, options)) {\n return utils.matchBasename(re, options);\n }\n\n function test(regex) {\n var equals = utils.equalsPattern(options);\n var unixify = utils.unixify(options);\n\n return function(str) {\n if (equals(str)) {\n return true;\n }\n\n if (regex.test(unixify(str))) {\n return true;\n }\n return false;\n };\n }\n\n // create matcher function\n var matcherFn = test(re);\n // set result object from compiler on matcher function,\n // as a non-enumerable property. useful for debugging\n utils.define(matcherFn, 'result', re.result);\n return matcherFn;\n};\n\n/**\n * Returns an array of matches captured by `pattern` in `string, or\n * `null` if the pattern did not match.\n *\n * ```js\n * var nm = require('nanomatch');\n * nm.capture(pattern, string[, options]);\n *\n * console.log(nm.capture('test/*.js', 'test/foo.js'));\n * //=> ['foo']\n * console.log(nm.capture('test/*.js', 'foo/bar.css'));\n * //=> null\n * ```\n * @param {String} `pattern` Glob pattern to use for matching.\n * @param {String} `string` String to match\n * @param {Object} `options` See available [options](#options) for changing how matches are performed\n * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`.\n * @api public\n */\n\nnanomatch.capture = function(pattern, str, options) {\n var re = nanomatch.makeRe(pattern, extend({capture: true}, options));\n var unixify = utils.unixify(options);\n\n function match() {\n return function(string) {\n var match = re.exec(unixify(string));\n if (!match) {\n return null;\n }\n\n return match.slice(1);\n };\n }\n\n var capture = memoize('capture', pattern, options, match);\n return capture(str);\n};\n\n/**\n * Create a regular expression from the given glob `pattern`.\n *\n * ```js\n * var nm = require('nanomatch');\n * nm.makeRe(pattern[, options]);\n *\n * console.log(nm.makeRe('*.js'));\n * //=> /^(?:(\\.[\\\\\\/])?(?!\\.)(?=.)[^\\/]*?\\.js)$/\n * ```\n * @param {String} `pattern` A glob pattern to convert to regex.\n * @param {Object} `options` See available [options](#options) for changing how matches are performed.\n * @return {RegExp} Returns a regex created from the given pattern.\n * @api public\n */\n\nnanomatch.makeRe = function(pattern, options) {\n if (pattern instanceof RegExp) {\n return pattern;\n }\n\n if (typeof pattern !== 'string') {\n throw new TypeError('expected pattern to be a string');\n }\n\n if (pattern.length > MAX_LENGTH) {\n throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters');\n }\n\n function makeRe() {\n var opts = utils.extend({wrap: false}, options);\n var result = nanomatch.create(pattern, opts);\n var regex = toRegex(result.output, opts);\n utils.define(regex, 'result', result);\n return regex;\n }\n\n return memoize('makeRe', pattern, options, makeRe);\n};\n\n/**\n * Parses the given glob `pattern` and returns an object with the compiled `output`\n * and optional source `map`.\n *\n * ```js\n * var nm = require('nanomatch');\n * nm.create(pattern[, options]);\n *\n * console.log(nm.create('abc/*.js'));\n * // { options: { source: 'string', sourcemap: true },\n * // state: {},\n * // compilers:\n * // { ... },\n * // output: '(\\\\.[\\\\\\\\\\\\/])?abc\\\\/(?!\\\\.)(?=.)[^\\\\/]*?\\\\.js',\n * // ast:\n * // { type: 'root',\n * // errors: [],\n * // nodes:\n * // [ ... ],\n * // dot: false,\n * // input: 'abc/*.js' },\n * // parsingErrors: [],\n * // map:\n * // { version: 3,\n * // sources: [ 'string' ],\n * // names: [],\n * // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE',\n * // sourcesContent: [ 'abc/*.js' ] },\n * // position: { line: 1, column: 28 },\n * // content: {},\n * // files: {},\n * // idx: 6 }\n * ```\n * @param {String} `pattern` Glob pattern to parse and compile.\n * @param {Object} `options` Any [options](#options) to change how parsing and compiling is performed.\n * @return {Object} Returns an object with the parsed AST, compiled string and optional source map.\n * @api public\n */\n\nnanomatch.create = function(pattern, options) {\n if (typeof pattern !== 'string') {\n throw new TypeError('expected a string');\n }\n function create() {\n return nanomatch.compile(nanomatch.parse(pattern, options), options);\n }\n return memoize('create', pattern, options, create);\n};\n\n/**\n * Parse the given `str` with the given `options`.\n *\n * ```js\n * var nm = require('nanomatch');\n * nm.parse(pattern[, options]);\n *\n * var ast = nm.parse('a/{b,c}/d');\n * console.log(ast);\n * // { type: 'root',\n * // errors: [],\n * // input: 'a/{b,c}/d',\n * // nodes:\n * // [ { type: 'bos', val: '' },\n * // { type: 'text', val: 'a/' },\n * // { type: 'brace',\n * // nodes:\n * // [ { type: 'brace.open', val: '{' },\n * // { type: 'text', val: 'b,c' },\n * // { type: 'brace.close', val: '}' } ] },\n * // { type: 'text', val: '/d' },\n * // { type: 'eos', val: '' } ] }\n * ```\n * @param {String} `str`\n * @param {Object} `options`\n * @return {Object} Returns an AST\n * @api public\n */\n\nnanomatch.parse = function(pattern, options) {\n if (typeof pattern !== 'string') {\n throw new TypeError('expected a string');\n }\n\n function parse() {\n var snapdragon = utils.instantiate(null, options);\n parsers(snapdragon, options);\n\n var ast = snapdragon.parse(pattern, options);\n utils.define(ast, 'snapdragon', snapdragon);\n ast.input = pattern;\n return ast;\n }\n\n return memoize('parse', pattern, options, parse);\n};\n\n/**\n * Compile the given `ast` or string with the given `options`.\n *\n * ```js\n * var nm = require('nanomatch');\n * nm.compile(ast[, options]);\n *\n * var ast = nm.parse('a/{b,c}/d');\n * console.log(nm.compile(ast));\n * // { options: { source: 'string' },\n * // state: {},\n * // compilers:\n * // { eos: [Function],\n * // noop: [Function],\n * // bos: [Function],\n * // brace: [Function],\n * // 'brace.open': [Function],\n * // text: [Function],\n * // 'brace.close': [Function] },\n * // output: [ 'a/(b|c)/d' ],\n * // ast:\n * // { ... },\n * // parsingErrors: [] }\n * ```\n * @param {Object|String} `ast`\n * @param {Object} `options`\n * @return {Object} Returns an object that has an `output` property with the compiled string.\n * @api public\n */\n\nnanomatch.compile = function(ast, options) {\n if (typeof ast === 'string') {\n ast = nanomatch.parse(ast, options);\n }\n\n function compile() {\n var snapdragon = utils.instantiate(ast, options);\n compilers(snapdragon, options);\n return snapdragon.compile(ast, options);\n }\n\n return memoize('compile', ast.input, options, compile);\n};\n\n/**\n * Clear the regex cache.\n *\n * ```js\n * nm.clearCache();\n * ```\n * @api public\n */\n\nnanomatch.clearCache = function() {\n nanomatch.cache.__data__ = {};\n};\n\n/**\n * Compose a matcher function with the given patterns.\n * This allows matcher functions to be compiled once and\n * called multiple times.\n */\n\nfunction compose(patterns, options, matcher) {\n var matchers;\n\n return memoize('compose', String(patterns), options, function() {\n return function(file) {\n // delay composition until it's invoked the first time,\n // after that it won't be called again\n if (!matchers) {\n matchers = [];\n for (var i = 0; i < patterns.length; i++) {\n matchers.push(matcher(patterns[i], options));\n }\n }\n\n var len = matchers.length;\n while (len--) {\n if (matchers[len](file) === true) {\n return true;\n }\n }\n return false;\n };\n });\n}\n\n/**\n * Memoize a generated regex or function. A unique key is generated\n * from the `type` (usually method name), the `pattern`, and\n * user-defined options.\n */\n\nfunction memoize(type, pattern, options, fn) {\n var key = utils.createKey(type + '=' + pattern, options);\n\n if (options && options.cache === false) {\n return fn(pattern, options);\n }\n\n if (cache.has(type, key)) {\n return cache.get(type, key);\n }\n\n var val = fn(pattern, options);\n cache.set(type, key, val);\n return val;\n}\n\n/**\n * Expose compiler, parser and cache on `nanomatch`\n */\n\nnanomatch.compilers = compilers;\nnanomatch.parsers = parsers;\nnanomatch.cache = cache;\n\n/**\n * Expose `nanomatch`\n * @type {Function}\n */\n\nmodule.exports = nanomatch;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/nanomatch/index.js?"); + +/***/ }), + +/***/ "./node_modules/nanomatch/lib/cache.js": +/*!*********************************************!*\ + !*** ./node_modules/nanomatch/lib/cache.js ***! + \*********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("module.exports = new (__webpack_require__(/*! fragment-cache */ \"./node_modules/fragment-cache/index.js\"))();\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/nanomatch/lib/cache.js?"); + +/***/ }), + +/***/ "./node_modules/nanomatch/lib/compilers.js": +/*!*************************************************!*\ + !*** ./node_modules/nanomatch/lib/compilers.js ***! + \*************************************************/ +/***/ ((module) => { + +"use strict"; +eval("\n\n/**\n* Nanomatch compilers\n*/\n\nmodule.exports = function(nanomatch, options) {\n function slash() {\n if (options && typeof options.slash === 'string') {\n return options.slash;\n }\n if (options && typeof options.slash === 'function') {\n return options.slash.call(nanomatch);\n }\n return '\\\\\\\\/';\n }\n\n function star() {\n if (options && typeof options.star === 'string') {\n return options.star;\n }\n if (options && typeof options.star === 'function') {\n return options.star.call(nanomatch);\n }\n return '[^' + slash() + ']*?';\n }\n\n var ast = nanomatch.ast = nanomatch.parser.ast;\n ast.state = nanomatch.parser.state;\n nanomatch.compiler.state = ast.state;\n nanomatch.compiler\n\n /**\n * Negation / escaping\n */\n\n .set('not', function(node) {\n var prev = this.prev();\n if (this.options.nonegate === true || prev.type !== 'bos') {\n return this.emit('\\\\' + node.val, node);\n }\n return this.emit(node.val, node);\n })\n .set('escape', function(node) {\n if (this.options.unescape && /^[-\\w_.]/.test(node.val)) {\n return this.emit(node.val, node);\n }\n return this.emit('\\\\' + node.val, node);\n })\n .set('quoted', function(node) {\n return this.emit(node.val, node);\n })\n\n /**\n * Regex\n */\n\n .set('dollar', function(node) {\n if (node.parent.type === 'bracket') {\n return this.emit(node.val, node);\n }\n return this.emit('\\\\' + node.val, node);\n })\n\n /**\n * Dot: \".\"\n */\n\n .set('dot', function(node) {\n if (node.dotfiles === true) this.dotfiles = true;\n return this.emit('\\\\' + node.val, node);\n })\n\n /**\n * Slashes: \"/\" and \"\\\"\n */\n\n .set('backslash', function(node) {\n return this.emit(node.val, node);\n })\n .set('slash', function(node, nodes, i) {\n var val = '[' + slash() + ']';\n var parent = node.parent;\n var prev = this.prev();\n\n // set \"node.hasSlash\" to true on all ancestor parens nodes\n while (parent.type === 'paren' && !parent.hasSlash) {\n parent.hasSlash = true;\n parent = parent.parent;\n }\n\n if (prev.addQmark) {\n val += '?';\n }\n\n // word boundary\n if (node.rest.slice(0, 2) === '\\\\b') {\n return this.emit(val, node);\n }\n\n // globstars\n if (node.parsed === '**' || node.parsed === './**') {\n this.output = '(?:' + this.output;\n return this.emit(val + ')?', node);\n }\n\n // negation\n if (node.parsed === '!**' && this.options.nonegate !== true) {\n return this.emit(val + '?\\\\b', node);\n }\n return this.emit(val, node);\n })\n\n /**\n * Square brackets\n */\n\n .set('bracket', function(node) {\n var close = node.close;\n var open = !node.escaped ? '[' : '\\\\[';\n var negated = node.negated;\n var inner = node.inner;\n var val = node.val;\n\n if (node.escaped === true) {\n inner = inner.replace(/\\\\?(\\W)/g, '\\\\$1');\n negated = '';\n }\n\n if (inner === ']-') {\n inner = '\\\\]\\\\-';\n }\n\n if (negated && inner.indexOf('.') === -1) {\n inner += '.';\n }\n if (negated && inner.indexOf('/') === -1) {\n inner += '/';\n }\n\n val = open + negated + inner + close;\n return this.emit(val, node);\n })\n\n /**\n * Square: \"[.]\" (only matches a single character in brackets)\n */\n\n .set('square', function(node) {\n var val = (/^\\W/.test(node.val) ? '\\\\' : '') + node.val;\n return this.emit(val, node);\n })\n\n /**\n * Question mark: \"?\"\n */\n\n .set('qmark', function(node) {\n var prev = this.prev();\n // don't use \"slash\" variable so that we always avoid\n // matching backslashes and slashes with a qmark\n var val = '[^.\\\\\\\\/]';\n if (this.options.dot || (prev.type !== 'bos' && prev.type !== 'slash')) {\n val = '[^\\\\\\\\/]';\n }\n\n if (node.parsed.slice(-1) === '(') {\n var ch = node.rest.charAt(0);\n if (ch === '!' || ch === '=' || ch === ':') {\n return this.emit(node.val, node);\n }\n }\n\n if (node.val.length > 1) {\n val += '{' + node.val.length + '}';\n }\n return this.emit(val, node);\n })\n\n /**\n * Plus\n */\n\n .set('plus', function(node) {\n var prev = node.parsed.slice(-1);\n if (prev === ']' || prev === ')') {\n return this.emit(node.val, node);\n }\n if (!this.output || (/[?*+]/.test(ch) && node.parent.type !== 'bracket')) {\n return this.emit('\\\\+', node);\n }\n var ch = this.output.slice(-1);\n if (/\\w/.test(ch) && !node.inside) {\n return this.emit('+\\\\+?', node);\n }\n return this.emit('+', node);\n })\n\n /**\n * globstar: '**'\n */\n\n .set('globstar', function(node, nodes, i) {\n if (!this.output) {\n this.state.leadingGlobstar = true;\n }\n\n var prev = this.prev();\n var before = this.prev(2);\n var next = this.next();\n var after = this.next(2);\n var type = prev.type;\n var val = node.val;\n\n if (prev.type === 'slash' && next.type === 'slash') {\n if (before.type === 'text') {\n this.output += '?';\n\n if (after.type !== 'text') {\n this.output += '\\\\b';\n }\n }\n }\n\n var parsed = node.parsed;\n if (parsed.charAt(0) === '!') {\n parsed = parsed.slice(1);\n }\n\n var isInside = node.isInside.paren || node.isInside.brace;\n if (parsed && type !== 'slash' && type !== 'bos' && !isInside) {\n val = star();\n } else {\n val = this.options.dot !== true\n ? '(?:(?!(?:[' + slash() + ']|^)\\\\.).)*?'\n : '(?:(?!(?:[' + slash() + ']|^)(?:\\\\.{1,2})($|[' + slash() + ']))(?!\\\\.{2}).)*?';\n }\n\n if ((type === 'slash' || type === 'bos') && this.options.dot !== true) {\n val = '(?!\\\\.)' + val;\n }\n\n if (prev.type === 'slash' && next.type === 'slash' && before.type !== 'text') {\n if (after.type === 'text' || after.type === 'star') {\n node.addQmark = true;\n }\n }\n\n if (this.options.capture) {\n val = '(' + val + ')';\n }\n\n return this.emit(val, node);\n })\n\n /**\n * Star: \"*\"\n */\n\n .set('star', function(node, nodes, i) {\n var prior = nodes[i - 2] || {};\n var prev = this.prev();\n var next = this.next();\n var type = prev.type;\n\n function isStart(n) {\n return n.type === 'bos' || n.type === 'slash';\n }\n\n if (this.output === '' && this.options.contains !== true) {\n this.output = '(?![' + slash() + '])';\n }\n\n if (type === 'bracket' && this.options.bash === false) {\n var str = next && next.type === 'bracket' ? star() : '*?';\n if (!prev.nodes || prev.nodes[1].type !== 'posix') {\n return this.emit(str, node);\n }\n }\n\n var prefix = !this.dotfiles && type !== 'text' && type !== 'escape'\n ? (this.options.dot ? '(?!(?:^|[' + slash() + '])\\\\.{1,2}(?:$|[' + slash() + ']))' : '(?!\\\\.)')\n : '';\n\n if (isStart(prev) || (isStart(prior) && type === 'not')) {\n if (prefix !== '(?!\\\\.)') {\n prefix += '(?!(\\\\.{2}|\\\\.[' + slash() + ']))(?=.)';\n } else {\n prefix += '(?=.)';\n }\n } else if (prefix === '(?!\\\\.)') {\n prefix = '';\n }\n\n if (prev.type === 'not' && prior.type === 'bos' && this.options.dot === true) {\n this.output = '(?!\\\\.)' + this.output;\n }\n\n var output = prefix + star();\n if (this.options.capture) {\n output = '(' + output + ')';\n }\n\n return this.emit(output, node);\n })\n\n /**\n * Text\n */\n\n .set('text', function(node) {\n return this.emit(node.val, node);\n })\n\n /**\n * End-of-string\n */\n\n .set('eos', function(node) {\n var prev = this.prev();\n var val = node.val;\n\n this.output = '(?:\\\\.[' + slash() + '](?=.))?' + this.output;\n if (this.state.metachar && prev.type !== 'qmark' && prev.type !== 'slash') {\n val += (this.options.contains ? '[' + slash() + ']?' : '(?:[' + slash() + ']|$)');\n }\n\n return this.emit(val, node);\n });\n\n /**\n * Allow custom compilers to be passed on options\n */\n\n if (options && typeof options.compilers === 'function') {\n options.compilers(nanomatch.compiler);\n }\n};\n\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/nanomatch/lib/compilers.js?"); + +/***/ }), + +/***/ "./node_modules/nanomatch/lib/parsers.js": +/*!***********************************************!*\ + !*** ./node_modules/nanomatch/lib/parsers.js ***! + \***********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar regexNot = __webpack_require__(/*! regex-not */ \"./node_modules/regex-not/index.js\");\nvar toRegex = __webpack_require__(/*! to-regex */ \"./node_modules/to-regex/index.js\");\n\n/**\n * Characters to use in negation regex (we want to \"not\" match\n * characters that are matched by other parsers)\n */\n\nvar cached;\nvar NOT_REGEX = '[\\\\[!*+?$^\"\\'.\\\\\\\\/]+';\nvar not = createTextRegex(NOT_REGEX);\n\n/**\n * Nanomatch parsers\n */\n\nmodule.exports = function(nanomatch, options) {\n var parser = nanomatch.parser;\n var opts = parser.options;\n\n parser.state = {\n slashes: 0,\n paths: []\n };\n\n parser.ast.state = parser.state;\n parser\n\n /**\n * Beginning-of-string\n */\n\n .capture('prefix', function() {\n if (this.parsed) return;\n var m = this.match(/^\\.[\\\\/]/);\n if (!m) return;\n this.state.strictOpen = !!this.options.strictOpen;\n this.state.addPrefix = true;\n })\n\n /**\n * Escape: \"\\\\.\"\n */\n\n .capture('escape', function() {\n if (this.isInside('bracket')) return;\n var pos = this.position();\n var m = this.match(/^(?:\\\\(.)|([$^]))/);\n if (!m) return;\n\n return pos({\n type: 'escape',\n val: m[2] || m[1]\n });\n })\n\n /**\n * Quoted strings\n */\n\n .capture('quoted', function() {\n var pos = this.position();\n var m = this.match(/^[\"']/);\n if (!m) return;\n\n var quote = m[0];\n if (this.input.indexOf(quote) === -1) {\n return pos({\n type: 'escape',\n val: quote\n });\n }\n\n var tok = advanceTo(this.input, quote);\n this.consume(tok.len);\n\n return pos({\n type: 'quoted',\n val: tok.esc\n });\n })\n\n /**\n * Negations: \"!\"\n */\n\n .capture('not', function() {\n var parsed = this.parsed;\n var pos = this.position();\n var m = this.match(this.notRegex || /^!+/);\n if (!m) return;\n var val = m[0];\n\n var isNegated = (val.length % 2) === 1;\n if (parsed === '' && !isNegated) {\n val = '';\n }\n\n // if nothing has been parsed, we know `!` is at the start,\n // so we need to wrap the result in a negation regex\n if (parsed === '' && isNegated && this.options.nonegate !== true) {\n this.bos.val = '(?!^(?:';\n this.append = ')$).*';\n val = '';\n }\n return pos({\n type: 'not',\n val: val\n });\n })\n\n /**\n * Dot: \".\"\n */\n\n .capture('dot', function() {\n var parsed = this.parsed;\n var pos = this.position();\n var m = this.match(/^\\.+/);\n if (!m) return;\n\n var val = m[0];\n this.state.dot = val === '.' && (parsed === '' || parsed.slice(-1) === '/');\n\n return pos({\n type: 'dot',\n dotfiles: this.state.dot,\n val: val\n });\n })\n\n /**\n * Plus: \"+\"\n */\n\n .capture('plus', /^\\+(?!\\()/)\n\n /**\n * Question mark: \"?\"\n */\n\n .capture('qmark', function() {\n var parsed = this.parsed;\n var pos = this.position();\n var m = this.match(/^\\?+(?!\\()/);\n if (!m) return;\n\n this.state.metachar = true;\n this.state.qmark = true;\n\n return pos({\n type: 'qmark',\n parsed: parsed,\n val: m[0]\n });\n })\n\n /**\n * Globstar: \"**\"\n */\n\n .capture('globstar', function() {\n var parsed = this.parsed;\n var pos = this.position();\n var m = this.match(/^\\*{2}(?![*(])(?=[,)/]|$)/);\n if (!m) return;\n\n var type = opts.noglobstar !== true ? 'globstar' : 'star';\n var node = pos({type: type, parsed: parsed});\n this.state.metachar = true;\n\n while (this.input.slice(0, 4) === '/**/') {\n this.input = this.input.slice(3);\n }\n\n node.isInside = {\n brace: this.isInside('brace'),\n paren: this.isInside('paren')\n };\n\n if (type === 'globstar') {\n this.state.globstar = true;\n node.val = '**';\n\n } else {\n this.state.star = true;\n node.val = '*';\n }\n\n return node;\n })\n\n /**\n * Star: \"*\"\n */\n\n .capture('star', function() {\n var pos = this.position();\n var starRe = /^(?:\\*(?![*(])|[*]{3,}(?!\\()|[*]{2}(?![(/]|$)|\\*(?=\\*\\())/;\n var m = this.match(starRe);\n if (!m) return;\n\n this.state.metachar = true;\n this.state.star = true;\n return pos({\n type: 'star',\n val: m[0]\n });\n })\n\n /**\n * Slash: \"/\"\n */\n\n .capture('slash', function() {\n var pos = this.position();\n var m = this.match(/^\\//);\n if (!m) return;\n\n this.state.slashes++;\n return pos({\n type: 'slash',\n val: m[0]\n });\n })\n\n /**\n * Backslash: \"\\\\\"\n */\n\n .capture('backslash', function() {\n var pos = this.position();\n var m = this.match(/^\\\\(?![*+?(){}[\\]'\"])/);\n if (!m) return;\n\n var val = m[0];\n\n if (this.isInside('bracket')) {\n val = '\\\\';\n } else if (val.length > 1) {\n val = '\\\\\\\\';\n }\n\n return pos({\n type: 'backslash',\n val: val\n });\n })\n\n /**\n * Square: \"[.]\"\n */\n\n .capture('square', function() {\n if (this.isInside('bracket')) return;\n var pos = this.position();\n var m = this.match(/^\\[([^!^\\\\])\\]/);\n if (!m) return;\n\n return pos({\n type: 'square',\n val: m[1]\n });\n })\n\n /**\n * Brackets: \"[...]\" (basic, this can be overridden by other parsers)\n */\n\n .capture('bracket', function() {\n var pos = this.position();\n var m = this.match(/^(?:\\[([!^]?)([^\\]]+|\\]-)(\\]|[^*+?]+)|\\[)/);\n if (!m) return;\n\n var val = m[0];\n var negated = m[1] ? '^' : '';\n var inner = (m[2] || '').replace(/\\\\\\\\+/, '\\\\\\\\');\n var close = m[3] || '';\n\n if (m[2] && inner.length < m[2].length) {\n val = val.replace(/\\\\\\\\+/, '\\\\\\\\');\n }\n\n var esc = this.input.slice(0, 2);\n if (inner === '' && esc === '\\\\]') {\n inner += esc;\n this.consume(2);\n\n var str = this.input;\n var idx = -1;\n var ch;\n\n while ((ch = str[++idx])) {\n this.consume(1);\n if (ch === ']') {\n close = ch;\n break;\n }\n inner += ch;\n }\n }\n\n return pos({\n type: 'bracket',\n val: val,\n escaped: close !== ']',\n negated: negated,\n inner: inner,\n close: close\n });\n })\n\n /**\n * Text\n */\n\n .capture('text', function() {\n if (this.isInside('bracket')) return;\n var pos = this.position();\n var m = this.match(not);\n if (!m || !m[0]) return;\n\n return pos({\n type: 'text',\n val: m[0]\n });\n });\n\n /**\n * Allow custom parsers to be passed on options\n */\n\n if (options && typeof options.parsers === 'function') {\n options.parsers(nanomatch.parser);\n }\n};\n\n/**\n * Advance to the next non-escaped character\n */\n\nfunction advanceTo(input, endChar) {\n var ch = input.charAt(0);\n var tok = { len: 1, val: '', esc: '' };\n var idx = 0;\n\n function advance() {\n if (ch !== '\\\\') {\n tok.esc += '\\\\' + ch;\n tok.val += ch;\n }\n\n ch = input.charAt(++idx);\n tok.len++;\n\n if (ch === '\\\\') {\n advance();\n advance();\n }\n }\n\n while (ch && ch !== endChar) {\n advance();\n }\n return tok;\n}\n\n/**\n * Create text regex\n */\n\nfunction createTextRegex(pattern) {\n if (cached) return cached;\n var opts = {contains: true, strictClose: false};\n var not = regexNot.create(pattern, opts);\n var re = toRegex('^(?:[*]\\\\((?=.)|' + not + ')', opts);\n return (cached = re);\n}\n\n/**\n * Expose negation string\n */\n\nmodule.exports.not = NOT_REGEX;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/nanomatch/lib/parsers.js?"); + +/***/ }), + +/***/ "./node_modules/nanomatch/lib/utils.js": +/*!*********************************************!*\ + !*** ./node_modules/nanomatch/lib/utils.js ***! + \*********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar utils = module.exports;\nvar path = __webpack_require__(/*! path */ \"path\");\n\n/**\n * Module dependencies\n */\n\nvar isWindows = __webpack_require__(/*! is-windows */ \"./node_modules/is-windows/index.js\")();\nvar Snapdragon = __webpack_require__(/*! snapdragon */ \"./node_modules/snapdragon/index.js\");\nutils.define = __webpack_require__(/*! define-property */ \"./node_modules/nanomatch/node_modules/define-property/index.js\");\nutils.diff = __webpack_require__(/*! arr-diff */ \"./node_modules/arr-diff/index.js\");\nutils.extend = __webpack_require__(/*! extend-shallow */ \"./node_modules/nanomatch/node_modules/extend-shallow/index.js\");\nutils.pick = __webpack_require__(/*! object.pick */ \"./node_modules/object.pick/index.js\");\nutils.typeOf = __webpack_require__(/*! kind-of */ \"./node_modules/kind-of/index.js\");\nutils.unique = __webpack_require__(/*! array-unique */ \"./node_modules/array-unique/index.js\");\n\n/**\n * Returns true if the given value is effectively an empty string\n */\n\nutils.isEmptyString = function(val) {\n return String(val) === '' || String(val) === './';\n};\n\n/**\n * Returns true if the platform is windows, or `path.sep` is `\\\\`.\n * This is defined as a function to allow `path.sep` to be set in unit tests,\n * or by the user, if there is a reason to do so.\n * @return {Boolean}\n */\n\nutils.isWindows = function() {\n return path.sep === '\\\\' || isWindows === true;\n};\n\n/**\n * Return the last element from an array\n */\n\nutils.last = function(arr, n) {\n return arr[arr.length - (n || 1)];\n};\n\n/**\n * Get the `Snapdragon` instance to use\n */\n\nutils.instantiate = function(ast, options) {\n var snapdragon;\n // if an instance was created by `.parse`, use that instance\n if (utils.typeOf(ast) === 'object' && ast.snapdragon) {\n snapdragon = ast.snapdragon;\n // if the user supplies an instance on options, use that instance\n } else if (utils.typeOf(options) === 'object' && options.snapdragon) {\n snapdragon = options.snapdragon;\n // create a new instance\n } else {\n snapdragon = new Snapdragon(options);\n }\n\n utils.define(snapdragon, 'parse', function(str, options) {\n var parsed = Snapdragon.prototype.parse.call(this, str, options);\n parsed.input = str;\n\n // escape unmatched brace/bracket/parens\n var last = this.parser.stack.pop();\n if (last && this.options.strictErrors !== true) {\n var open = last.nodes[0];\n var inner = last.nodes[1];\n if (last.type === 'bracket') {\n if (inner.val.charAt(0) === '[') {\n inner.val = '\\\\' + inner.val;\n }\n\n } else {\n open.val = '\\\\' + open.val;\n var sibling = open.parent.nodes[1];\n if (sibling.type === 'star') {\n sibling.loose = true;\n }\n }\n }\n\n // add non-enumerable parser reference\n utils.define(parsed, 'parser', this.parser);\n return parsed;\n });\n\n return snapdragon;\n};\n\n/**\n * Create the key to use for memoization. The key is generated\n * by iterating over the options and concatenating key-value pairs\n * to the pattern string.\n */\n\nutils.createKey = function(pattern, options) {\n if (typeof options === 'undefined') {\n return pattern;\n }\n var key = pattern;\n for (var prop in options) {\n if (options.hasOwnProperty(prop)) {\n key += ';' + prop + '=' + String(options[prop]);\n }\n }\n return key;\n};\n\n/**\n * Cast `val` to an array\n * @return {Array}\n */\n\nutils.arrayify = function(val) {\n if (typeof val === 'string') return [val];\n return val ? (Array.isArray(val) ? val : [val]) : [];\n};\n\n/**\n * Return true if `val` is a non-empty string\n */\n\nutils.isString = function(val) {\n return typeof val === 'string';\n};\n\n/**\n * Return true if `val` is a non-empty string\n */\n\nutils.isRegex = function(val) {\n return utils.typeOf(val) === 'regexp';\n};\n\n/**\n * Return true if `val` is a non-empty string\n */\n\nutils.isObject = function(val) {\n return utils.typeOf(val) === 'object';\n};\n\n/**\n * Escape regex characters in the given string\n */\n\nutils.escapeRegex = function(str) {\n return str.replace(/[-[\\]{}()^$|*+?.\\\\/\\s]/g, '\\\\$&');\n};\n\n/**\n * Combines duplicate characters in the provided `input` string.\n * @param {String} `input`\n * @returns {String}\n */\n\nutils.combineDupes = function(input, patterns) {\n patterns = utils.arrayify(patterns).join('|').split('|');\n patterns = patterns.map(function(s) {\n return s.replace(/\\\\?([+*\\\\/])/g, '\\\\$1');\n });\n var substr = patterns.join('|');\n var regex = new RegExp('(' + substr + ')(?=\\\\1)', 'g');\n return input.replace(regex, '');\n};\n\n/**\n * Returns true if the given `str` has special characters\n */\n\nutils.hasSpecialChars = function(str) {\n return /(?:(?:(^|\\/)[!.])|[*?+()|[\\]{}]|[+@]\\()/.test(str);\n};\n\n/**\n * Normalize slashes in the given filepath.\n *\n * @param {String} `filepath`\n * @return {String}\n */\n\nutils.toPosixPath = function(str) {\n return str.replace(/\\\\+/g, '/');\n};\n\n/**\n * Strip backslashes before special characters in a string.\n *\n * @param {String} `str`\n * @return {String}\n */\n\nutils.unescape = function(str) {\n return utils.toPosixPath(str.replace(/\\\\(?=[*+?!.])/g, ''));\n};\n\n/**\n * Strip the drive letter from a windows filepath\n * @param {String} `fp`\n * @return {String}\n */\n\nutils.stripDrive = function(fp) {\n return utils.isWindows() ? fp.replace(/^[a-z]:[\\\\/]+?/i, '/') : fp;\n};\n\n/**\n * Strip the prefix from a filepath\n * @param {String} `fp`\n * @return {String}\n */\n\nutils.stripPrefix = function(str) {\n if (str.charAt(0) === '.' && (str.charAt(1) === '/' || str.charAt(1) === '\\\\')) {\n return str.slice(2);\n }\n return str;\n};\n\n/**\n * Returns true if `str` is a common character that doesn't need\n * to be processed to be used for matching.\n * @param {String} `str`\n * @return {Boolean}\n */\n\nutils.isSimpleChar = function(str) {\n return str.trim() === '' || str === '.';\n};\n\n/**\n * Returns true if the given str is an escaped or\n * unescaped path character\n */\n\nutils.isSlash = function(str) {\n return str === '/' || str === '\\\\/' || str === '\\\\' || str === '\\\\\\\\';\n};\n\n/**\n * Returns a function that returns true if the given\n * pattern matches or contains a `filepath`\n *\n * @param {String} `pattern`\n * @return {Function}\n */\n\nutils.matchPath = function(pattern, options) {\n return (options && options.contains)\n ? utils.containsPattern(pattern, options)\n : utils.equalsPattern(pattern, options);\n};\n\n/**\n * Returns true if the given (original) filepath or unixified path are equal\n * to the given pattern.\n */\n\nutils._equals = function(filepath, unixPath, pattern) {\n return pattern === filepath || pattern === unixPath;\n};\n\n/**\n * Returns true if the given (original) filepath or unixified path contain\n * the given pattern.\n */\n\nutils._contains = function(filepath, unixPath, pattern) {\n return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1;\n};\n\n/**\n * Returns a function that returns true if the given\n * pattern is the same as a given `filepath`\n *\n * @param {String} `pattern`\n * @return {Function}\n */\n\nutils.equalsPattern = function(pattern, options) {\n var unixify = utils.unixify(options);\n options = options || {};\n\n return function fn(filepath) {\n var equal = utils._equals(filepath, unixify(filepath), pattern);\n if (equal === true || options.nocase !== true) {\n return equal;\n }\n var lower = filepath.toLowerCase();\n return utils._equals(lower, unixify(lower), pattern);\n };\n};\n\n/**\n * Returns a function that returns true if the given\n * pattern contains a `filepath`\n *\n * @param {String} `pattern`\n * @return {Function}\n */\n\nutils.containsPattern = function(pattern, options) {\n var unixify = utils.unixify(options);\n options = options || {};\n\n return function(filepath) {\n var contains = utils._contains(filepath, unixify(filepath), pattern);\n if (contains === true || options.nocase !== true) {\n return contains;\n }\n var lower = filepath.toLowerCase();\n return utils._contains(lower, unixify(lower), pattern);\n };\n};\n\n/**\n * Returns a function that returns true if the given\n * regex matches the `filename` of a file path.\n *\n * @param {RegExp} `re` Matching regex\n * @return {Function}\n */\n\nutils.matchBasename = function(re) {\n return function(filepath) {\n return re.test(filepath) || re.test(path.basename(filepath));\n };\n};\n\n/**\n * Returns the given value unchanced.\n * @return {any}\n */\n\nutils.identity = function(val) {\n return val;\n};\n\n/**\n * Determines the filepath to return based on the provided options.\n * @return {any}\n */\n\nutils.value = function(str, unixify, options) {\n if (options && options.unixify === false) {\n return str;\n }\n if (options && typeof options.unixify === 'function') {\n return options.unixify(str);\n }\n return unixify(str);\n};\n\n/**\n * Returns a function that normalizes slashes in a string to forward\n * slashes, strips `./` from beginning of paths, and optionally unescapes\n * special characters.\n * @return {Function}\n */\n\nutils.unixify = function(options) {\n var opts = options || {};\n return function(filepath) {\n if (opts.stripPrefix !== false) {\n filepath = utils.stripPrefix(filepath);\n }\n if (opts.unescape === true) {\n filepath = utils.unescape(filepath);\n }\n if (opts.unixify === true || utils.isWindows()) {\n filepath = utils.toPosixPath(filepath);\n }\n return filepath;\n };\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/nanomatch/lib/utils.js?"); + +/***/ }), + +/***/ "./node_modules/nanomatch/node_modules/define-property/index.js": +/*!**********************************************************************!*\ + !*** ./node_modules/nanomatch/node_modules/define-property/index.js ***! + \**********************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * define-property \n *\n * Copyright (c) 2015-2018, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar isobject = __webpack_require__(/*! isobject */ \"./node_modules/isobject/index.js\");\nvar isDescriptor = __webpack_require__(/*! is-descriptor */ \"./node_modules/is-descriptor/index.js\");\nvar define = (typeof Reflect !== 'undefined' && Reflect.defineProperty)\n ? Reflect.defineProperty\n : Object.defineProperty;\n\nmodule.exports = function defineProperty(obj, key, val) {\n if (!isobject(obj) && typeof obj !== 'function' && !Array.isArray(obj)) {\n throw new TypeError('expected an object, function, or array');\n }\n\n if (typeof key !== 'string') {\n throw new TypeError('expected \"key\" to be a string');\n }\n\n if (isDescriptor(val)) {\n define(obj, key, val);\n return obj;\n }\n\n define(obj, key, {\n configurable: true,\n enumerable: false,\n writable: true,\n value: val\n });\n\n return obj;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/nanomatch/node_modules/define-property/index.js?"); + +/***/ }), + +/***/ "./node_modules/nanomatch/node_modules/extend-shallow/index.js": +/*!*********************************************************************!*\ + !*** ./node_modules/nanomatch/node_modules/extend-shallow/index.js ***! + \*********************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar isExtendable = __webpack_require__(/*! is-extendable */ \"./node_modules/nanomatch/node_modules/is-extendable/index.js\");\nvar assignSymbols = __webpack_require__(/*! assign-symbols */ \"./node_modules/assign-symbols/index.js\");\n\nmodule.exports = Object.assign || function(obj/*, objects*/) {\n if (obj === null || typeof obj === 'undefined') {\n throw new TypeError('Cannot convert undefined or null to object');\n }\n if (!isObject(obj)) {\n obj = {};\n }\n for (var i = 1; i < arguments.length; i++) {\n var val = arguments[i];\n if (isString(val)) {\n val = toObject(val);\n }\n if (isObject(val)) {\n assign(obj, val);\n assignSymbols(obj, val);\n }\n }\n return obj;\n};\n\nfunction assign(a, b) {\n for (var key in b) {\n if (hasOwn(b, key)) {\n a[key] = b[key];\n }\n }\n}\n\nfunction isString(val) {\n return (val && typeof val === 'string');\n}\n\nfunction toObject(str) {\n var obj = {};\n for (var i in str) {\n obj[i] = str[i];\n }\n return obj;\n}\n\nfunction isObject(val) {\n return (val && typeof val === 'object') || isExtendable(val);\n}\n\n/**\n * Returns true if the given `key` is an own property of `obj`.\n */\n\nfunction hasOwn(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nfunction isEnum(obj, key) {\n return Object.prototype.propertyIsEnumerable.call(obj, key);\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/nanomatch/node_modules/extend-shallow/index.js?"); + +/***/ }), + +/***/ "./node_modules/nanomatch/node_modules/is-extendable/index.js": +/*!********************************************************************!*\ + !*** ./node_modules/nanomatch/node_modules/is-extendable/index.js ***! + \********************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * is-extendable \n *\n * Copyright (c) 2015-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar isPlainObject = __webpack_require__(/*! is-plain-object */ \"./node_modules/is-plain-object/index.js\");\n\nmodule.exports = function isExtendable(val) {\n return isPlainObject(val) || typeof val === 'function' || Array.isArray(val);\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/nanomatch/node_modules/is-extendable/index.js?"); + +/***/ }), + +/***/ "./node_modules/normalize-path/index.js": +/*!**********************************************!*\ + !*** ./node_modules/normalize-path/index.js ***! + \**********************************************/ +/***/ ((module) => { + +eval("/*!\n * normalize-path \n *\n * Copyright (c) 2014-2018, Jon Schlinkert.\n * Released under the MIT License.\n */\n\nmodule.exports = function(path, stripTrailing) {\n if (typeof path !== 'string') {\n throw new TypeError('expected path to be a string');\n }\n\n if (path === '\\\\' || path === '/') return '/';\n\n var len = path.length;\n if (len <= 1) return path;\n\n // ensure that win32 namespaces has two leading slashes, so that the path is\n // handled properly by the win32 version of path.parse() after being normalized\n // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces\n var prefix = '';\n if (len > 4 && path[3] === '\\\\') {\n var ch = path[2];\n if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\\\\\') {\n path = path.slice(2);\n prefix = '//';\n }\n }\n\n var segs = path.split(/[/\\\\]+/);\n if (stripTrailing !== false && segs[segs.length - 1] === '') {\n segs.pop();\n }\n return prefix + segs.join('/');\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/normalize-path/index.js?"); + +/***/ }), + +/***/ "./node_modules/object-copy/index.js": +/*!*******************************************!*\ + !*** ./node_modules/object-copy/index.js ***! + \*******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar typeOf = __webpack_require__(/*! kind-of */ \"./node_modules/object-copy/node_modules/kind-of/index.js\");\nvar copyDescriptor = __webpack_require__(/*! copy-descriptor */ \"./node_modules/copy-descriptor/index.js\");\nvar define = __webpack_require__(/*! define-property */ \"./node_modules/define-property/index.js\");\n\n/**\n * Copy static properties, prototype properties, and descriptors from one object to another.\n *\n * ```js\n * function App() {}\n * var proto = App.prototype;\n * App.prototype.set = function() {};\n * App.prototype.get = function() {};\n *\n * var obj = {};\n * copy(obj, proto);\n * ```\n * @param {Object} `receiver`\n * @param {Object} `provider`\n * @param {String|Array} `omit` One or more properties to omit\n * @return {Object}\n * @api public\n */\n\nfunction copy(receiver, provider, omit) {\n if (!isObject(receiver)) {\n throw new TypeError('expected receiving object to be an object.');\n }\n if (!isObject(provider)) {\n throw new TypeError('expected providing object to be an object.');\n }\n\n var props = nativeKeys(provider);\n var keys = Object.keys(provider);\n var len = props.length;\n omit = arrayify(omit);\n\n while (len--) {\n var key = props[len];\n\n if (has(keys, key)) {\n define(receiver, key, provider[key]);\n } else if (!(key in receiver) && !has(omit, key)) {\n copyDescriptor(receiver, provider, key);\n }\n }\n};\n\n/**\n * Return true if the given value is an object or function\n */\n\nfunction isObject(val) {\n return typeOf(val) === 'object' || typeof val === 'function';\n}\n\n/**\n * Returns true if an array has any of the given elements, or an\n * object has any of the give keys.\n *\n * ```js\n * has(['a', 'b', 'c'], 'c');\n * //=> true\n *\n * has(['a', 'b', 'c'], ['c', 'z']);\n * //=> true\n *\n * has({a: 'b', c: 'd'}, ['c', 'z']);\n * //=> true\n * ```\n * @param {Object} `obj`\n * @param {String|Array} `val`\n * @return {Boolean}\n */\n\nfunction has(obj, val) {\n val = arrayify(val);\n var len = val.length;\n\n if (isObject(obj)) {\n for (var key in obj) {\n if (val.indexOf(key) > -1) {\n return true;\n }\n }\n\n var keys = nativeKeys(obj);\n return has(keys, val);\n }\n\n if (Array.isArray(obj)) {\n var arr = obj;\n while (len--) {\n if (arr.indexOf(val[len]) > -1) {\n return true;\n }\n }\n return false;\n }\n\n throw new TypeError('expected an array or object.');\n}\n\n/**\n * Cast the given value to an array.\n *\n * ```js\n * arrayify('foo');\n * //=> ['foo']\n *\n * arrayify(['foo']);\n * //=> ['foo']\n * ```\n *\n * @param {String|Array} `val`\n * @return {Array}\n */\n\nfunction arrayify(val) {\n return val ? (Array.isArray(val) ? val : [val]) : [];\n}\n\n/**\n * Returns true if a value has a `contructor`\n *\n * ```js\n * hasConstructor({});\n * //=> true\n *\n * hasConstructor(Object.create(null));\n * //=> false\n * ```\n * @param {Object} `value`\n * @return {Boolean}\n */\n\nfunction hasConstructor(val) {\n return isObject(val) && typeof val.constructor !== 'undefined';\n}\n\n/**\n * Get the native `ownPropertyNames` from the constructor of the\n * given `object`. An empty array is returned if the object does\n * not have a constructor.\n *\n * ```js\n * nativeKeys({a: 'b', b: 'c', c: 'd'})\n * //=> ['a', 'b', 'c']\n *\n * nativeKeys(function(){})\n * //=> ['length', 'caller']\n * ```\n *\n * @param {Object} `obj` Object that has a `constructor`.\n * @return {Array} Array of keys.\n */\n\nfunction nativeKeys(val) {\n if (!hasConstructor(val)) return [];\n return Object.getOwnPropertyNames(val);\n}\n\n/**\n * Expose `copy`\n */\n\nmodule.exports = copy;\n\n/**\n * Expose `copy.has` for tests\n */\n\nmodule.exports.has = has;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/object-copy/index.js?"); + +/***/ }), + +/***/ "./node_modules/object-copy/node_modules/kind-of/index.js": +/*!****************************************************************!*\ + !*** ./node_modules/object-copy/node_modules/kind-of/index.js ***! + \****************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var isBuffer = __webpack_require__(/*! is-buffer */ \"./node_modules/is-buffer/index.js\");\nvar toString = Object.prototype.toString;\n\n/**\n * Get the native `typeof` a value.\n *\n * @param {*} `val`\n * @return {*} Native javascript type\n */\n\nmodule.exports = function kindOf(val) {\n // primitivies\n if (typeof val === 'undefined') {\n return 'undefined';\n }\n if (val === null) {\n return 'null';\n }\n if (val === true || val === false || val instanceof Boolean) {\n return 'boolean';\n }\n if (typeof val === 'string' || val instanceof String) {\n return 'string';\n }\n if (typeof val === 'number' || val instanceof Number) {\n return 'number';\n }\n\n // functions\n if (typeof val === 'function' || val instanceof Function) {\n return 'function';\n }\n\n // array\n if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {\n return 'array';\n }\n\n // check for instances of RegExp and Date before calling `toString`\n if (val instanceof RegExp) {\n return 'regexp';\n }\n if (val instanceof Date) {\n return 'date';\n }\n\n // other objects\n var type = toString.call(val);\n\n if (type === '[object RegExp]') {\n return 'regexp';\n }\n if (type === '[object Date]') {\n return 'date';\n }\n if (type === '[object Arguments]') {\n return 'arguments';\n }\n if (type === '[object Error]') {\n return 'error';\n }\n\n // buffer\n if (isBuffer(val)) {\n return 'buffer';\n }\n\n // es6: Map, WeakMap, Set, WeakSet\n if (type === '[object Set]') {\n return 'set';\n }\n if (type === '[object WeakSet]') {\n return 'weakset';\n }\n if (type === '[object Map]') {\n return 'map';\n }\n if (type === '[object WeakMap]') {\n return 'weakmap';\n }\n if (type === '[object Symbol]') {\n return 'symbol';\n }\n\n // typed arrays\n if (type === '[object Int8Array]') {\n return 'int8array';\n }\n if (type === '[object Uint8Array]') {\n return 'uint8array';\n }\n if (type === '[object Uint8ClampedArray]') {\n return 'uint8clampedarray';\n }\n if (type === '[object Int16Array]') {\n return 'int16array';\n }\n if (type === '[object Uint16Array]') {\n return 'uint16array';\n }\n if (type === '[object Int32Array]') {\n return 'int32array';\n }\n if (type === '[object Uint32Array]') {\n return 'uint32array';\n }\n if (type === '[object Float32Array]') {\n return 'float32array';\n }\n if (type === '[object Float64Array]') {\n return 'float64array';\n }\n\n // must be a plain object\n return 'object';\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/object-copy/node_modules/kind-of/index.js?"); + +/***/ }), + +/***/ "./node_modules/object-visit/index.js": +/*!********************************************!*\ + !*** ./node_modules/object-visit/index.js ***! + \********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * object-visit \n *\n * Copyright (c) 2015, 2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar isObject = __webpack_require__(/*! isobject */ \"./node_modules/isobject/index.js\");\n\nmodule.exports = function visit(thisArg, method, target, val) {\n if (!isObject(thisArg) && typeof thisArg !== 'function') {\n throw new Error('object-visit expects `thisArg` to be an object.');\n }\n\n if (typeof method !== 'string') {\n throw new Error('object-visit expects `method` name to be a string');\n }\n\n if (typeof thisArg[method] !== 'function') {\n return thisArg;\n }\n\n var args = [].slice.call(arguments, 3);\n target = target || {};\n\n for (var key in target) {\n var arr = [key, target[key]].concat(args);\n thisArg[method].apply(thisArg, arr);\n }\n return thisArg;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/object-visit/index.js?"); + +/***/ }), + +/***/ "./node_modules/object.pick/index.js": +/*!*******************************************!*\ + !*** ./node_modules/object.pick/index.js ***! + \*******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * object.pick \n *\n * Copyright (c) 2014-2015 Jon Schlinkert, contributors.\n * Licensed under the MIT License\n */\n\n\n\nvar isObject = __webpack_require__(/*! isobject */ \"./node_modules/isobject/index.js\");\n\nmodule.exports = function pick(obj, keys) {\n if (!isObject(obj) && typeof obj !== 'function') {\n return {};\n }\n\n var res = {};\n if (typeof keys === 'string') {\n if (keys in obj) {\n res[keys] = obj[keys];\n }\n return res;\n }\n\n var len = keys.length;\n var idx = -1;\n\n while (++idx < len) {\n var key = keys[idx];\n if (key in obj) {\n res[key] = obj[key];\n }\n }\n return res;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/object.pick/index.js?"); + +/***/ }), + +/***/ "./node_modules/pascalcase/index.js": +/*!******************************************!*\ + !*** ./node_modules/pascalcase/index.js ***! + \******************************************/ +/***/ ((module) => { + +eval("/*!\n * pascalcase \n *\n * Copyright (c) 2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\nfunction pascalcase(str) {\n if (typeof str !== 'string') {\n throw new TypeError('expected a string.');\n }\n str = str.replace(/([A-Z])/g, ' $1');\n if (str.length === 1) { return str.toUpperCase(); }\n str = str.replace(/^[\\W_]+|[\\W_]+$/g, '').toLowerCase();\n str = str.charAt(0).toUpperCase() + str.slice(1);\n return str.replace(/[\\W_]+(\\w|$)/g, function (_, ch) {\n return ch.toUpperCase();\n });\n}\n\nmodule.exports = pascalcase;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/pascalcase/index.js?"); + +/***/ }), + +/***/ "./node_modules/path-is-absolute/index.js": +/*!************************************************!*\ + !*** ./node_modules/path-is-absolute/index.js ***! + \************************************************/ +/***/ ((module) => { + +"use strict"; +eval("\n\nfunction posix(path) {\n\treturn path.charAt(0) === '/';\n}\n\nfunction win32(path) {\n\t// https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56\n\tvar splitDeviceRe = /^([a-zA-Z]:|[\\\\\\/]{2}[^\\\\\\/]+[\\\\\\/]+[^\\\\\\/]+)?([\\\\\\/])?([\\s\\S]*?)$/;\n\tvar result = splitDeviceRe.exec(path);\n\tvar device = result[1] || '';\n\tvar isUnc = Boolean(device && device.charAt(1) !== ':');\n\n\t// UNC paths are always absolute\n\treturn Boolean(result[2] || isUnc);\n}\n\nmodule.exports = process.platform === 'win32' ? win32 : posix;\nmodule.exports.posix = posix;\nmodule.exports.win32 = win32;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/path-is-absolute/index.js?"); + +/***/ }), + +/***/ "./node_modules/posix-character-classes/index.js": +/*!*******************************************************!*\ + !*** ./node_modules/posix-character-classes/index.js ***! + \*******************************************************/ +/***/ ((module) => { + +"use strict"; +eval("\n\n/**\n * POSIX character classes\n */\n\nmodule.exports = {\n alnum: 'a-zA-Z0-9',\n alpha: 'a-zA-Z',\n ascii: '\\\\x00-\\\\x7F',\n blank: ' \\\\t',\n cntrl: '\\\\x00-\\\\x1F\\\\x7F',\n digit: '0-9',\n graph: '\\\\x21-\\\\x7E',\n lower: 'a-z',\n print: '\\\\x20-\\\\x7E ',\n punct: '\\\\-!\"#$%&\\'()\\\\*+,./:;<=>?@[\\\\]^_`{|}~',\n space: ' \\\\t\\\\r\\\\n\\\\v\\\\f',\n upper: 'A-Z',\n word: 'A-Za-z0-9_',\n xdigit: 'A-Fa-f0-9'\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/posix-character-classes/index.js?"); + +/***/ }), + +/***/ "./node_modules/process-nextick-args/index.js": +/*!****************************************************!*\ + !*** ./node_modules/process-nextick-args/index.js ***! + \****************************************************/ +/***/ ((module) => { + +"use strict"; +eval("\n\nif (typeof process === 'undefined' ||\n !process.version ||\n process.version.indexOf('v0.') === 0 ||\n process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {\n module.exports = { nextTick: nextTick };\n} else {\n module.exports = process\n}\n\nfunction nextTick(fn, arg1, arg2, arg3) {\n if (typeof fn !== 'function') {\n throw new TypeError('\"callback\" argument must be a function');\n }\n var len = arguments.length;\n var args, i;\n switch (len) {\n case 0:\n case 1:\n return process.nextTick(fn);\n case 2:\n return process.nextTick(function afterTickOne() {\n fn.call(null, arg1);\n });\n case 3:\n return process.nextTick(function afterTickTwo() {\n fn.call(null, arg1, arg2);\n });\n case 4:\n return process.nextTick(function afterTickThree() {\n fn.call(null, arg1, arg2, arg3);\n });\n default:\n args = new Array(len - 1);\n i = 0;\n while (i < args.length) {\n args[i++] = arguments[i];\n }\n return process.nextTick(function afterTick() {\n fn.apply(null, args);\n });\n }\n}\n\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/process-nextick-args/index.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/lib/_stream_duplex.js": +/*!************************************************************!*\ + !*** ./node_modules/readable-stream/lib/_stream_duplex.js ***! + \************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n\n\n\n/**/\n\nvar pna = __webpack_require__(/*! process-nextick-args */ \"./node_modules/process-nextick-args/index.js\");\n/**/\n\n/**/\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n for (var key in obj) {\n keys.push(key);\n }return keys;\n};\n/**/\n\nmodule.exports = Duplex;\n\n/**/\nvar util = Object.create(__webpack_require__(/*! core-util-is */ \"./node_modules/core-util-is/lib/util.js\"));\nutil.inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits.js\");\n/**/\n\nvar Readable = __webpack_require__(/*! ./_stream_readable */ \"./node_modules/readable-stream/lib/_stream_readable.js\");\nvar Writable = __webpack_require__(/*! ./_stream_writable */ \"./node_modules/readable-stream/lib/_stream_writable.js\");\n\nutil.inherits(Duplex, Readable);\n\n{\n // avoid scope creep, the keys array can then be collected\n var keys = objectKeys(Writable.prototype);\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n\n Readable.call(this, options);\n Writable.call(this, options);\n\n if (options && options.readable === false) this.readable = false;\n\n if (options && options.writable === false) this.writable = false;\n\n this.allowHalfOpen = true;\n if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;\n\n this.once('end', onend);\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// the no-half-open enforcer\nfunction onend() {\n // if we allow half-open state, or if the writable side ended,\n // then we're ok.\n if (this.allowHalfOpen || this._writableState.ended) return;\n\n // no more data can be written.\n // But allow more writes to happen in this tick.\n pna.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});\n\nDuplex.prototype._destroy = function (err, cb) {\n this.push(null);\n this.end();\n\n pna.nextTick(cb, err);\n};\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/readable-stream/lib/_stream_duplex.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/lib/_stream_passthrough.js": +/*!*****************************************************************!*\ + !*** ./node_modules/readable-stream/lib/_stream_passthrough.js ***! + \*****************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\n\n\nmodule.exports = PassThrough;\n\nvar Transform = __webpack_require__(/*! ./_stream_transform */ \"./node_modules/readable-stream/lib/_stream_transform.js\");\n\n/**/\nvar util = Object.create(__webpack_require__(/*! core-util-is */ \"./node_modules/core-util-is/lib/util.js\"));\nutil.inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits.js\");\n/**/\n\nutil.inherits(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/readable-stream/lib/_stream_passthrough.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/lib/_stream_readable.js": +/*!**************************************************************!*\ + !*** ./node_modules/readable-stream/lib/_stream_readable.js ***! + \**************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n\n/**/\n\nvar pna = __webpack_require__(/*! process-nextick-args */ \"./node_modules/process-nextick-args/index.js\");\n/**/\n\nmodule.exports = Readable;\n\n/**/\nvar isArray = __webpack_require__(/*! isarray */ \"./node_modules/isarray/index.js\");\n/**/\n\n/**/\nvar Duplex;\n/**/\n\nReadable.ReadableState = ReadableState;\n\n/**/\nvar EE = __webpack_require__(/*! events */ \"events\").EventEmitter;\n\nvar EElistenerCount = function (emitter, type) {\n return emitter.listeners(type).length;\n};\n/**/\n\n/**/\nvar Stream = __webpack_require__(/*! ./internal/streams/stream */ \"./node_modules/readable-stream/lib/internal/streams/stream.js\");\n/**/\n\n/**/\n\nvar Buffer = __webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer;\nvar OurUint8Array = global.Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/**/\n\n/**/\nvar util = Object.create(__webpack_require__(/*! core-util-is */ \"./node_modules/core-util-is/lib/util.js\"));\nutil.inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits.js\");\n/**/\n\n/**/\nvar debugUtil = __webpack_require__(/*! util */ \"util\");\nvar debug = void 0;\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function () {};\n}\n/**/\n\nvar BufferList = __webpack_require__(/*! ./internal/streams/BufferList */ \"./node_modules/readable-stream/lib/internal/streams/BufferList.js\");\nvar destroyImpl = __webpack_require__(/*! ./internal/streams/destroy */ \"./node_modules/readable-stream/lib/internal/streams/destroy.js\");\nvar StringDecoder;\n\nutil.inherits(Readable, Stream);\n\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);\n\n // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/readable-stream/lib/_stream_duplex.js\");\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;\n\n // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n var hwm = options.highWaterMark;\n var readableHwm = options.readableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false;\n\n // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n this.sync = true;\n\n // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // the number of writers that are awaiting a drain event in .pipe()s\n this.awaitDrain = 0;\n\n // if true, a maybeReadMore has been scheduled\n this.readingMore = false;\n\n this.decoder = null;\n this.encoding = null;\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = __webpack_require__(/*! string_decoder/ */ \"./node_modules/string_decoder/lib/string_decoder.js\").StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/readable-stream/lib/_stream_duplex.js\");\n\n if (!(this instanceof Readable)) return new Readable(options);\n\n this._readableState = new ReadableState(options, this);\n\n // legacy\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined) {\n return false;\n }\n return this._readableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n }\n});\n\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\nReadable.prototype._destroy = function (err, cb) {\n this.push(null);\n cb(err);\n};\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n};\n\n// Unshift should *always* be something directly out of read()\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n var state = stream._readableState;\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n if (er) {\n stream.emit('error', er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n stream.emit('error', new Error('stream.push() after EOF'));\n } else {\n state.reading = false;\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n }\n }\n\n return needMoreData(state);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n stream.emit('data', chunk);\n stream.read(0);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n\n if (state.needReadable) emitReadable(stream);\n }\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n return er;\n}\n\n// if it's past the high water mark, we can push in some more.\n// Also, if we have no data yet, we can stand some\n// more bytes. This is to work around cases where hwm=0,\n// such as the repl. Also, if the push() triggered a\n// readable event, and the user called read(largeNumber) such that\n// needReadable was set, then we ought to push more, so that another\n// 'readable' event will be triggered.\nfunction needMoreData(state) {\n return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n};\n\n// backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = __webpack_require__(/*! string_decoder/ */ \"./node_modules/string_decoder/lib/string_decoder.js\").StringDecoder;\n this._readableState.decoder = new StringDecoder(enc);\n this._readableState.encoding = enc;\n return this;\n};\n\n// Don't raise the hwm > 8MB\nvar MAX_HWM = 0x800000;\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n return n;\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n }\n // If we're asking for more than the current hwm, then raise the hwm.\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n;\n // Don't have enough\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n return state.length;\n}\n\n// you can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n\n if (n !== 0) state.emittedReadable = false;\n\n // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state);\n\n // if we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n var doRead = state.needReadable;\n debug('need readable', doRead);\n\n // if we currently have less than the highWaterMark, then also read some\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n }\n\n // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true;\n // if the length is currently zero, then we *need* a readable event.\n if (state.length === 0) state.needReadable = true;\n // call internal read method\n this._read(state.highWaterMark);\n state.sync = false;\n // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = true;\n n = 0;\n } else {\n state.length -= n;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true;\n\n // If we tried to read() past the EOF, then emit end on the next tick.\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n if (state.ended) return;\n if (state.decoder) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n state.ended = true;\n\n // emit 'readable' now to make sure it gets picked up.\n emitReadable(stream);\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n var state = stream._readableState;\n state.needReadable = false;\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);\n }\n}\n\nfunction emitReadable_(stream) {\n debug('emit readable');\n stream.emit('readable');\n flow(stream);\n}\n\n// at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n pna.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n var len = state.length;\n while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length)\n // didn't get any data, stop spinning.\n break;else len = state.length;\n }\n state.readingMore = false;\n}\n\n// abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n this.emit('error', new Error('_read() is not implemented'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n default:\n state.pipes.push(dest);\n break;\n }\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);\n\n dest.on('unpipe', onunpipe);\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n }\n\n // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n\n var cleanedUp = false;\n function cleanup() {\n debug('cleanup');\n // cleanup event handlers once the pipe is broken\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n\n cleanedUp = true;\n\n // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n // If the user pushes more data while we're writing to dest then we'll end up\n // in ondata again. However, we only want to increase awaitDrain once because\n // dest will only emit one 'drain' event for the multiple writes.\n // => Introduce a guard on increasing awaitDrain.\n var increasedAwaitDrain = false;\n src.on('data', ondata);\n function ondata(chunk) {\n debug('ondata');\n increasedAwaitDrain = false;\n var ret = dest.write(chunk);\n if (false === ret && !increasedAwaitDrain) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', src._readableState.awaitDrain);\n src._readableState.awaitDrain++;\n increasedAwaitDrain = true;\n }\n src.pause();\n }\n }\n\n // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);\n }\n\n // Make sure our error handler is attached before userland ones.\n prependListener(dest, 'error', onerror);\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n dest.once('close', onclose);\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n }\n\n // tell the dest that it's being piped to\n dest.emit('pipe', src);\n\n // start the flow if it hasn't been started already.\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function () {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = { hasUnpiped: false };\n\n // if we're not piping anywhere, then do nothing.\n if (state.pipesCount === 0) return this;\n\n // just one destination. most common case.\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n\n if (!dest) dest = state.pipes;\n\n // got a match.\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n }\n\n // slow case. multiple pipe destinations.\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, unpipeInfo);\n }return this;\n }\n\n // try to find the right one.\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n\n dest.emit('unpipe', this, unpipeInfo);\n\n return this;\n};\n\n// set up data events if they are asked for\n// Ensure readable listeners eventually get something\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n\n if (ev === 'data') {\n // Start flowing on next tick if stream isn't explicitly paused\n if (this._readableState.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n var state = this._readableState;\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.emittedReadable = false;\n if (!state.reading) {\n pna.nextTick(nReadingNextTick, this);\n } else if (state.length) {\n emitReadable(this);\n }\n }\n }\n\n return res;\n};\nReadable.prototype.addListener = Readable.prototype.on;\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n var state = this._readableState;\n if (!state.flowing) {\n debug('resume');\n state.flowing = true;\n resume(this, state);\n }\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n pna.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n if (!state.reading) {\n debug('resume read 0');\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n state.awaitDrain = 0;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n if (false !== this._readableState.flowing) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n while (state.flowing && stream.read() !== null) {}\n}\n\n// wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n\n stream.on('end', function () {\n debug('wrapped end');\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk);\n\n // don't skip over falsy values in objectMode\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n if (!ret) {\n paused = true;\n stream.pause();\n }\n });\n\n // proxy all the other methods.\n // important when wrapping filters and duplexes.\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function (method) {\n return function () {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n }\n\n // proxy certain important events.\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n }\n\n // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n this._read = function (n) {\n debug('wrapped _read', n);\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._readableState.highWaterMark;\n }\n});\n\n// exposed for testing purposes only.\nReadable._fromList = fromList;\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = fromListPartial(n, state.buffer, state.decoder);\n }\n\n return ret;\n}\n\n// Extracts only enough buffered data to satisfy the amount requested.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromListPartial(n, list, hasStrings) {\n var ret;\n if (n < list.head.data.length) {\n // slice is the same for buffers and strings\n ret = list.head.data.slice(0, n);\n list.head.data = list.head.data.slice(n);\n } else if (n === list.head.data.length) {\n // first chunk is a perfect match\n ret = list.shift();\n } else {\n // result spans more than one buffer\n ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);\n }\n return ret;\n}\n\n// Copies a specified amount of characters from the list of buffered data\n// chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBufferString(n, list) {\n var p = list.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = str.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\n// Copies a specified amount of bytes from the list of buffered data chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n\n // If we get here before consuming all the bytes, then that is a\n // bug in node. Should never happen.\n if (state.length > 0) throw new Error('\"endReadable()\" called on non-empty stream');\n\n if (!state.endEmitted) {\n state.ended = true;\n pna.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n // Check that we didn't get one last unshift.\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n }\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n return -1;\n}\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/readable-stream/lib/_stream_readable.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/lib/_stream_transform.js": +/*!***************************************************************!*\ + !*** ./node_modules/readable-stream/lib/_stream_transform.js ***! + \***************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n\n\nmodule.exports = Transform;\n\nvar Duplex = __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/readable-stream/lib/_stream_duplex.js\");\n\n/**/\nvar util = Object.create(__webpack_require__(/*! core-util-is */ \"./node_modules/core-util-is/lib/util.js\"));\nutil.inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits.js\");\n/**/\n\nutil.inherits(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n\n var cb = ts.writecb;\n\n if (!cb) {\n return this.emit('error', new Error('write callback called multiple times'));\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n\n cb(er);\n\n var rs = this._readableState;\n rs.reading = false;\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n\n Duplex.call(this, options);\n\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n };\n\n // start out asking for a readable event once data is transformed.\n this._readableState.needReadable = true;\n\n // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n\n if (typeof options.flush === 'function') this._flush = options.flush;\n }\n\n // When the writable side finishes, then flush out anything remaining.\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function') {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n};\n\n// This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\nTransform.prototype._transform = function (chunk, encoding, cb) {\n throw new Error('_transform() is not implemented');\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n};\n\n// Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && ts.writecb && !ts.transforming) {\n ts.transforming = true;\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n var _this2 = this;\n\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n _this2.emit('close');\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data);\n\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');\n\n if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');\n\n return stream.push(null);\n}\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/readable-stream/lib/_stream_transform.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/lib/_stream_writable.js": +/*!**************************************************************!*\ + !*** ./node_modules/readable-stream/lib/_stream_writable.js ***! + \**************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n\n\n/**/\n\nvar pna = __webpack_require__(/*! process-nextick-args */ \"./node_modules/process-nextick-args/index.js\");\n/**/\n\nmodule.exports = Writable;\n\n/* */\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n}\n\n// It seems a linked list but it is not\n// there will be only 2 of these for each stream\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* */\n\n/**/\nvar asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;\n/**/\n\n/**/\nvar Duplex;\n/**/\n\nWritable.WritableState = WritableState;\n\n/**/\nvar util = Object.create(__webpack_require__(/*! core-util-is */ \"./node_modules/core-util-is/lib/util.js\"));\nutil.inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits.js\");\n/**/\n\n/**/\nvar internalUtil = {\n deprecate: __webpack_require__(/*! util-deprecate */ \"./node_modules/util-deprecate/node.js\")\n};\n/**/\n\n/**/\nvar Stream = __webpack_require__(/*! ./internal/streams/stream */ \"./node_modules/readable-stream/lib/internal/streams/stream.js\");\n/**/\n\n/**/\n\nvar Buffer = __webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer;\nvar OurUint8Array = global.Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/**/\n\nvar destroyImpl = __webpack_require__(/*! ./internal/streams/destroy */ \"./node_modules/readable-stream/lib/internal/streams/destroy.js\");\n\nutil.inherits(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/readable-stream/lib/_stream_duplex.js\");\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;\n\n // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n var hwm = options.highWaterMark;\n var writableHwm = options.writableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // if _final has been called\n this.finalCalled = false;\n\n // drain event flag.\n this.needDrain = false;\n // at the start of calling end()\n this.ending = false;\n // when end() has been called, and returned\n this.ended = false;\n // when 'finish' is emitted\n this.finished = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0;\n\n // a flag to see when we're in the middle of a write.\n this.writing = false;\n\n // when true all writes will be buffered until .uncork() call\n this.corked = 0;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false;\n\n // the callback that's passed to _write(chunk,cb)\n this.onwrite = function (er) {\n onwrite(stream, er);\n };\n\n // the callback that the user supplies to write(chunk,encoding,cb)\n this.writecb = null;\n\n // the amount that is being written when _write is called.\n this.writelen = 0;\n\n this.bufferedRequest = null;\n this.lastBufferedRequest = null;\n\n // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n this.pendingcb = 0;\n\n // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n this.prefinished = false;\n\n // True if the error was already emitted and should not be thrown again\n this.errorEmitted = false;\n\n // count buffered requests\n this.bufferedRequestCount = 0;\n\n // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n while (current) {\n out.push(current);\n current = current.next;\n }\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function () {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})();\n\n// Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\nvar realHasInstance;\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function (object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function (object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/readable-stream/lib/_stream_duplex.js\");\n\n // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {\n return new Writable(options);\n }\n\n this._writableState = new WritableState(options, this);\n\n // legacy.\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n\n if (typeof options.writev === 'function') this._writev = options.writev;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n}\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n this.emit('error', new Error('Cannot pipe, not readable'));\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new Error('write after end');\n // TODO: defer error events consistently everywhere, not just the cb\n stream.emit('error', er);\n pna.nextTick(cb, er);\n}\n\n// Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\nfunction validChunk(stream, state, chunk, cb) {\n var valid = true;\n var er = false;\n\n if (chunk === null) {\n er = new TypeError('May not write null values to stream');\n } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n if (er) {\n stream.emit('error', er);\n pna.nextTick(cb, er);\n valid = false;\n }\n return valid;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n\n if (typeof cb !== 'function') cb = nop;\n\n if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n\n return ret;\n};\n\nWritable.prototype.cork = function () {\n var state = this._writableState;\n\n state.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n\n if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n var len = state.objectMode ? 1 : chunk.length;\n\n state.length += len;\n\n var ret = state.length < state.highWaterMark;\n // we must ensure that previous needDrain will not be reset to false.\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n pna.nextTick(cb, er);\n // this can emit finish, and it will always happen\n // after error\n pna.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n // this can emit finish, but finish must\n // always follow error\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n\n onwriteStateUpdate(state);\n\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state);\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n /**/\n asyncWrite(afterWrite, stream, state, finished, cb);\n /**/\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n}\n\n// Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n}\n\n// if there's something in the buffer waiting, then process it\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n\n var count = 0;\n var allBuffers = true;\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n buffer.allBuffers = allBuffers;\n\n doWrite(stream, state, true, state.length, buffer, '', holder.finish);\n\n // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n state.pendingcb++;\n state.lastBufferedRequest = null;\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--;\n // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new Error('_write() is not implemented'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);\n\n // .end() fully uncorks\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n }\n\n // ignore unnecessary end() calls.\n if (!state.ending && !state.finished) endWritable(this, state, cb);\n};\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n if (err) {\n stream.emit('error', err);\n }\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function') {\n state.pendingcb++;\n state.finalCalled = true;\n pna.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n if (need) {\n prefinish(stream, state);\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n }\n }\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n if (cb) {\n if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);\n }\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n }\n if (state.corkedRequestsFree) {\n state.corkedRequestsFree.next = corkReq;\n } else {\n state.corkedRequestsFree = corkReq;\n }\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n get: function () {\n if (this._writableState === undefined) {\n return false;\n }\n return this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._writableState.destroyed = value;\n }\n});\n\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\nWritable.prototype._destroy = function (err, cb) {\n this.end();\n cb(err);\n};\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/readable-stream/lib/_stream_writable.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/lib/internal/streams/BufferList.js": +/*!*************************************************************************!*\ + !*** ./node_modules/readable-stream/lib/internal/streams/BufferList.js ***! + \*************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar Buffer = __webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer;\nvar util = __webpack_require__(/*! util */ \"util\");\n\nfunction copyBuffer(src, target, offset) {\n src.copy(target, offset);\n}\n\nmodule.exports = function () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n BufferList.prototype.push = function push(v) {\n var entry = { data: v, next: null };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n };\n\n BufferList.prototype.unshift = function unshift(v) {\n var entry = { data: v, next: this.head };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n };\n\n BufferList.prototype.shift = function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n };\n\n BufferList.prototype.clear = function clear() {\n this.head = this.tail = null;\n this.length = 0;\n };\n\n BufferList.prototype.join = function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n while (p = p.next) {\n ret += s + p.data;\n }return ret;\n };\n\n BufferList.prototype.concat = function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n if (this.length === 1) return this.head.data;\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n return ret;\n };\n\n return BufferList;\n}();\n\nif (util && util.inspect && util.inspect.custom) {\n module.exports.prototype[util.inspect.custom] = function () {\n var obj = util.inspect({ length: this.length });\n return this.constructor.name + ' ' + obj;\n };\n}\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/readable-stream/lib/internal/streams/BufferList.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/lib/internal/streams/destroy.js": +/*!**********************************************************************!*\ + !*** ./node_modules/readable-stream/lib/internal/streams/destroy.js ***! + \**********************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\n/**/\n\nvar pna = __webpack_require__(/*! process-nextick-args */ \"./node_modules/process-nextick-args/index.js\");\n/**/\n\n// undocumented cb() API, needed for core, not for public API\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {\n pna.nextTick(emitErrorNT, this, err);\n }\n return this;\n }\n\n // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n }\n\n // if this is a duplex stream mark the writable part as destroyed as well\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n pna.nextTick(emitErrorNT, _this, err);\n if (_this._writableState) {\n _this._writableState.errorEmitted = true;\n }\n } else if (cb) {\n cb(err);\n }\n });\n\n return this;\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy\n};\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/readable-stream/lib/internal/streams/destroy.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/lib/internal/streams/stream.js": +/*!*********************************************************************!*\ + !*** ./node_modules/readable-stream/lib/internal/streams/stream.js ***! + \*********************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("module.exports = __webpack_require__(/*! stream */ \"stream\");\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/readable-stream/lib/internal/streams/stream.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/readable.js": +/*!**************************************************!*\ + !*** ./node_modules/readable-stream/readable.js ***! + \**************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +eval("var Stream = __webpack_require__(/*! stream */ \"stream\");\nif (process.env.READABLE_STREAM === 'disable' && Stream) {\n module.exports = Stream;\n exports = module.exports = Stream.Readable;\n exports.Readable = Stream.Readable;\n exports.Writable = Stream.Writable;\n exports.Duplex = Stream.Duplex;\n exports.Transform = Stream.Transform;\n exports.PassThrough = Stream.PassThrough;\n exports.Stream = Stream;\n} else {\n exports = module.exports = __webpack_require__(/*! ./lib/_stream_readable.js */ \"./node_modules/readable-stream/lib/_stream_readable.js\");\n exports.Stream = Stream || exports;\n exports.Readable = exports;\n exports.Writable = __webpack_require__(/*! ./lib/_stream_writable.js */ \"./node_modules/readable-stream/lib/_stream_writable.js\");\n exports.Duplex = __webpack_require__(/*! ./lib/_stream_duplex.js */ \"./node_modules/readable-stream/lib/_stream_duplex.js\");\n exports.Transform = __webpack_require__(/*! ./lib/_stream_transform.js */ \"./node_modules/readable-stream/lib/_stream_transform.js\");\n exports.PassThrough = __webpack_require__(/*! ./lib/_stream_passthrough.js */ \"./node_modules/readable-stream/lib/_stream_passthrough.js\");\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/readable-stream/readable.js?"); + +/***/ }), + +/***/ "./node_modules/readdirp/readdirp.js": +/*!*******************************************!*\ + !*** ./node_modules/readdirp/readdirp.js ***! + \*******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar fs = __webpack_require__(/*! graceful-fs */ \"./node_modules/graceful-fs/graceful-fs.js\")\n , path = __webpack_require__(/*! path */ \"path\")\n , micromatch = __webpack_require__(/*! micromatch */ \"./node_modules/micromatch/index.js\").isMatch\n , toString = Object.prototype.toString\n ;\n\n\n// Standard helpers\nfunction isFunction (obj) {\n return toString.call(obj) === '[object Function]';\n}\n\nfunction isString (obj) {\n return toString.call(obj) === '[object String]';\n}\n\nfunction isUndefined (obj) {\n return obj === void 0;\n}\n\n/**\n * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.\n * @param { Object } opts Options to specify root (start directory), filters and recursion depth\n * @param { function } callback1 When callback2 is given calls back for each processed file - function (fileInfo) { ... },\n * when callback2 is not given, it behaves like explained in callback2\n * @param { function } callback2 Calls back once all files have been processed with an array of errors and file infos\n * function (err, fileInfos) { ... }\n */\nfunction readdir(opts, callback1, callback2) {\n var stream\n , handleError\n , handleFatalError\n , errors = []\n , readdirResult = {\n directories: []\n , files: []\n }\n , fileProcessed\n , allProcessed\n , realRoot\n , aborted = false\n , paused = false\n ;\n\n // If no callbacks were given we will use a streaming interface\n if (isUndefined(callback1)) {\n var api = __webpack_require__(/*! ./stream-api */ \"./node_modules/readdirp/stream-api.js\")();\n stream = api.stream;\n callback1 = api.processEntry;\n callback2 = api.done;\n handleError = api.handleError;\n handleFatalError = api.handleFatalError;\n\n stream.on('close', function () { aborted = true; });\n stream.on('pause', function () { paused = true; });\n stream.on('resume', function () { paused = false; });\n } else {\n handleError = function (err) { errors.push(err); };\n handleFatalError = function (err) {\n handleError(err);\n allProcessed(errors, null);\n };\n }\n\n if (isUndefined(opts)){\n handleFatalError(new Error (\n 'Need to pass at least one argument: opts! \\n' +\n 'https://github.com/paulmillr/readdirp#options'\n )\n );\n return stream;\n }\n\n opts.root = opts.root || '.';\n opts.fileFilter = opts.fileFilter || function() { return true; };\n opts.directoryFilter = opts.directoryFilter || function() { return true; };\n opts.depth = typeof opts.depth === 'undefined' ? 999999999 : opts.depth;\n opts.entryType = opts.entryType || 'files';\n\n var statfn = opts.lstat === true ? fs.lstat.bind(fs) : fs.stat.bind(fs);\n\n if (isUndefined(callback2)) {\n fileProcessed = function() { };\n allProcessed = callback1;\n } else {\n fileProcessed = callback1;\n allProcessed = callback2;\n }\n\n function normalizeFilter (filter) {\n\n if (isUndefined(filter)) return undefined;\n\n function isNegated (filters) {\n\n function negated(f) {\n return f.indexOf('!') === 0;\n }\n\n var some = filters.some(negated);\n if (!some) {\n return false;\n } else {\n if (filters.every(negated)) {\n return true;\n } else {\n // if we detect illegal filters, bail out immediately\n throw new Error(\n 'Cannot mix negated with non negated glob filters: ' + filters + '\\n' +\n 'https://github.com/paulmillr/readdirp#filters'\n );\n }\n }\n }\n\n // Turn all filters into a function\n if (isFunction(filter)) {\n\n return filter;\n\n } else if (isString(filter)) {\n\n return function (entryInfo) {\n return micromatch(entryInfo.name, filter.trim());\n };\n\n } else if (filter && Array.isArray(filter)) {\n\n if (filter) filter = filter.map(function (f) {\n return f.trim();\n });\n\n return isNegated(filter) ?\n // use AND to concat multiple negated filters\n function (entryInfo) {\n return filter.every(function (f) {\n return micromatch(entryInfo.name, f);\n });\n }\n :\n // use OR to concat multiple inclusive filters\n function (entryInfo) {\n return filter.some(function (f) {\n return micromatch(entryInfo.name, f);\n });\n };\n }\n }\n\n function processDir(currentDir, entries, callProcessed) {\n if (aborted) return;\n var total = entries.length\n , processed = 0\n , entryInfos = []\n ;\n\n fs.realpath(currentDir, function(err, realCurrentDir) {\n if (aborted) return;\n if (err) {\n handleError(err);\n callProcessed(entryInfos);\n return;\n }\n\n var relDir = path.relative(realRoot, realCurrentDir);\n\n if (entries.length === 0) {\n callProcessed([]);\n } else {\n entries.forEach(function (entry) {\n\n var fullPath = path.join(realCurrentDir, entry)\n , relPath = path.join(relDir, entry);\n\n statfn(fullPath, function (err, stat) {\n if (err) {\n handleError(err);\n } else {\n entryInfos.push({\n name : entry\n , path : relPath // relative to root\n , fullPath : fullPath\n\n , parentDir : relDir // relative to root\n , fullParentDir : realCurrentDir\n\n , stat : stat\n });\n }\n processed++;\n if (processed === total) callProcessed(entryInfos);\n });\n });\n }\n });\n }\n\n function readdirRec(currentDir, depth, callCurrentDirProcessed) {\n var args = arguments;\n if (aborted) return;\n if (paused) {\n setImmediate(function () {\n readdirRec.apply(null, args);\n })\n return;\n }\n\n fs.readdir(currentDir, function (err, entries) {\n if (err) {\n handleError(err);\n callCurrentDirProcessed();\n return;\n }\n\n processDir(currentDir, entries, function(entryInfos) {\n\n var subdirs = entryInfos\n .filter(function (ei) { return ei.stat.isDirectory() && opts.directoryFilter(ei); });\n\n subdirs.forEach(function (di) {\n if(opts.entryType === 'directories' || opts.entryType === 'both' || opts.entryType === 'all') {\n fileProcessed(di);\n }\n readdirResult.directories.push(di);\n });\n\n entryInfos\n .filter(function(ei) {\n var isCorrectType = opts.entryType === 'all' ?\n !ei.stat.isDirectory() : ei.stat.isFile() || ei.stat.isSymbolicLink();\n return isCorrectType && opts.fileFilter(ei);\n })\n .forEach(function (fi) {\n if(opts.entryType === 'files' || opts.entryType === 'both' || opts.entryType === 'all') {\n fileProcessed(fi);\n }\n readdirResult.files.push(fi);\n });\n\n var pendingSubdirs = subdirs.length;\n\n // Be done if no more subfolders exist or we reached the maximum desired depth\n if(pendingSubdirs === 0 || depth === opts.depth) {\n callCurrentDirProcessed();\n } else {\n // recurse into subdirs, keeping track of which ones are done\n // and call back once all are processed\n subdirs.forEach(function (subdir) {\n readdirRec(subdir.fullPath, depth + 1, function () {\n pendingSubdirs = pendingSubdirs - 1;\n if(pendingSubdirs === 0) {\n callCurrentDirProcessed();\n }\n });\n });\n }\n });\n });\n }\n\n // Validate and normalize filters\n try {\n opts.fileFilter = normalizeFilter(opts.fileFilter);\n opts.directoryFilter = normalizeFilter(opts.directoryFilter);\n } catch (err) {\n // if we detect illegal filters, bail out immediately\n handleFatalError(err);\n return stream;\n }\n\n // If filters were valid get on with the show\n fs.realpath(opts.root, function(err, res) {\n if (err) {\n handleFatalError(err);\n return stream;\n }\n\n realRoot = res;\n readdirRec(opts.root, 0, function () {\n // All errors are collected into the errors array\n if (errors.length > 0) {\n allProcessed(errors, readdirResult);\n } else {\n allProcessed(null, readdirResult);\n }\n });\n });\n\n return stream;\n}\n\nmodule.exports = readdir;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/readdirp/readdirp.js?"); + +/***/ }), + +/***/ "./node_modules/readdirp/stream-api.js": +/*!*********************************************!*\ + !*** ./node_modules/readdirp/stream-api.js ***! + \*********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar stream = __webpack_require__(/*! readable-stream */ \"./node_modules/readable-stream/readable.js\");\nvar util = __webpack_require__(/*! util */ \"util\");\n\nvar Readable = stream.Readable;\n\nmodule.exports = ReaddirpReadable;\n\nutil.inherits(ReaddirpReadable, Readable);\n\nfunction ReaddirpReadable (opts) {\n if (!(this instanceof ReaddirpReadable)) return new ReaddirpReadable(opts);\n\n opts = opts || {};\n\n opts.objectMode = true;\n Readable.call(this, opts);\n\n // backpressure not implemented at this point\n this.highWaterMark = Infinity;\n\n this._destroyed = false;\n this._paused = false;\n this._warnings = [];\n this._errors = [];\n\n this._pauseResumeErrors();\n}\n\nvar proto = ReaddirpReadable.prototype;\n\nproto._pauseResumeErrors = function () {\n var self = this;\n self.on('pause', function () { self._paused = true });\n self.on('resume', function () {\n if (self._destroyed) return;\n self._paused = false;\n\n self._warnings.forEach(function (err) { self.emit('warn', err) });\n self._warnings.length = 0;\n\n self._errors.forEach(function (err) { self.emit('error', err) });\n self._errors.length = 0;\n })\n}\n\n// called for each entry\nproto._processEntry = function (entry) {\n if (this._destroyed) return;\n this.push(entry);\n}\n\nproto._read = function () { }\n\nproto.destroy = function () {\n // when stream is destroyed it will emit nothing further, not even errors or warnings\n this.push(null);\n this.readable = false;\n this._destroyed = true;\n this.emit('close');\n}\n\nproto._done = function () {\n this.push(null);\n}\n\n// we emit errors and warnings async since we may handle errors like invalid args\n// within the initial event loop before any event listeners subscribed\nproto._handleError = function (err) {\n var self = this;\n setImmediate(function () {\n if (self._paused) return self._warnings.push(err);\n if (!self._destroyed) self.emit('warn', err);\n });\n}\n\nproto._handleFatalError = function (err) {\n var self = this;\n setImmediate(function () {\n if (self._paused) return self._errors.push(err);\n if (!self._destroyed) self.emit('error', err);\n });\n}\n\nfunction createStreamAPI () {\n var stream = new ReaddirpReadable();\n\n return {\n stream : stream\n , processEntry : stream._processEntry.bind(stream)\n , done : stream._done.bind(stream)\n , handleError : stream._handleError.bind(stream)\n , handleFatalError : stream._handleFatalError.bind(stream)\n };\n}\n\nmodule.exports = createStreamAPI;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/readdirp/stream-api.js?"); + +/***/ }), + +/***/ "./node_modules/regex-not/index.js": +/*!*****************************************!*\ + !*** ./node_modules/regex-not/index.js ***! + \*****************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar extend = __webpack_require__(/*! extend-shallow */ \"./node_modules/regex-not/node_modules/extend-shallow/index.js\");\nvar safe = __webpack_require__(/*! safe-regex */ \"./node_modules/safe-regex/index.js\");\n\n/**\n * The main export is a function that takes a `pattern` string and an `options` object.\n *\n * ```js\n & var not = require('regex-not');\n & console.log(not('foo'));\n & //=> /^(?:(?!^(?:foo)$).)*$/\n * ```\n *\n * @param {String} `pattern`\n * @param {Object} `options`\n * @return {RegExp} Converts the given `pattern` to a regex using the specified `options`.\n * @api public\n */\n\nfunction toRegex(pattern, options) {\n return new RegExp(toRegex.create(pattern, options));\n}\n\n/**\n * Create a regex-compatible string from the given `pattern` and `options`.\n *\n * ```js\n & var not = require('regex-not');\n & console.log(not.create('foo'));\n & //=> '^(?:(?!^(?:foo)$).)*$'\n * ```\n * @param {String} `pattern`\n * @param {Object} `options`\n * @return {String}\n * @api public\n */\n\ntoRegex.create = function(pattern, options) {\n if (typeof pattern !== 'string') {\n throw new TypeError('expected a string');\n }\n\n var opts = extend({}, options);\n if (opts.contains === true) {\n opts.strictNegate = false;\n }\n\n var open = opts.strictOpen !== false ? '^' : '';\n var close = opts.strictClose !== false ? '$' : '';\n var endChar = opts.endChar ? opts.endChar : '+';\n var str = pattern;\n\n if (opts.strictNegate === false) {\n str = '(?:(?!(?:' + pattern + ')).)' + endChar;\n } else {\n str = '(?:(?!^(?:' + pattern + ')$).)' + endChar;\n }\n\n var res = open + str + close;\n if (opts.safe === true && safe(res) === false) {\n throw new Error('potentially unsafe regular expression: ' + res);\n }\n\n return res;\n};\n\n/**\n * Expose `toRegex`\n */\n\nmodule.exports = toRegex;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/regex-not/index.js?"); + +/***/ }), + +/***/ "./node_modules/regex-not/node_modules/extend-shallow/index.js": +/*!*********************************************************************!*\ + !*** ./node_modules/regex-not/node_modules/extend-shallow/index.js ***! + \*********************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar isExtendable = __webpack_require__(/*! is-extendable */ \"./node_modules/regex-not/node_modules/is-extendable/index.js\");\nvar assignSymbols = __webpack_require__(/*! assign-symbols */ \"./node_modules/assign-symbols/index.js\");\n\nmodule.exports = Object.assign || function(obj/*, objects*/) {\n if (obj === null || typeof obj === 'undefined') {\n throw new TypeError('Cannot convert undefined or null to object');\n }\n if (!isObject(obj)) {\n obj = {};\n }\n for (var i = 1; i < arguments.length; i++) {\n var val = arguments[i];\n if (isString(val)) {\n val = toObject(val);\n }\n if (isObject(val)) {\n assign(obj, val);\n assignSymbols(obj, val);\n }\n }\n return obj;\n};\n\nfunction assign(a, b) {\n for (var key in b) {\n if (hasOwn(b, key)) {\n a[key] = b[key];\n }\n }\n}\n\nfunction isString(val) {\n return (val && typeof val === 'string');\n}\n\nfunction toObject(str) {\n var obj = {};\n for (var i in str) {\n obj[i] = str[i];\n }\n return obj;\n}\n\nfunction isObject(val) {\n return (val && typeof val === 'object') || isExtendable(val);\n}\n\n/**\n * Returns true if the given `key` is an own property of `obj`.\n */\n\nfunction hasOwn(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nfunction isEnum(obj, key) {\n return Object.prototype.propertyIsEnumerable.call(obj, key);\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/regex-not/node_modules/extend-shallow/index.js?"); + +/***/ }), + +/***/ "./node_modules/regex-not/node_modules/is-extendable/index.js": +/*!********************************************************************!*\ + !*** ./node_modules/regex-not/node_modules/is-extendable/index.js ***! + \********************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * is-extendable \n *\n * Copyright (c) 2015-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar isPlainObject = __webpack_require__(/*! is-plain-object */ \"./node_modules/is-plain-object/index.js\");\n\nmodule.exports = function isExtendable(val) {\n return isPlainObject(val) || typeof val === 'function' || Array.isArray(val);\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/regex-not/node_modules/is-extendable/index.js?"); + +/***/ }), + +/***/ "./node_modules/remove-trailing-separator/index.js": +/*!*********************************************************!*\ + !*** ./node_modules/remove-trailing-separator/index.js ***! + \*********************************************************/ +/***/ ((module) => { + +eval("var isWin = process.platform === 'win32';\n\nmodule.exports = function (str) {\n\tvar i = str.length - 1;\n\tif (i < 2) {\n\t\treturn str;\n\t}\n\twhile (isSeparator(str, i)) {\n\t\ti--;\n\t}\n\treturn str.substr(0, i + 1);\n};\n\nfunction isSeparator(str, i) {\n\tvar char = str[i];\n\treturn i > 0 && (char === '/' || (isWin && char === '\\\\'));\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/remove-trailing-separator/index.js?"); + +/***/ }), + +/***/ "./node_modules/repeat-element/index.js": +/*!**********************************************!*\ + !*** ./node_modules/repeat-element/index.js ***! + \**********************************************/ +/***/ ((module) => { + +"use strict"; +eval("/*!\n * repeat-element \n *\n * Copyright (c) 2015-present, Jon Schlinkert.\n * Licensed under the MIT license.\n */\n\n\n\nmodule.exports = function repeat(ele, num) {\n if (Array.prototype.fill) {\n return new Array(num).fill(ele);\n }\n\n var arr = new Array(num);\n\n for (var i = 0; i < num; i++) {\n arr[i] = ele;\n }\n\n return arr;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/repeat-element/index.js?"); + +/***/ }), + +/***/ "./node_modules/repeat-string/index.js": +/*!*********************************************!*\ + !*** ./node_modules/repeat-string/index.js ***! + \*********************************************/ +/***/ ((module) => { + +"use strict"; +eval("/*!\n * repeat-string \n *\n * Copyright (c) 2014-2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n\n\n/**\n * Results cache\n */\n\nvar res = '';\nvar cache;\n\n/**\n * Expose `repeat`\n */\n\nmodule.exports = repeat;\n\n/**\n * Repeat the given `string` the specified `number`\n * of times.\n *\n * **Example:**\n *\n * ```js\n * var repeat = require('repeat-string');\n * repeat('A', 5);\n * //=> AAAAA\n * ```\n *\n * @param {String} `string` The string to repeat\n * @param {Number} `number` The number of times to repeat the string\n * @return {String} Repeated string\n * @api public\n */\n\nfunction repeat(str, num) {\n if (typeof str !== 'string') {\n throw new TypeError('expected a string');\n }\n\n // cover common, quick use cases\n if (num === 1) return str;\n if (num === 2) return str + str;\n\n var max = str.length * num;\n if (cache !== str || typeof cache === 'undefined') {\n cache = str;\n res = '';\n } else if (res.length >= max) {\n return res.substr(0, max);\n }\n\n while (max > res.length && num > 1) {\n if (num & 1) {\n res += str;\n }\n\n num >>= 1;\n str += str;\n }\n\n res += str;\n res = res.substr(0, max);\n return res;\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/repeat-string/index.js?"); + +/***/ }), + +/***/ "./node_modules/ret/lib/index.js": +/*!***************************************!*\ + !*** ./node_modules/ret/lib/index.js ***! + \***************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var util = __webpack_require__(/*! ./util */ \"./node_modules/ret/lib/util.js\");\nvar types = __webpack_require__(/*! ./types */ \"./node_modules/ret/lib/types.js\");\nvar sets = __webpack_require__(/*! ./sets */ \"./node_modules/ret/lib/sets.js\");\nvar positions = __webpack_require__(/*! ./positions */ \"./node_modules/ret/lib/positions.js\");\n\n\nmodule.exports = function(regexpStr) {\n var i = 0, l, c,\n start = { type: types.ROOT, stack: []},\n\n // Keep track of last clause/group and stack.\n lastGroup = start,\n last = start.stack,\n groupStack = [];\n\n\n var repeatErr = function(i) {\n util.error(regexpStr, 'Nothing to repeat at column ' + (i - 1));\n };\n\n // Decode a few escaped characters.\n var str = util.strToChars(regexpStr);\n l = str.length;\n\n // Iterate through each character in string.\n while (i < l) {\n c = str[i++];\n\n switch (c) {\n // Handle escaped characters, inclues a few sets.\n case '\\\\':\n c = str[i++];\n\n switch (c) {\n case 'b':\n last.push(positions.wordBoundary());\n break;\n\n case 'B':\n last.push(positions.nonWordBoundary());\n break;\n\n case 'w':\n last.push(sets.words());\n break;\n\n case 'W':\n last.push(sets.notWords());\n break;\n\n case 'd':\n last.push(sets.ints());\n break;\n\n case 'D':\n last.push(sets.notInts());\n break;\n\n case 's':\n last.push(sets.whitespace());\n break;\n\n case 'S':\n last.push(sets.notWhitespace());\n break;\n\n default:\n // Check if c is integer.\n // In which case it's a reference.\n if (/\\d/.test(c)) {\n last.push({ type: types.REFERENCE, value: parseInt(c, 10) });\n\n // Escaped character.\n } else {\n last.push({ type: types.CHAR, value: c.charCodeAt(0) });\n }\n }\n\n break;\n\n\n // Positionals.\n case '^':\n last.push(positions.begin());\n break;\n\n case '$':\n last.push(positions.end());\n break;\n\n\n // Handle custom sets.\n case '[':\n // Check if this class is 'anti' i.e. [^abc].\n var not;\n if (str[i] === '^') {\n not = true;\n i++;\n } else {\n not = false;\n }\n\n // Get all the characters in class.\n var classTokens = util.tokenizeClass(str.slice(i), regexpStr);\n\n // Increase index by length of class.\n i += classTokens[1];\n last.push({\n type: types.SET,\n set: classTokens[0],\n not: not,\n });\n\n break;\n\n\n // Class of any character except \\n.\n case '.':\n last.push(sets.anyChar());\n break;\n\n\n // Push group onto stack.\n case '(':\n // Create group.\n var group = {\n type: types.GROUP,\n stack: [],\n remember: true,\n };\n\n c = str[i];\n\n // If if this is a special kind of group.\n if (c === '?') {\n c = str[i + 1];\n i += 2;\n\n // Match if followed by.\n if (c === '=') {\n group.followedBy = true;\n\n // Match if not followed by.\n } else if (c === '!') {\n group.notFollowedBy = true;\n\n } else if (c !== ':') {\n util.error(regexpStr,\n 'Invalid group, character \\'' + c +\n '\\' after \\'?\\' at column ' + (i - 1));\n }\n\n group.remember = false;\n }\n\n // Insert subgroup into current group stack.\n last.push(group);\n\n // Remember the current group for when the group closes.\n groupStack.push(lastGroup);\n\n // Make this new group the current group.\n lastGroup = group;\n last = group.stack;\n break;\n\n\n // Pop group out of stack.\n case ')':\n if (groupStack.length === 0) {\n util.error(regexpStr, 'Unmatched ) at column ' + (i - 1));\n }\n lastGroup = groupStack.pop();\n\n // Check if this group has a PIPE.\n // To get back the correct last stack.\n last = lastGroup.options ?\n lastGroup.options[lastGroup.options.length - 1] : lastGroup.stack;\n break;\n\n\n // Use pipe character to give more choices.\n case '|':\n // Create array where options are if this is the first PIPE\n // in this clause.\n if (!lastGroup.options) {\n lastGroup.options = [lastGroup.stack];\n delete lastGroup.stack;\n }\n\n // Create a new stack and add to options for rest of clause.\n var stack = [];\n lastGroup.options.push(stack);\n last = stack;\n break;\n\n\n // Repetition.\n // For every repetition, remove last element from last stack\n // then insert back a RANGE object.\n // This design is chosen because there could be more than\n // one repetition symbols in a regex i.e. `a?+{2,3}`.\n case '{':\n var rs = /^(\\d+)(,(\\d+)?)?\\}/.exec(str.slice(i)), min, max;\n if (rs !== null) {\n if (last.length === 0) {\n repeatErr(i);\n }\n min = parseInt(rs[1], 10);\n max = rs[2] ? rs[3] ? parseInt(rs[3], 10) : Infinity : min;\n i += rs[0].length;\n\n last.push({\n type: types.REPETITION,\n min: min,\n max: max,\n value: last.pop(),\n });\n } else {\n last.push({\n type: types.CHAR,\n value: 123,\n });\n }\n break;\n\n case '?':\n if (last.length === 0) {\n repeatErr(i);\n }\n last.push({\n type: types.REPETITION,\n min: 0,\n max: 1,\n value: last.pop(),\n });\n break;\n\n case '+':\n if (last.length === 0) {\n repeatErr(i);\n }\n last.push({\n type: types.REPETITION,\n min: 1,\n max: Infinity,\n value: last.pop(),\n });\n break;\n\n case '*':\n if (last.length === 0) {\n repeatErr(i);\n }\n last.push({\n type: types.REPETITION,\n min: 0,\n max: Infinity,\n value: last.pop(),\n });\n break;\n\n\n // Default is a character that is not `\\[](){}?+*^$`.\n default:\n last.push({\n type: types.CHAR,\n value: c.charCodeAt(0),\n });\n }\n\n }\n\n // Check if any groups have not been closed.\n if (groupStack.length !== 0) {\n util.error(regexpStr, 'Unterminated group');\n }\n\n return start;\n};\n\nmodule.exports.types = types;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/ret/lib/index.js?"); + +/***/ }), + +/***/ "./node_modules/ret/lib/positions.js": +/*!*******************************************!*\ + !*** ./node_modules/ret/lib/positions.js ***! + \*******************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("var types = __webpack_require__(/*! ./types */ \"./node_modules/ret/lib/types.js\");\n\nexports.wordBoundary = function() {\n return { type: types.POSITION, value: 'b' };\n};\n\nexports.nonWordBoundary = function() {\n return { type: types.POSITION, value: 'B' };\n};\n\nexports.begin = function() {\n return { type: types.POSITION, value: '^' };\n};\n\nexports.end = function() {\n return { type: types.POSITION, value: '$' };\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/ret/lib/positions.js?"); + +/***/ }), + +/***/ "./node_modules/ret/lib/sets.js": +/*!**************************************!*\ + !*** ./node_modules/ret/lib/sets.js ***! + \**************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("var types = __webpack_require__(/*! ./types */ \"./node_modules/ret/lib/types.js\");\n\nvar INTS = function() {\n return [{ type: types.RANGE , from: 48, to: 57 }];\n};\n\nvar WORDS = function() {\n return [\n { type: types.CHAR, value: 95 },\n { type: types.RANGE, from: 97, to: 122 },\n { type: types.RANGE, from: 65, to: 90 }\n ].concat(INTS());\n};\n\nvar WHITESPACE = function() {\n return [\n { type: types.CHAR, value: 9 },\n { type: types.CHAR, value: 10 },\n { type: types.CHAR, value: 11 },\n { type: types.CHAR, value: 12 },\n { type: types.CHAR, value: 13 },\n { type: types.CHAR, value: 32 },\n { type: types.CHAR, value: 160 },\n { type: types.CHAR, value: 5760 },\n { type: types.CHAR, value: 6158 },\n { type: types.CHAR, value: 8192 },\n { type: types.CHAR, value: 8193 },\n { type: types.CHAR, value: 8194 },\n { type: types.CHAR, value: 8195 },\n { type: types.CHAR, value: 8196 },\n { type: types.CHAR, value: 8197 },\n { type: types.CHAR, value: 8198 },\n { type: types.CHAR, value: 8199 },\n { type: types.CHAR, value: 8200 },\n { type: types.CHAR, value: 8201 },\n { type: types.CHAR, value: 8202 },\n { type: types.CHAR, value: 8232 },\n { type: types.CHAR, value: 8233 },\n { type: types.CHAR, value: 8239 },\n { type: types.CHAR, value: 8287 },\n { type: types.CHAR, value: 12288 },\n { type: types.CHAR, value: 65279 }\n ];\n};\n\nvar NOTANYCHAR = function() {\n return [\n { type: types.CHAR, value: 10 },\n { type: types.CHAR, value: 13 },\n { type: types.CHAR, value: 8232 },\n { type: types.CHAR, value: 8233 },\n ];\n};\n\n// Predefined class objects.\nexports.words = function() {\n return { type: types.SET, set: WORDS(), not: false };\n};\n\nexports.notWords = function() {\n return { type: types.SET, set: WORDS(), not: true };\n};\n\nexports.ints = function() {\n return { type: types.SET, set: INTS(), not: false };\n};\n\nexports.notInts = function() {\n return { type: types.SET, set: INTS(), not: true };\n};\n\nexports.whitespace = function() {\n return { type: types.SET, set: WHITESPACE(), not: false };\n};\n\nexports.notWhitespace = function() {\n return { type: types.SET, set: WHITESPACE(), not: true };\n};\n\nexports.anyChar = function() {\n return { type: types.SET, set: NOTANYCHAR(), not: true };\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/ret/lib/sets.js?"); + +/***/ }), + +/***/ "./node_modules/ret/lib/types.js": +/*!***************************************!*\ + !*** ./node_modules/ret/lib/types.js ***! + \***************************************/ +/***/ ((module) => { + +eval("module.exports = {\n ROOT : 0,\n GROUP : 1,\n POSITION : 2,\n SET : 3,\n RANGE : 4,\n REPETITION : 5,\n REFERENCE : 6,\n CHAR : 7,\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/ret/lib/types.js?"); + +/***/ }), + +/***/ "./node_modules/ret/lib/util.js": +/*!**************************************!*\ + !*** ./node_modules/ret/lib/util.js ***! + \**************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("var types = __webpack_require__(/*! ./types */ \"./node_modules/ret/lib/types.js\");\nvar sets = __webpack_require__(/*! ./sets */ \"./node_modules/ret/lib/sets.js\");\n\n\n// All of these are private and only used by randexp.\n// It's assumed that they will always be called with the correct input.\n\nvar CTRL = '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^ ?';\nvar SLSH = { '0': 0, 't': 9, 'n': 10, 'v': 11, 'f': 12, 'r': 13 };\n\n/**\n * Finds character representations in str and convert all to\n * their respective characters\n *\n * @param {String} str\n * @return {String}\n */\nexports.strToChars = function(str) {\n /* jshint maxlen: false */\n var chars_regex = /(\\[\\\\b\\])|(\\\\)?\\\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|(0?[0-7]{2})|c([@A-Z\\[\\\\\\]\\^?])|([0tnvfr]))/g;\n str = str.replace(chars_regex, function(s, b, lbs, a16, b16, c8, dctrl, eslsh) {\n if (lbs) {\n return s;\n }\n\n var code = b ? 8 :\n a16 ? parseInt(a16, 16) :\n b16 ? parseInt(b16, 16) :\n c8 ? parseInt(c8, 8) :\n dctrl ? CTRL.indexOf(dctrl) :\n SLSH[eslsh];\n\n var c = String.fromCharCode(code);\n\n // Escape special regex characters.\n if (/[\\[\\]{}\\^$.|?*+()]/.test(c)) {\n c = '\\\\' + c;\n }\n\n return c;\n });\n\n return str;\n};\n\n\n/**\n * turns class into tokens\n * reads str until it encounters a ] not preceeded by a \\\n *\n * @param {String} str\n * @param {String} regexpStr\n * @return {Array., Number>}\n */\nexports.tokenizeClass = function(str, regexpStr) {\n /* jshint maxlen: false */\n var tokens = [];\n var regexp = /\\\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\\\)(.)|([^\\]\\\\]))-(?:\\\\)?([^\\]]))|(\\])|(?:\\\\)?(.)/g;\n var rs, c;\n\n\n while ((rs = regexp.exec(str)) != null) {\n if (rs[1]) {\n tokens.push(sets.words());\n\n } else if (rs[2]) {\n tokens.push(sets.ints());\n\n } else if (rs[3]) {\n tokens.push(sets.whitespace());\n\n } else if (rs[4]) {\n tokens.push(sets.notWords());\n\n } else if (rs[5]) {\n tokens.push(sets.notInts());\n\n } else if (rs[6]) {\n tokens.push(sets.notWhitespace());\n\n } else if (rs[7]) {\n tokens.push({\n type: types.RANGE,\n from: (rs[8] || rs[9]).charCodeAt(0),\n to: rs[10].charCodeAt(0),\n });\n\n } else if (c = rs[12]) {\n tokens.push({\n type: types.CHAR,\n value: c.charCodeAt(0),\n });\n\n } else {\n return [tokens, regexp.lastIndex];\n }\n }\n\n exports.error(regexpStr, 'Unterminated character class');\n};\n\n\n/**\n * Shortcut to throw errors.\n *\n * @param {String} regexp\n * @param {String} msg\n */\nexports.error = function(regexp, msg) {\n throw new SyntaxError('Invalid regular expression: /' + regexp + '/: ' + msg);\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/ret/lib/util.js?"); + +/***/ }), + +/***/ "./node_modules/safe-buffer/index.js": +/*!*******************************************!*\ + !*** ./node_modules/safe-buffer/index.js ***! + \*******************************************/ +/***/ ((module, exports, __webpack_require__) => { + +eval("/* eslint-disable node/no-deprecated-api */\nvar buffer = __webpack_require__(/*! buffer */ \"buffer\")\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/safe-buffer/index.js?"); + +/***/ }), + +/***/ "./node_modules/safe-regex/index.js": +/*!******************************************!*\ + !*** ./node_modules/safe-regex/index.js ***! + \******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var parse = __webpack_require__(/*! ret */ \"./node_modules/ret/lib/index.js\");\nvar types = parse.types;\n\nmodule.exports = function (re, opts) {\n if (!opts) opts = {};\n var replimit = opts.limit === undefined ? 25 : opts.limit;\n \n if (isRegExp(re)) re = re.source;\n else if (typeof re !== 'string') re = String(re);\n \n try { re = parse(re) }\n catch (err) { return false }\n \n var reps = 0;\n return (function walk (node, starHeight) {\n if (node.type === types.REPETITION) {\n starHeight ++;\n reps ++;\n if (starHeight > 1) return false;\n if (reps > replimit) return false;\n }\n \n if (node.options) {\n for (var i = 0, len = node.options.length; i < len; i++) {\n var ok = walk({ stack: node.options[i] }, starHeight);\n if (!ok) return false;\n }\n }\n var stack = node.stack || (node.value && node.value.stack);\n if (!stack) return true;\n \n for (var i = 0; i < stack.length; i++) {\n var ok = walk(stack[i], starHeight);\n if (!ok) return false;\n }\n \n return true;\n })(re, 0);\n};\n\nfunction isRegExp (x) {\n return {}.toString.call(x) === '[object RegExp]';\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/safe-regex/index.js?"); + +/***/ }), + +/***/ "./node_modules/set-value/index.js": +/*!*****************************************!*\ + !*** ./node_modules/set-value/index.js ***! + \*****************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * set-value \n *\n * Copyright (c) 2014-2015, 2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar split = __webpack_require__(/*! split-string */ \"./node_modules/split-string/index.js\");\nvar extend = __webpack_require__(/*! extend-shallow */ \"./node_modules/extend-shallow/index.js\");\nvar isPlainObject = __webpack_require__(/*! is-plain-object */ \"./node_modules/is-plain-object/index.js\");\nvar isObject = __webpack_require__(/*! is-extendable */ \"./node_modules/is-extendable/index.js\");\n\nmodule.exports = function(obj, prop, val) {\n if (!isObject(obj)) {\n return obj;\n }\n\n if (Array.isArray(prop)) {\n prop = [].concat.apply([], prop).join('.');\n }\n\n if (typeof prop !== 'string') {\n return obj;\n }\n\n var keys = split(prop, {sep: '.', brackets: true}).filter(isValidKey);\n var len = keys.length;\n var idx = -1;\n var current = obj;\n\n while (++idx < len) {\n var key = keys[idx];\n if (idx !== len - 1) {\n if (!isObject(current[key])) {\n current[key] = {};\n }\n current = current[key];\n continue;\n }\n\n if (isPlainObject(current[key]) && isPlainObject(val)) {\n current[key] = extend({}, current[key], val);\n } else {\n current[key] = val;\n }\n }\n\n return obj;\n};\n\nfunction isValidKey(key) {\n return key !== '__proto__' && key !== 'constructor' && key !== 'prototype';\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/set-value/index.js?"); + +/***/ }), + +/***/ "./node_modules/snapdragon-node/index.js": +/*!***********************************************!*\ + !*** ./node_modules/snapdragon-node/index.js ***! + \***********************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar isObject = __webpack_require__(/*! isobject */ \"./node_modules/isobject/index.js\");\nvar define = __webpack_require__(/*! define-property */ \"./node_modules/snapdragon-node/node_modules/define-property/index.js\");\nvar utils = __webpack_require__(/*! snapdragon-util */ \"./node_modules/snapdragon-util/index.js\");\nvar ownNames;\n\n/**\n * Create a new AST `Node` with the given `val` and `type`.\n *\n * ```js\n * var node = new Node('*', 'Star');\n * var node = new Node({type: 'star', val: '*'});\n * ```\n * @name Node\n * @param {String|Object} `val` Pass a matched substring, or an object to merge onto the node.\n * @param {String} `type` The node type to use when `val` is a string.\n * @return {Object} node instance\n * @api public\n */\n\nfunction Node(val, type, parent) {\n if (typeof type !== 'string') {\n parent = type;\n type = null;\n }\n\n define(this, 'parent', parent);\n define(this, 'isNode', true);\n define(this, 'expect', null);\n\n if (typeof type !== 'string' && isObject(val)) {\n lazyKeys();\n var keys = Object.keys(val);\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n if (ownNames.indexOf(key) === -1) {\n this[key] = val[key];\n }\n }\n } else {\n this.type = type;\n this.val = val;\n }\n}\n\n/**\n * Returns true if the given value is a node.\n *\n * ```js\n * var Node = require('snapdragon-node');\n * var node = new Node({type: 'foo'});\n * console.log(Node.isNode(node)); //=> true\n * console.log(Node.isNode({})); //=> false\n * ```\n * @param {Object} `node`\n * @returns {Boolean}\n * @api public\n */\n\nNode.isNode = function(node) {\n return utils.isNode(node);\n};\n\n/**\n * Define a non-enumberable property on the node instance.\n * Useful for adding properties that shouldn't be extended\n * or visible during debugging.\n *\n * ```js\n * var node = new Node();\n * node.define('foo', 'something non-enumerable');\n * ```\n * @param {String} `name`\n * @param {any} `val`\n * @return {Object} returns the node instance\n * @api public\n */\n\nNode.prototype.define = function(name, val) {\n define(this, name, val);\n return this;\n};\n\n/**\n * Returns true if `node.val` is an empty string, or `node.nodes` does\n * not contain any non-empty text nodes.\n *\n * ```js\n * var node = new Node({type: 'text'});\n * node.isEmpty(); //=> true\n * node.val = 'foo';\n * node.isEmpty(); //=> false\n * ```\n * @param {Function} `fn` (optional) Filter function that is called on `node` and/or child nodes. `isEmpty` will return false immediately when the filter function returns false on any nodes.\n * @return {Boolean}\n * @api public\n */\n\nNode.prototype.isEmpty = function(fn) {\n return utils.isEmpty(this, fn);\n};\n\n/**\n * Given node `foo` and node `bar`, push node `bar` onto `foo.nodes`, and\n * set `foo` as `bar.parent`.\n *\n * ```js\n * var foo = new Node({type: 'foo'});\n * var bar = new Node({type: 'bar'});\n * foo.push(bar);\n * ```\n * @param {Object} `node`\n * @return {Number} Returns the length of `node.nodes`\n * @api public\n */\n\nNode.prototype.push = function(node) {\n assert(Node.isNode(node), 'expected node to be an instance of Node');\n define(node, 'parent', this);\n\n this.nodes = this.nodes || [];\n return this.nodes.push(node);\n};\n\n/**\n * Given node `foo` and node `bar`, unshift node `bar` onto `foo.nodes`, and\n * set `foo` as `bar.parent`.\n *\n * ```js\n * var foo = new Node({type: 'foo'});\n * var bar = new Node({type: 'bar'});\n * foo.unshift(bar);\n * ```\n * @param {Object} `node`\n * @return {Number} Returns the length of `node.nodes`\n * @api public\n */\n\nNode.prototype.unshift = function(node) {\n assert(Node.isNode(node), 'expected node to be an instance of Node');\n define(node, 'parent', this);\n\n this.nodes = this.nodes || [];\n return this.nodes.unshift(node);\n};\n\n/**\n * Pop a node from `node.nodes`.\n *\n * ```js\n * var node = new Node({type: 'foo'});\n * node.push(new Node({type: 'a'}));\n * node.push(new Node({type: 'b'}));\n * node.push(new Node({type: 'c'}));\n * node.push(new Node({type: 'd'}));\n * console.log(node.nodes.length);\n * //=> 4\n * node.pop();\n * console.log(node.nodes.length);\n * //=> 3\n * ```\n * @return {Number} Returns the popped `node`\n * @api public\n */\n\nNode.prototype.pop = function() {\n return this.nodes && this.nodes.pop();\n};\n\n/**\n * Shift a node from `node.nodes`.\n *\n * ```js\n * var node = new Node({type: 'foo'});\n * node.push(new Node({type: 'a'}));\n * node.push(new Node({type: 'b'}));\n * node.push(new Node({type: 'c'}));\n * node.push(new Node({type: 'd'}));\n * console.log(node.nodes.length);\n * //=> 4\n * node.shift();\n * console.log(node.nodes.length);\n * //=> 3\n * ```\n * @return {Object} Returns the shifted `node`\n * @api public\n */\n\nNode.prototype.shift = function() {\n return this.nodes && this.nodes.shift();\n};\n\n/**\n * Remove `node` from `node.nodes`.\n *\n * ```js\n * node.remove(childNode);\n * ```\n * @param {Object} `node`\n * @return {Object} Returns the removed node.\n * @api public\n */\n\nNode.prototype.remove = function(node) {\n assert(Node.isNode(node), 'expected node to be an instance of Node');\n this.nodes = this.nodes || [];\n var idx = node.index;\n if (idx !== -1) {\n node.index = -1;\n return this.nodes.splice(idx, 1);\n }\n return null;\n};\n\n/**\n * Get the first child node from `node.nodes` that matches the given `type`.\n * If `type` is a number, the child node at that index is returned.\n *\n * ```js\n * var child = node.find(1); //<= index of the node to get\n * var child = node.find('foo'); //<= node.type of a child node\n * var child = node.find(/^(foo|bar)$/); //<= regex to match node.type\n * var child = node.find(['foo', 'bar']); //<= array of node.type(s)\n * ```\n * @param {String} `type`\n * @return {Object} Returns a child node or undefined.\n * @api public\n */\n\nNode.prototype.find = function(type) {\n return utils.findNode(this.nodes, type);\n};\n\n/**\n * Return true if the node is the given `type`.\n *\n * ```js\n * var node = new Node({type: 'bar'});\n * cosole.log(node.isType('foo')); // false\n * cosole.log(node.isType(/^(foo|bar)$/)); // true\n * cosole.log(node.isType(['foo', 'bar'])); // true\n * ```\n * @param {String} `type`\n * @return {Boolean}\n * @api public\n */\n\nNode.prototype.isType = function(type) {\n return utils.isType(this, type);\n};\n\n/**\n * Return true if the `node.nodes` has the given `type`.\n *\n * ```js\n * var foo = new Node({type: 'foo'});\n * var bar = new Node({type: 'bar'});\n * foo.push(bar);\n *\n * cosole.log(foo.hasType('qux')); // false\n * cosole.log(foo.hasType(/^(qux|bar)$/)); // true\n * cosole.log(foo.hasType(['qux', 'bar'])); // true\n * ```\n * @param {String} `type`\n * @return {Boolean}\n * @api public\n */\n\nNode.prototype.hasType = function(type) {\n return utils.hasType(this, type);\n};\n\n/**\n * Get the siblings array, or `null` if it doesn't exist.\n *\n * ```js\n * var foo = new Node({type: 'foo'});\n * var bar = new Node({type: 'bar'});\n * var baz = new Node({type: 'baz'});\n * foo.push(bar);\n * foo.push(baz);\n *\n * console.log(bar.siblings.length) // 2\n * console.log(baz.siblings.length) // 2\n * ```\n * @return {Array}\n * @api public\n */\n\nObject.defineProperty(Node.prototype, 'siblings', {\n set: function() {\n throw new Error('node.siblings is a getter and cannot be defined');\n },\n get: function() {\n return this.parent ? this.parent.nodes : null;\n }\n});\n\n/**\n * Get the node's current index from `node.parent.nodes`.\n * This should always be correct, even when the parent adds nodes.\n *\n * ```js\n * var foo = new Node({type: 'foo'});\n * var bar = new Node({type: 'bar'});\n * var baz = new Node({type: 'baz'});\n * var qux = new Node({type: 'qux'});\n * foo.push(bar);\n * foo.push(baz);\n * foo.unshift(qux);\n *\n * console.log(bar.index) // 1\n * console.log(baz.index) // 2\n * console.log(qux.index) // 0\n * ```\n * @return {Number}\n * @api public\n */\n\nObject.defineProperty(Node.prototype, 'index', {\n set: function(index) {\n define(this, 'idx', index);\n },\n get: function() {\n if (!Array.isArray(this.siblings)) {\n return -1;\n }\n var tok = this.idx !== -1 ? this.siblings[this.idx] : null;\n if (tok !== this) {\n this.idx = this.siblings.indexOf(this);\n }\n return this.idx;\n }\n});\n\n/**\n * Get the previous node from the siblings array or `null`.\n *\n * ```js\n * var foo = new Node({type: 'foo'});\n * var bar = new Node({type: 'bar'});\n * var baz = new Node({type: 'baz'});\n * foo.push(bar);\n * foo.push(baz);\n *\n * console.log(baz.prev.type) // 'bar'\n * ```\n * @return {Object}\n * @api public\n */\n\nObject.defineProperty(Node.prototype, 'prev', {\n set: function() {\n throw new Error('node.prev is a getter and cannot be defined');\n },\n get: function() {\n if (Array.isArray(this.siblings)) {\n return this.siblings[this.index - 1] || this.parent.prev;\n }\n return null;\n }\n});\n\n/**\n * Get the siblings array, or `null` if it doesn't exist.\n *\n * ```js\n * var foo = new Node({type: 'foo'});\n * var bar = new Node({type: 'bar'});\n * var baz = new Node({type: 'baz'});\n * foo.push(bar);\n * foo.push(baz);\n *\n * console.log(bar.siblings.length) // 2\n * console.log(baz.siblings.length) // 2\n * ```\n * @return {Object}\n * @api public\n */\n\nObject.defineProperty(Node.prototype, 'next', {\n set: function() {\n throw new Error('node.next is a getter and cannot be defined');\n },\n get: function() {\n if (Array.isArray(this.siblings)) {\n return this.siblings[this.index + 1] || this.parent.next;\n }\n return null;\n }\n});\n\n/**\n * Get the first node from `node.nodes`.\n *\n * ```js\n * var foo = new Node({type: 'foo'});\n * var bar = new Node({type: 'bar'});\n * var baz = new Node({type: 'baz'});\n * var qux = new Node({type: 'qux'});\n * foo.push(bar);\n * foo.push(baz);\n * foo.push(qux);\n *\n * console.log(foo.first.type) // 'bar'\n * ```\n * @return {Object} The first node, or undefiend\n * @api public\n */\n\nObject.defineProperty(Node.prototype, 'first', {\n get: function() {\n return this.nodes ? this.nodes[0] : null;\n }\n});\n\n/**\n * Get the last node from `node.nodes`.\n *\n * ```js\n * var foo = new Node({type: 'foo'});\n * var bar = new Node({type: 'bar'});\n * var baz = new Node({type: 'baz'});\n * var qux = new Node({type: 'qux'});\n * foo.push(bar);\n * foo.push(baz);\n * foo.push(qux);\n *\n * console.log(foo.last.type) // 'qux'\n * ```\n * @return {Object} The last node, or undefiend\n * @api public\n */\n\nObject.defineProperty(Node.prototype, 'last', {\n get: function() {\n return this.nodes ? utils.last(this.nodes) : null;\n }\n});\n\n/**\n * Get the last node from `node.nodes`.\n *\n * ```js\n * var foo = new Node({type: 'foo'});\n * var bar = new Node({type: 'bar'});\n * var baz = new Node({type: 'baz'});\n * var qux = new Node({type: 'qux'});\n * foo.push(bar);\n * foo.push(baz);\n * foo.push(qux);\n *\n * console.log(foo.last.type) // 'qux'\n * ```\n * @return {Object} The last node, or undefiend\n * @api public\n */\n\nObject.defineProperty(Node.prototype, 'scope', {\n get: function() {\n if (this.isScope !== true) {\n return this.parent ? this.parent.scope : this;\n }\n return this;\n }\n});\n\n/**\n * Get own property names from Node prototype, but only the\n * first time `Node` is instantiated\n */\n\nfunction lazyKeys() {\n if (!ownNames) {\n ownNames = Object.getOwnPropertyNames(Node.prototype);\n }\n}\n\n/**\n * Simplified assertion. Throws an error is `val` is falsey.\n */\n\nfunction assert(val, message) {\n if (!val) throw new Error(message);\n}\n\n/**\n * Expose `Node`\n */\n\nexports = module.exports = Node;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/snapdragon-node/index.js?"); + +/***/ }), + +/***/ "./node_modules/snapdragon-node/node_modules/define-property/index.js": +/*!****************************************************************************!*\ + !*** ./node_modules/snapdragon-node/node_modules/define-property/index.js ***! + \****************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * define-property \n *\n * Copyright (c) 2015, 2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar isDescriptor = __webpack_require__(/*! is-descriptor */ \"./node_modules/is-descriptor/index.js\");\n\nmodule.exports = function defineProperty(obj, prop, val) {\n if (typeof obj !== 'object' && typeof obj !== 'function') {\n throw new TypeError('expected an object or function.');\n }\n\n if (typeof prop !== 'string') {\n throw new TypeError('expected `prop` to be a string.');\n }\n\n if (isDescriptor(val) && ('set' in val || 'get' in val)) {\n return Object.defineProperty(obj, prop, val);\n }\n\n return Object.defineProperty(obj, prop, {\n configurable: true,\n enumerable: false,\n writable: true,\n value: val\n });\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/snapdragon-node/node_modules/define-property/index.js?"); + +/***/ }), + +/***/ "./node_modules/snapdragon-util/index.js": +/*!***********************************************!*\ + !*** ./node_modules/snapdragon-util/index.js ***! + \***********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar typeOf = __webpack_require__(/*! kind-of */ \"./node_modules/snapdragon-util/node_modules/kind-of/index.js\");\nvar utils = module.exports;\n\n/**\n * Returns true if the given value is a node.\n *\n * ```js\n * var Node = require('snapdragon-node');\n * var node = new Node({type: 'foo'});\n * console.log(utils.isNode(node)); //=> true\n * console.log(utils.isNode({})); //=> false\n * ```\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @returns {Boolean}\n * @api public\n */\n\nutils.isNode = function(node) {\n return typeOf(node) === 'object' && node.isNode === true;\n};\n\n/**\n * Emit an empty string for the given `node`.\n *\n * ```js\n * // do nothing for beginning-of-string\n * snapdragon.compiler.set('bos', utils.noop);\n * ```\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @returns {undefined}\n * @api public\n */\n\nutils.noop = function(node) {\n append(this, '', node);\n};\n\n/**\n * Appdend `node.val` to `compiler.output`, exactly as it was created\n * by the parser.\n *\n * ```js\n * snapdragon.compiler.set('text', utils.identity);\n * ```\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @returns {undefined}\n * @api public\n */\n\nutils.identity = function(node) {\n append(this, node.val, node);\n};\n\n/**\n * Previously named `.emit`, this method appends the given `val`\n * to `compiler.output` for the given node. Useful when you know\n * what value should be appended advance, regardless of the actual\n * value of `node.val`.\n *\n * ```js\n * snapdragon.compiler\n * .set('i', function(node) {\n * this.mapVisit(node);\n * })\n * .set('i.open', utils.append(''))\n * .set('i.close', utils.append(''))\n * ```\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @returns {Function} Returns a compiler middleware function.\n * @api public\n */\n\nutils.append = function(val) {\n return function(node) {\n append(this, val, node);\n };\n};\n\n/**\n * Used in compiler middleware, this onverts an AST node into\n * an empty `text` node and deletes `node.nodes` if it exists.\n * The advantage of this method is that, as opposed to completely\n * removing the node, indices will not need to be re-calculated\n * in sibling nodes, and nothing is appended to the output.\n *\n * ```js\n * utils.toNoop(node);\n * // convert `node.nodes` to the given value instead of deleting it\n * utils.toNoop(node, []);\n * ```\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @param {Array} `nodes` Optionally pass a new `nodes` value, to replace the existing `node.nodes` array.\n * @api public\n */\n\nutils.toNoop = function(node, nodes) {\n if (nodes) {\n node.nodes = nodes;\n } else {\n delete node.nodes;\n node.type = 'text';\n node.val = '';\n }\n};\n\n/**\n * Visit `node` with the given `fn`. The built-in `.visit` method in snapdragon\n * automatically calls registered compilers, this allows you to pass a visitor\n * function.\n *\n * ```js\n * snapdragon.compiler.set('i', function(node) {\n * utils.visit(node, function(childNode) {\n * // do stuff with \"childNode\"\n * return childNode;\n * });\n * });\n * ```\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @param {Function} `fn`\n * @return {Object} returns the node after recursively visiting all child nodes.\n * @api public\n */\n\nutils.visit = function(node, fn) {\n assert(utils.isNode(node), 'expected node to be an instance of Node');\n assert(isFunction(fn), 'expected a visitor function');\n fn(node);\n return node.nodes ? utils.mapVisit(node, fn) : node;\n};\n\n/**\n * Map [visit](#visit) the given `fn` over `node.nodes`. This is called by\n * [visit](#visit), use this method if you do not want `fn` to be called on\n * the first node.\n *\n * ```js\n * snapdragon.compiler.set('i', function(node) {\n * utils.mapVisit(node, function(childNode) {\n * // do stuff with \"childNode\"\n * return childNode;\n * });\n * });\n * ```\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @param {Object} `options`\n * @param {Function} `fn`\n * @return {Object} returns the node\n * @api public\n */\n\nutils.mapVisit = function(node, fn) {\n assert(utils.isNode(node), 'expected node to be an instance of Node');\n assert(isArray(node.nodes), 'expected node.nodes to be an array');\n assert(isFunction(fn), 'expected a visitor function');\n\n for (var i = 0; i < node.nodes.length; i++) {\n utils.visit(node.nodes[i], fn);\n }\n return node;\n};\n\n/**\n * Unshift an `*.open` node onto `node.nodes`.\n *\n * ```js\n * var Node = require('snapdragon-node');\n * snapdragon.parser.set('brace', function(node) {\n * var match = this.match(/^{/);\n * if (match) {\n * var parent = new Node({type: 'brace'});\n * utils.addOpen(parent, Node);\n * console.log(parent.nodes[0]):\n * // { type: 'brace.open', val: '' };\n *\n * // push the parent \"brace\" node onto the stack\n * this.push(parent);\n *\n * // return the parent node, so it's also added to the AST\n * return brace;\n * }\n * });\n * ```\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][].\n * @param {Function} `filter` Optionaly specify a filter function to exclude the node.\n * @return {Object} Returns the created opening node.\n * @api public\n */\n\nutils.addOpen = function(node, Node, val, filter) {\n assert(utils.isNode(node), 'expected node to be an instance of Node');\n assert(isFunction(Node), 'expected Node to be a constructor function');\n\n if (typeof val === 'function') {\n filter = val;\n val = '';\n }\n\n if (typeof filter === 'function' && !filter(node)) return;\n var open = new Node({ type: node.type + '.open', val: val});\n var unshift = node.unshift || node.unshiftNode;\n if (typeof unshift === 'function') {\n unshift.call(node, open);\n } else {\n utils.unshiftNode(node, open);\n }\n return open;\n};\n\n/**\n * Push a `*.close` node onto `node.nodes`.\n *\n * ```js\n * var Node = require('snapdragon-node');\n * snapdragon.parser.set('brace', function(node) {\n * var match = this.match(/^}/);\n * if (match) {\n * var parent = this.parent();\n * if (parent.type !== 'brace') {\n * throw new Error('missing opening: ' + '}');\n * }\n *\n * utils.addClose(parent, Node);\n * console.log(parent.nodes[parent.nodes.length - 1]):\n * // { type: 'brace.close', val: '' };\n *\n * // no need to return a node, since the parent\n * // was already added to the AST\n * return;\n * }\n * });\n * ```\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][].\n * @param {Function} `filter` Optionaly specify a filter function to exclude the node.\n * @return {Object} Returns the created closing node.\n * @api public\n */\n\nutils.addClose = function(node, Node, val, filter) {\n assert(utils.isNode(node), 'expected node to be an instance of Node');\n assert(isFunction(Node), 'expected Node to be a constructor function');\n\n if (typeof val === 'function') {\n filter = val;\n val = '';\n }\n\n if (typeof filter === 'function' && !filter(node)) return;\n var close = new Node({ type: node.type + '.close', val: val});\n var push = node.push || node.pushNode;\n if (typeof push === 'function') {\n push.call(node, close);\n } else {\n utils.pushNode(node, close);\n }\n return close;\n};\n\n/**\n * Wraps the given `node` with `*.open` and `*.close` nodes.\n *\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][].\n * @param {Function} `filter` Optionaly specify a filter function to exclude the node.\n * @return {Object} Returns the node\n * @api public\n */\n\nutils.wrapNodes = function(node, Node, filter) {\n assert(utils.isNode(node), 'expected node to be an instance of Node');\n assert(isFunction(Node), 'expected Node to be a constructor function');\n\n utils.addOpen(node, Node, filter);\n utils.addClose(node, Node, filter);\n return node;\n};\n\n/**\n * Push the given `node` onto `parent.nodes`, and set `parent` as `node.parent.\n *\n * ```js\n * var parent = new Node({type: 'foo'});\n * var node = new Node({type: 'bar'});\n * utils.pushNode(parent, node);\n * console.log(parent.nodes[0].type) // 'bar'\n * console.log(node.parent.type) // 'foo'\n * ```\n * @param {Object} `parent`\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @return {Object} Returns the child node\n * @api public\n */\n\nutils.pushNode = function(parent, node) {\n assert(utils.isNode(parent), 'expected parent node to be an instance of Node');\n assert(utils.isNode(node), 'expected node to be an instance of Node');\n\n node.define('parent', parent);\n parent.nodes = parent.nodes || [];\n parent.nodes.push(node);\n return node;\n};\n\n/**\n * Unshift `node` onto `parent.nodes`, and set `parent` as `node.parent.\n *\n * ```js\n * var parent = new Node({type: 'foo'});\n * var node = new Node({type: 'bar'});\n * utils.unshiftNode(parent, node);\n * console.log(parent.nodes[0].type) // 'bar'\n * console.log(node.parent.type) // 'foo'\n * ```\n * @param {Object} `parent`\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @return {undefined}\n * @api public\n */\n\nutils.unshiftNode = function(parent, node) {\n assert(utils.isNode(parent), 'expected parent node to be an instance of Node');\n assert(utils.isNode(node), 'expected node to be an instance of Node');\n\n node.define('parent', parent);\n parent.nodes = parent.nodes || [];\n parent.nodes.unshift(node);\n};\n\n/**\n * Pop the last `node` off of `parent.nodes`. The advantage of\n * using this method is that it checks for `node.nodes` and works\n * with any version of `snapdragon-node`.\n *\n * ```js\n * var parent = new Node({type: 'foo'});\n * utils.pushNode(parent, new Node({type: 'foo'}));\n * utils.pushNode(parent, new Node({type: 'bar'}));\n * utils.pushNode(parent, new Node({type: 'baz'}));\n * console.log(parent.nodes.length); //=> 3\n * utils.popNode(parent);\n * console.log(parent.nodes.length); //=> 2\n * ```\n * @param {Object} `parent`\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @return {Number|Undefined} Returns the length of `node.nodes` or undefined.\n * @api public\n */\n\nutils.popNode = function(node) {\n assert(utils.isNode(node), 'expected node to be an instance of Node');\n if (typeof node.pop === 'function') {\n return node.pop();\n }\n return node.nodes && node.nodes.pop();\n};\n\n/**\n * Shift the first `node` off of `parent.nodes`. The advantage of\n * using this method is that it checks for `node.nodes` and works\n * with any version of `snapdragon-node`.\n *\n * ```js\n * var parent = new Node({type: 'foo'});\n * utils.pushNode(parent, new Node({type: 'foo'}));\n * utils.pushNode(parent, new Node({type: 'bar'}));\n * utils.pushNode(parent, new Node({type: 'baz'}));\n * console.log(parent.nodes.length); //=> 3\n * utils.shiftNode(parent);\n * console.log(parent.nodes.length); //=> 2\n * ```\n * @param {Object} `parent`\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @return {Number|Undefined} Returns the length of `node.nodes` or undefined.\n * @api public\n */\n\nutils.shiftNode = function(node) {\n assert(utils.isNode(node), 'expected node to be an instance of Node');\n if (typeof node.shift === 'function') {\n return node.shift();\n }\n return node.nodes && node.nodes.shift();\n};\n\n/**\n * Remove the specified `node` from `parent.nodes`.\n *\n * ```js\n * var parent = new Node({type: 'abc'});\n * var foo = new Node({type: 'foo'});\n * utils.pushNode(parent, foo);\n * utils.pushNode(parent, new Node({type: 'bar'}));\n * utils.pushNode(parent, new Node({type: 'baz'}));\n * console.log(parent.nodes.length); //=> 3\n * utils.removeNode(parent, foo);\n * console.log(parent.nodes.length); //=> 2\n * ```\n * @param {Object} `parent`\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @return {Object|undefined} Returns the removed node, if successful, or undefined if it does not exist on `parent.nodes`.\n * @api public\n */\n\nutils.removeNode = function(parent, node) {\n assert(utils.isNode(parent), 'expected parent.node to be an instance of Node');\n assert(utils.isNode(node), 'expected node to be an instance of Node');\n\n if (!parent.nodes) {\n return null;\n }\n\n if (typeof parent.remove === 'function') {\n return parent.remove(node);\n }\n\n var idx = parent.nodes.indexOf(node);\n if (idx !== -1) {\n return parent.nodes.splice(idx, 1);\n }\n};\n\n/**\n * Returns true if `node.type` matches the given `type`. Throws a\n * `TypeError` if `node` is not an instance of `Node`.\n *\n * ```js\n * var Node = require('snapdragon-node');\n * var node = new Node({type: 'foo'});\n * console.log(utils.isType(node, 'foo')); // false\n * console.log(utils.isType(node, 'bar')); // true\n * ```\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @param {String} `type`\n * @return {Boolean}\n * @api public\n */\n\nutils.isType = function(node, type) {\n assert(utils.isNode(node), 'expected node to be an instance of Node');\n switch (typeOf(type)) {\n case 'array':\n var types = type.slice();\n for (var i = 0; i < types.length; i++) {\n if (utils.isType(node, types[i])) {\n return true;\n }\n }\n return false;\n case 'string':\n return node.type === type;\n case 'regexp':\n return type.test(node.type);\n default: {\n throw new TypeError('expected \"type\" to be an array, string or regexp');\n }\n }\n};\n\n/**\n * Returns true if the given `node` has the given `type` in `node.nodes`.\n * Throws a `TypeError` if `node` is not an instance of `Node`.\n *\n * ```js\n * var Node = require('snapdragon-node');\n * var node = new Node({\n * type: 'foo',\n * nodes: [\n * new Node({type: 'bar'}),\n * new Node({type: 'baz'})\n * ]\n * });\n * console.log(utils.hasType(node, 'xyz')); // false\n * console.log(utils.hasType(node, 'baz')); // true\n * ```\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @param {String} `type`\n * @return {Boolean}\n * @api public\n */\n\nutils.hasType = function(node, type) {\n assert(utils.isNode(node), 'expected node to be an instance of Node');\n if (!Array.isArray(node.nodes)) return false;\n for (var i = 0; i < node.nodes.length; i++) {\n if (utils.isType(node.nodes[i], type)) {\n return true;\n }\n }\n return false;\n};\n\n/**\n * Returns the first node from `node.nodes` of the given `type`\n *\n * ```js\n * var node = new Node({\n * type: 'foo',\n * nodes: [\n * new Node({type: 'text', val: 'abc'}),\n * new Node({type: 'text', val: 'xyz'})\n * ]\n * });\n *\n * var textNode = utils.firstOfType(node.nodes, 'text');\n * console.log(textNode.val);\n * //=> 'abc'\n * ```\n * @param {Array} `nodes`\n * @param {String} `type`\n * @return {Object|undefined} Returns the first matching node or undefined.\n * @api public\n */\n\nutils.firstOfType = function(nodes, type) {\n for (var i = 0; i < nodes.length; i++) {\n var node = nodes[i];\n if (utils.isType(node, type)) {\n return node;\n }\n }\n};\n\n/**\n * Returns the node at the specified index, or the first node of the\n * given `type` from `node.nodes`.\n *\n * ```js\n * var node = new Node({\n * type: 'foo',\n * nodes: [\n * new Node({type: 'text', val: 'abc'}),\n * new Node({type: 'text', val: 'xyz'})\n * ]\n * });\n *\n * var nodeOne = utils.findNode(node.nodes, 'text');\n * console.log(nodeOne.val);\n * //=> 'abc'\n *\n * var nodeTwo = utils.findNode(node.nodes, 1);\n * console.log(nodeTwo.val);\n * //=> 'xyz'\n * ```\n *\n * @param {Array} `nodes`\n * @param {String|Number} `type` Node type or index.\n * @return {Object} Returns a node or undefined.\n * @api public\n */\n\nutils.findNode = function(nodes, type) {\n if (!Array.isArray(nodes)) {\n return null;\n }\n if (typeof type === 'number') {\n return nodes[type];\n }\n return utils.firstOfType(nodes, type);\n};\n\n/**\n * Returns true if the given node is an \"*.open\" node.\n *\n * ```js\n * var Node = require('snapdragon-node');\n * var brace = new Node({type: 'brace'});\n * var open = new Node({type: 'brace.open'});\n * var close = new Node({type: 'brace.close'});\n *\n * console.log(utils.isOpen(brace)); // false\n * console.log(utils.isOpen(open)); // true\n * console.log(utils.isOpen(close)); // false\n * ```\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @return {Boolean}\n * @api public\n */\n\nutils.isOpen = function(node) {\n assert(utils.isNode(node), 'expected node to be an instance of Node');\n return node.type.slice(-5) === '.open';\n};\n\n/**\n * Returns true if the given node is a \"*.close\" node.\n *\n * ```js\n * var Node = require('snapdragon-node');\n * var brace = new Node({type: 'brace'});\n * var open = new Node({type: 'brace.open'});\n * var close = new Node({type: 'brace.close'});\n *\n * console.log(utils.isClose(brace)); // false\n * console.log(utils.isClose(open)); // false\n * console.log(utils.isClose(close)); // true\n * ```\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @return {Boolean}\n * @api public\n */\n\nutils.isClose = function(node) {\n assert(utils.isNode(node), 'expected node to be an instance of Node');\n return node.type.slice(-6) === '.close';\n};\n\n/**\n * Returns true if `node.nodes` **has** an `.open` node\n *\n * ```js\n * var Node = require('snapdragon-node');\n * var brace = new Node({\n * type: 'brace',\n * nodes: []\n * });\n *\n * var open = new Node({type: 'brace.open'});\n * console.log(utils.hasOpen(brace)); // false\n *\n * brace.pushNode(open);\n * console.log(utils.hasOpen(brace)); // true\n * ```\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @return {Boolean}\n * @api public\n */\n\nutils.hasOpen = function(node) {\n assert(utils.isNode(node), 'expected node to be an instance of Node');\n var first = node.first || node.nodes ? node.nodes[0] : null;\n if (utils.isNode(first)) {\n return first.type === node.type + '.open';\n }\n return false;\n};\n\n/**\n * Returns true if `node.nodes` **has** a `.close` node\n *\n * ```js\n * var Node = require('snapdragon-node');\n * var brace = new Node({\n * type: 'brace',\n * nodes: []\n * });\n *\n * var close = new Node({type: 'brace.close'});\n * console.log(utils.hasClose(brace)); // false\n *\n * brace.pushNode(close);\n * console.log(utils.hasClose(brace)); // true\n * ```\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @return {Boolean}\n * @api public\n */\n\nutils.hasClose = function(node) {\n assert(utils.isNode(node), 'expected node to be an instance of Node');\n var last = node.last || node.nodes ? node.nodes[node.nodes.length - 1] : null;\n if (utils.isNode(last)) {\n return last.type === node.type + '.close';\n }\n return false;\n};\n\n/**\n * Returns true if `node.nodes` has both `.open` and `.close` nodes\n *\n * ```js\n * var Node = require('snapdragon-node');\n * var brace = new Node({\n * type: 'brace',\n * nodes: []\n * });\n *\n * var open = new Node({type: 'brace.open'});\n * var close = new Node({type: 'brace.close'});\n * console.log(utils.hasOpen(brace)); // false\n * console.log(utils.hasClose(brace)); // false\n *\n * brace.pushNode(open);\n * brace.pushNode(close);\n * console.log(utils.hasOpen(brace)); // true\n * console.log(utils.hasClose(brace)); // true\n * ```\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @return {Boolean}\n * @api public\n */\n\nutils.hasOpenAndClose = function(node) {\n return utils.hasOpen(node) && utils.hasClose(node);\n};\n\n/**\n * Push the given `node` onto the `state.inside` array for the\n * given type. This array is used as a specialized \"stack\" for\n * only the given `node.type`.\n *\n * ```js\n * var state = { inside: {}};\n * var node = new Node({type: 'brace'});\n * utils.addType(state, node);\n * console.log(state.inside);\n * //=> { brace: [{type: 'brace'}] }\n * ```\n * @param {Object} `state` The `compiler.state` object or custom state object.\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @return {Array} Returns the `state.inside` stack for the given type.\n * @api public\n */\n\nutils.addType = function(state, node) {\n assert(utils.isNode(node), 'expected node to be an instance of Node');\n assert(isObject(state), 'expected state to be an object');\n\n var type = node.parent\n ? node.parent.type\n : node.type.replace(/\\.open$/, '');\n\n if (!state.hasOwnProperty('inside')) {\n state.inside = {};\n }\n if (!state.inside.hasOwnProperty(type)) {\n state.inside[type] = [];\n }\n\n var arr = state.inside[type];\n arr.push(node);\n return arr;\n};\n\n/**\n * Remove the given `node` from the `state.inside` array for the\n * given type. This array is used as a specialized \"stack\" for\n * only the given `node.type`.\n *\n * ```js\n * var state = { inside: {}};\n * var node = new Node({type: 'brace'});\n * utils.addType(state, node);\n * console.log(state.inside);\n * //=> { brace: [{type: 'brace'}] }\n * utils.removeType(state, node);\n * //=> { brace: [] }\n * ```\n * @param {Object} `state` The `compiler.state` object or custom state object.\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @return {Array} Returns the `state.inside` stack for the given type.\n * @api public\n */\n\nutils.removeType = function(state, node) {\n assert(utils.isNode(node), 'expected node to be an instance of Node');\n assert(isObject(state), 'expected state to be an object');\n\n var type = node.parent\n ? node.parent.type\n : node.type.replace(/\\.close$/, '');\n\n if (state.inside.hasOwnProperty(type)) {\n return state.inside[type].pop();\n }\n};\n\n/**\n * Returns true if `node.val` is an empty string, or `node.nodes` does\n * not contain any non-empty text nodes.\n *\n * ```js\n * var node = new Node({type: 'text'});\n * utils.isEmpty(node); //=> true\n * node.val = 'foo';\n * utils.isEmpty(node); //=> false\n * ```\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @param {Function} `fn`\n * @return {Boolean}\n * @api public\n */\n\nutils.isEmpty = function(node, fn) {\n assert(utils.isNode(node), 'expected node to be an instance of Node');\n\n if (!Array.isArray(node.nodes)) {\n if (node.type !== 'text') {\n return true;\n }\n if (typeof fn === 'function') {\n return fn(node, node.parent);\n }\n return !utils.trim(node.val);\n }\n\n for (var i = 0; i < node.nodes.length; i++) {\n var child = node.nodes[i];\n if (utils.isOpen(child) || utils.isClose(child)) {\n continue;\n }\n if (!utils.isEmpty(child, fn)) {\n return false;\n }\n }\n\n return true;\n};\n\n/**\n * Returns true if the `state.inside` stack for the given type exists\n * and has one or more nodes on it.\n *\n * ```js\n * var state = { inside: {}};\n * var node = new Node({type: 'brace'});\n * console.log(utils.isInsideType(state, 'brace')); //=> false\n * utils.addType(state, node);\n * console.log(utils.isInsideType(state, 'brace')); //=> true\n * utils.removeType(state, node);\n * console.log(utils.isInsideType(state, 'brace')); //=> false\n * ```\n * @param {Object} `state`\n * @param {String} `type`\n * @return {Boolean}\n * @api public\n */\n\nutils.isInsideType = function(state, type) {\n assert(isObject(state), 'expected state to be an object');\n assert(isString(type), 'expected type to be a string');\n\n if (!state.hasOwnProperty('inside')) {\n return false;\n }\n\n if (!state.inside.hasOwnProperty(type)) {\n return false;\n }\n\n return state.inside[type].length > 0;\n};\n\n/**\n * Returns true if `node` is either a child or grand-child of the given `type`,\n * or `state.inside[type]` is a non-empty array.\n *\n * ```js\n * var state = { inside: {}};\n * var node = new Node({type: 'brace'});\n * var open = new Node({type: 'brace.open'});\n * console.log(utils.isInside(state, open, 'brace')); //=> false\n * utils.pushNode(node, open);\n * console.log(utils.isInside(state, open, 'brace')); //=> true\n * ```\n * @param {Object} `state` Either the `compiler.state` object, if it exists, or a user-supplied state object.\n * @param {Object} `node` Instance of [snapdragon-node][]\n * @param {String} `type` The `node.type` to check for.\n * @return {Boolean}\n * @api public\n */\n\nutils.isInside = function(state, node, type) {\n assert(utils.isNode(node), 'expected node to be an instance of Node');\n assert(isObject(state), 'expected state to be an object');\n\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n if (utils.isInside(state, node, type[i])) {\n return true;\n }\n }\n return false;\n }\n\n var parent = node.parent;\n if (typeof type === 'string') {\n return (parent && parent.type === type) || utils.isInsideType(state, type);\n }\n\n if (typeOf(type) === 'regexp') {\n if (parent && parent.type && type.test(parent.type)) {\n return true;\n }\n\n var keys = Object.keys(state.inside);\n var len = keys.length;\n var idx = -1;\n while (++idx < len) {\n var key = keys[idx];\n var val = state.inside[key];\n\n if (Array.isArray(val) && val.length !== 0 && type.test(key)) {\n return true;\n }\n }\n }\n return false;\n};\n\n/**\n * Get the last `n` element from the given `array`. Used for getting\n * a node from `node.nodes.`\n *\n * @param {Array} `array`\n * @param {Number} `n`\n * @return {undefined}\n * @api public\n */\n\nutils.last = function(arr, n) {\n return arr[arr.length - (n || 1)];\n};\n\n/**\n * Cast the given `val` to an array.\n *\n * ```js\n * console.log(utils.arrayify(''));\n * //=> []\n * console.log(utils.arrayify('foo'));\n * //=> ['foo']\n * console.log(utils.arrayify(['foo']));\n * //=> ['foo']\n * ```\n * @param {any} `val`\n * @return {Array}\n * @api public\n */\n\nutils.arrayify = function(val) {\n if (typeof val === 'string' && val !== '') {\n return [val];\n }\n if (!Array.isArray(val)) {\n return [];\n }\n return val;\n};\n\n/**\n * Convert the given `val` to a string by joining with `,`. Useful\n * for creating a cheerio/CSS/DOM-style selector from a list of strings.\n *\n * @param {any} `val`\n * @return {Array}\n * @api public\n */\n\nutils.stringify = function(val) {\n return utils.arrayify(val).join(',');\n};\n\n/**\n * Ensure that the given value is a string and call `.trim()` on it,\n * or return an empty string.\n *\n * @param {String} `str`\n * @return {String}\n * @api public\n */\n\nutils.trim = function(str) {\n return typeof str === 'string' ? str.trim() : '';\n};\n\n/**\n * Return true if val is an object\n */\n\nfunction isObject(val) {\n return typeOf(val) === 'object';\n}\n\n/**\n * Return true if val is a string\n */\n\nfunction isString(val) {\n return typeof val === 'string';\n}\n\n/**\n * Return true if val is a function\n */\n\nfunction isFunction(val) {\n return typeof val === 'function';\n}\n\n/**\n * Return true if val is an array\n */\n\nfunction isArray(val) {\n return Array.isArray(val);\n}\n\n/**\n * Shim to ensure the `.append` methods work with any version of snapdragon\n */\n\nfunction append(compiler, val, node) {\n if (typeof compiler.append !== 'function') {\n return compiler.emit(val, node);\n }\n return compiler.append(val, node);\n}\n\n/**\n * Simplified assertion. Throws an error is `val` is falsey.\n */\n\nfunction assert(val, message) {\n if (!val) throw new Error(message);\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/snapdragon-util/index.js?"); + +/***/ }), + +/***/ "./node_modules/snapdragon-util/node_modules/kind-of/index.js": +/*!********************************************************************!*\ + !*** ./node_modules/snapdragon-util/node_modules/kind-of/index.js ***! + \********************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var isBuffer = __webpack_require__(/*! is-buffer */ \"./node_modules/is-buffer/index.js\");\nvar toString = Object.prototype.toString;\n\n/**\n * Get the native `typeof` a value.\n *\n * @param {*} `val`\n * @return {*} Native javascript type\n */\n\nmodule.exports = function kindOf(val) {\n // primitivies\n if (typeof val === 'undefined') {\n return 'undefined';\n }\n if (val === null) {\n return 'null';\n }\n if (val === true || val === false || val instanceof Boolean) {\n return 'boolean';\n }\n if (typeof val === 'string' || val instanceof String) {\n return 'string';\n }\n if (typeof val === 'number' || val instanceof Number) {\n return 'number';\n }\n\n // functions\n if (typeof val === 'function' || val instanceof Function) {\n return 'function';\n }\n\n // array\n if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {\n return 'array';\n }\n\n // check for instances of RegExp and Date before calling `toString`\n if (val instanceof RegExp) {\n return 'regexp';\n }\n if (val instanceof Date) {\n return 'date';\n }\n\n // other objects\n var type = toString.call(val);\n\n if (type === '[object RegExp]') {\n return 'regexp';\n }\n if (type === '[object Date]') {\n return 'date';\n }\n if (type === '[object Arguments]') {\n return 'arguments';\n }\n if (type === '[object Error]') {\n return 'error';\n }\n\n // buffer\n if (isBuffer(val)) {\n return 'buffer';\n }\n\n // es6: Map, WeakMap, Set, WeakSet\n if (type === '[object Set]') {\n return 'set';\n }\n if (type === '[object WeakSet]') {\n return 'weakset';\n }\n if (type === '[object Map]') {\n return 'map';\n }\n if (type === '[object WeakMap]') {\n return 'weakmap';\n }\n if (type === '[object Symbol]') {\n return 'symbol';\n }\n\n // typed arrays\n if (type === '[object Int8Array]') {\n return 'int8array';\n }\n if (type === '[object Uint8Array]') {\n return 'uint8array';\n }\n if (type === '[object Uint8ClampedArray]') {\n return 'uint8clampedarray';\n }\n if (type === '[object Int16Array]') {\n return 'int16array';\n }\n if (type === '[object Uint16Array]') {\n return 'uint16array';\n }\n if (type === '[object Int32Array]') {\n return 'int32array';\n }\n if (type === '[object Uint32Array]') {\n return 'uint32array';\n }\n if (type === '[object Float32Array]') {\n return 'float32array';\n }\n if (type === '[object Float64Array]') {\n return 'float64array';\n }\n\n // must be a plain object\n return 'object';\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/snapdragon-util/node_modules/kind-of/index.js?"); + +/***/ }), + +/***/ "./node_modules/snapdragon/index.js": +/*!******************************************!*\ + !*** ./node_modules/snapdragon/index.js ***! + \******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar Base = __webpack_require__(/*! base */ \"./node_modules/base/index.js\");\nvar define = __webpack_require__(/*! define-property */ \"./node_modules/define-property/index.js\");\nvar Compiler = __webpack_require__(/*! ./lib/compiler */ \"./node_modules/snapdragon/lib/compiler.js\");\nvar Parser = __webpack_require__(/*! ./lib/parser */ \"./node_modules/snapdragon/lib/parser.js\");\nvar utils = __webpack_require__(/*! ./lib/utils */ \"./node_modules/snapdragon/lib/utils.js\");\nvar regexCache = {};\nvar cache = {};\n\n/**\n * Create a new instance of `Snapdragon` with the given `options`.\n *\n * ```js\n * var snapdragon = new Snapdragon();\n * ```\n *\n * @param {Object} `options`\n * @api public\n */\n\nfunction Snapdragon(options) {\n Base.call(this, null, options);\n this.options = utils.extend({source: 'string'}, this.options);\n this.compiler = new Compiler(this.options);\n this.parser = new Parser(this.options);\n\n Object.defineProperty(this, 'compilers', {\n get: function() {\n return this.compiler.compilers;\n }\n });\n\n Object.defineProperty(this, 'parsers', {\n get: function() {\n return this.parser.parsers;\n }\n });\n\n Object.defineProperty(this, 'regex', {\n get: function() {\n return this.parser.regex;\n }\n });\n}\n\n/**\n * Inherit Base\n */\n\nBase.extend(Snapdragon);\n\n/**\n * Add a parser to `snapdragon.parsers` for capturing the given `type` using\n * the specified regex or parser function. A function is useful if you need\n * to customize how the token is created and/or have access to the parser\n * instance to check options, etc.\n *\n * ```js\n * snapdragon\n * .capture('slash', /^\\//)\n * .capture('dot', function() {\n * var pos = this.position();\n * var m = this.match(/^\\./);\n * if (!m) return;\n * return pos({\n * type: 'dot',\n * val: m[0]\n * });\n * });\n * ```\n * @param {String} `type`\n * @param {RegExp|Function} `regex`\n * @return {Object} Returns the parser instance for chaining\n * @api public\n */\n\nSnapdragon.prototype.capture = function() {\n return this.parser.capture.apply(this.parser, arguments);\n};\n\n/**\n * Register a plugin `fn`.\n *\n * ```js\n * var snapdragon = new Snapdgragon([options]);\n * snapdragon.use(function() {\n * console.log(this); //<= snapdragon instance\n * console.log(this.parser); //<= parser instance\n * console.log(this.compiler); //<= compiler instance\n * });\n * ```\n * @param {Object} `fn`\n * @api public\n */\n\nSnapdragon.prototype.use = function(fn) {\n fn.call(this, this);\n return this;\n};\n\n/**\n * Parse the given `str`.\n *\n * ```js\n * var snapdragon = new Snapdgragon([options]);\n * // register parsers\n * snapdragon.parser.use(function() {});\n *\n * // parse\n * var ast = snapdragon.parse('foo/bar');\n * console.log(ast);\n * ```\n * @param {String} `str`\n * @param {Object} `options` Set `options.sourcemap` to true to enable source maps.\n * @return {Object} Returns an AST.\n * @api public\n */\n\nSnapdragon.prototype.parse = function(str, options) {\n this.options = utils.extend({}, this.options, options);\n var parsed = this.parser.parse(str, this.options);\n\n // add non-enumerable parser reference\n define(parsed, 'parser', this.parser);\n return parsed;\n};\n\n/**\n * Compile the given `AST`.\n *\n * ```js\n * var snapdragon = new Snapdgragon([options]);\n * // register plugins\n * snapdragon.use(function() {});\n * // register parser plugins\n * snapdragon.parser.use(function() {});\n * // register compiler plugins\n * snapdragon.compiler.use(function() {});\n *\n * // parse\n * var ast = snapdragon.parse('foo/bar');\n *\n * // compile\n * var res = snapdragon.compile(ast);\n * console.log(res.output);\n * ```\n * @param {Object} `ast`\n * @param {Object} `options`\n * @return {Object} Returns an object with an `output` property with the rendered string.\n * @api public\n */\n\nSnapdragon.prototype.compile = function(ast, options) {\n this.options = utils.extend({}, this.options, options);\n var compiled = this.compiler.compile(ast, this.options);\n\n // add non-enumerable compiler reference\n define(compiled, 'compiler', this.compiler);\n return compiled;\n};\n\n/**\n * Expose `Snapdragon`\n */\n\nmodule.exports = Snapdragon;\n\n/**\n * Expose `Parser` and `Compiler`\n */\n\nmodule.exports.Compiler = Compiler;\nmodule.exports.Parser = Parser;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/snapdragon/index.js?"); + +/***/ }), + +/***/ "./node_modules/snapdragon/lib/compiler.js": +/*!*************************************************!*\ + !*** ./node_modules/snapdragon/lib/compiler.js ***! + \*************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar use = __webpack_require__(/*! use */ \"./node_modules/use/index.js\");\nvar define = __webpack_require__(/*! define-property */ \"./node_modules/define-property/index.js\");\nvar debug = __webpack_require__(/*! debug */ \"./node_modules/debug/src/index.js\")('snapdragon:compiler');\nvar utils = __webpack_require__(/*! ./utils */ \"./node_modules/snapdragon/lib/utils.js\");\n\n/**\n * Create a new `Compiler` with the given `options`.\n * @param {Object} `options`\n */\n\nfunction Compiler(options, state) {\n debug('initializing', __filename);\n this.options = utils.extend({source: 'string'}, options);\n this.state = state || {};\n this.compilers = {};\n this.output = '';\n this.set('eos', function(node) {\n return this.emit(node.val, node);\n });\n this.set('noop', function(node) {\n return this.emit(node.val, node);\n });\n this.set('bos', function(node) {\n return this.emit(node.val, node);\n });\n use(this);\n}\n\n/**\n * Prototype methods\n */\n\nCompiler.prototype = {\n\n /**\n * Throw an error message with details including the cursor position.\n * @param {String} `msg` Message to use in the Error.\n */\n\n error: function(msg, node) {\n var pos = node.position || {start: {column: 0}};\n var message = this.options.source + ' column:' + pos.start.column + ': ' + msg;\n\n var err = new Error(message);\n err.reason = msg;\n err.column = pos.start.column;\n err.source = this.pattern;\n\n if (this.options.silent) {\n this.errors.push(err);\n } else {\n throw err;\n }\n },\n\n /**\n * Define a non-enumberable property on the `Compiler` instance.\n *\n * ```js\n * compiler.define('foo', 'bar');\n * ```\n * @name .define\n * @param {String} `key` propery name\n * @param {any} `val` property value\n * @return {Object} Returns the Compiler instance for chaining.\n * @api public\n */\n\n define: function(key, val) {\n define(this, key, val);\n return this;\n },\n\n /**\n * Emit `node.val`\n */\n\n emit: function(str, node) {\n this.output += str;\n return str;\n },\n\n /**\n * Add a compiler `fn` with the given `name`\n */\n\n set: function(name, fn) {\n this.compilers[name] = fn;\n return this;\n },\n\n /**\n * Get compiler `name`.\n */\n\n get: function(name) {\n return this.compilers[name];\n },\n\n /**\n * Get the previous AST node.\n */\n\n prev: function(n) {\n return this.ast.nodes[this.idx - (n || 1)] || { type: 'bos', val: '' };\n },\n\n /**\n * Get the next AST node.\n */\n\n next: function(n) {\n return this.ast.nodes[this.idx + (n || 1)] || { type: 'eos', val: '' };\n },\n\n /**\n * Visit `node`.\n */\n\n visit: function(node, nodes, i) {\n var fn = this.compilers[node.type];\n this.idx = i;\n\n if (typeof fn !== 'function') {\n throw this.error('compiler \"' + node.type + '\" is not registered', node);\n }\n return fn.call(this, node, nodes, i);\n },\n\n /**\n * Map visit over array of `nodes`.\n */\n\n mapVisit: function(nodes) {\n if (!Array.isArray(nodes)) {\n throw new TypeError('expected an array');\n }\n var len = nodes.length;\n var idx = -1;\n while (++idx < len) {\n this.visit(nodes[idx], nodes, idx);\n }\n return this;\n },\n\n /**\n * Compile `ast`.\n */\n\n compile: function(ast, options) {\n var opts = utils.extend({}, this.options, options);\n this.ast = ast;\n this.parsingErrors = this.ast.errors;\n this.output = '';\n\n // source map support\n if (opts.sourcemap) {\n var sourcemaps = __webpack_require__(/*! ./source-maps */ \"./node_modules/snapdragon/lib/source-maps.js\");\n sourcemaps(this);\n this.mapVisit(this.ast.nodes);\n this.applySourceMaps();\n this.map = opts.sourcemap === 'generator' ? this.map : this.map.toJSON();\n return this;\n }\n\n this.mapVisit(this.ast.nodes);\n return this;\n }\n};\n\n/**\n * Expose `Compiler`\n */\n\nmodule.exports = Compiler;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/snapdragon/lib/compiler.js?"); + +/***/ }), + +/***/ "./node_modules/snapdragon/lib/parser.js": +/*!***********************************************!*\ + !*** ./node_modules/snapdragon/lib/parser.js ***! + \***********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar use = __webpack_require__(/*! use */ \"./node_modules/use/index.js\");\nvar util = __webpack_require__(/*! util */ \"util\");\nvar Cache = __webpack_require__(/*! map-cache */ \"./node_modules/map-cache/index.js\");\nvar define = __webpack_require__(/*! define-property */ \"./node_modules/define-property/index.js\");\nvar debug = __webpack_require__(/*! debug */ \"./node_modules/debug/src/index.js\")('snapdragon:parser');\nvar Position = __webpack_require__(/*! ./position */ \"./node_modules/snapdragon/lib/position.js\");\nvar utils = __webpack_require__(/*! ./utils */ \"./node_modules/snapdragon/lib/utils.js\");\n\n/**\n * Create a new `Parser` with the given `input` and `options`.\n * @param {String} `input`\n * @param {Object} `options`\n * @api public\n */\n\nfunction Parser(options) {\n debug('initializing', __filename);\n this.options = utils.extend({source: 'string'}, options);\n this.init(this.options);\n use(this);\n}\n\n/**\n * Prototype methods\n */\n\nParser.prototype = {\n constructor: Parser,\n\n init: function(options) {\n this.orig = '';\n this.input = '';\n this.parsed = '';\n\n this.column = 1;\n this.line = 1;\n\n this.regex = new Cache();\n this.errors = this.errors || [];\n this.parsers = this.parsers || {};\n this.types = this.types || [];\n this.sets = this.sets || {};\n this.fns = this.fns || [];\n this.currentType = 'root';\n\n var pos = this.position();\n this.bos = pos({type: 'bos', val: ''});\n\n this.ast = {\n type: 'root',\n errors: this.errors,\n nodes: [this.bos]\n };\n\n define(this.bos, 'parent', this.ast);\n this.nodes = [this.ast];\n\n this.count = 0;\n this.setCount = 0;\n this.stack = [];\n },\n\n /**\n * Throw a formatted error with the cursor column and `msg`.\n * @param {String} `msg` Message to use in the Error.\n */\n\n error: function(msg, node) {\n var pos = node.position || {start: {column: 0, line: 0}};\n var line = pos.start.line;\n var column = pos.start.column;\n var source = this.options.source;\n\n var message = source + ' : ' + msg;\n var err = new Error(message);\n err.source = source;\n err.reason = msg;\n err.pos = pos;\n\n if (this.options.silent) {\n this.errors.push(err);\n } else {\n throw err;\n }\n },\n\n /**\n * Define a non-enumberable property on the `Parser` instance.\n *\n * ```js\n * parser.define('foo', 'bar');\n * ```\n * @name .define\n * @param {String} `key` propery name\n * @param {any} `val` property value\n * @return {Object} Returns the Parser instance for chaining.\n * @api public\n */\n\n define: function(key, val) {\n define(this, key, val);\n return this;\n },\n\n /**\n * Mark position and patch `node.position`.\n */\n\n position: function() {\n var start = { line: this.line, column: this.column };\n var self = this;\n\n return function(node) {\n define(node, 'position', new Position(start, self));\n return node;\n };\n },\n\n /**\n * Set parser `name` with the given `fn`\n * @param {String} `name`\n * @param {Function} `fn`\n * @api public\n */\n\n set: function(type, fn) {\n if (this.types.indexOf(type) === -1) {\n this.types.push(type);\n }\n this.parsers[type] = fn.bind(this);\n return this;\n },\n\n /**\n * Get parser `name`\n * @param {String} `name`\n * @api public\n */\n\n get: function(name) {\n return this.parsers[name];\n },\n\n /**\n * Push a `token` onto the `type` stack.\n *\n * @param {String} `type`\n * @return {Object} `token`\n * @api public\n */\n\n push: function(type, token) {\n this.sets[type] = this.sets[type] || [];\n this.count++;\n this.stack.push(token);\n return this.sets[type].push(token);\n },\n\n /**\n * Pop a token off of the `type` stack\n * @param {String} `type`\n * @returns {Object} Returns a token\n * @api public\n */\n\n pop: function(type) {\n this.sets[type] = this.sets[type] || [];\n this.count--;\n this.stack.pop();\n return this.sets[type].pop();\n },\n\n /**\n * Return true if inside a `stack` node. Types are `braces`, `parens` or `brackets`.\n *\n * @param {String} `type`\n * @return {Boolean}\n * @api public\n */\n\n isInside: function(type) {\n this.sets[type] = this.sets[type] || [];\n return this.sets[type].length > 0;\n },\n\n /**\n * Return true if `node` is the given `type`.\n *\n * ```js\n * parser.isType(node, 'brace');\n * ```\n * @param {Object} `node`\n * @param {String} `type`\n * @return {Boolean}\n * @api public\n */\n\n isType: function(node, type) {\n return node && node.type === type;\n },\n\n /**\n * Get the previous AST node\n * @return {Object}\n */\n\n prev: function(n) {\n return this.stack.length > 0\n ? utils.last(this.stack, n)\n : utils.last(this.nodes, n);\n },\n\n /**\n * Update line and column based on `str`.\n */\n\n consume: function(len) {\n this.input = this.input.substr(len);\n },\n\n /**\n * Update column based on `str`.\n */\n\n updatePosition: function(str, len) {\n var lines = str.match(/\\n/g);\n if (lines) this.line += lines.length;\n var i = str.lastIndexOf('\\n');\n this.column = ~i ? len - i : this.column + len;\n this.parsed += str;\n this.consume(len);\n },\n\n /**\n * Match `regex`, return captures, and update the cursor position by `match[0]` length.\n * @param {RegExp} `regex`\n * @return {Object}\n */\n\n match: function(regex) {\n var m = regex.exec(this.input);\n if (m) {\n this.updatePosition(m[0], m[0].length);\n return m;\n }\n },\n\n /**\n * Capture `type` with the given regex.\n * @param {String} `type`\n * @param {RegExp} `regex`\n * @return {Function}\n */\n\n capture: function(type, regex) {\n if (typeof regex === 'function') {\n return this.set.apply(this, arguments);\n }\n\n this.regex.set(type, regex);\n this.set(type, function() {\n var parsed = this.parsed;\n var pos = this.position();\n var m = this.match(regex);\n if (!m || !m[0]) return;\n\n var prev = this.prev();\n var node = pos({\n type: type,\n val: m[0],\n parsed: parsed,\n rest: this.input\n });\n\n if (m[1]) {\n node.inner = m[1];\n }\n\n define(node, 'inside', this.stack.length > 0);\n define(node, 'parent', prev);\n prev.nodes.push(node);\n }.bind(this));\n return this;\n },\n\n /**\n * Create a parser with open and close for parens,\n * brackets or braces\n */\n\n capturePair: function(type, openRegex, closeRegex, fn) {\n this.sets[type] = this.sets[type] || [];\n\n /**\n * Open\n */\n\n this.set(type + '.open', function() {\n var parsed = this.parsed;\n var pos = this.position();\n var m = this.match(openRegex);\n if (!m || !m[0]) return;\n\n var val = m[0];\n this.setCount++;\n this.specialChars = true;\n var open = pos({\n type: type + '.open',\n val: val,\n rest: this.input\n });\n\n if (typeof m[1] !== 'undefined') {\n open.inner = m[1];\n }\n\n var prev = this.prev();\n var node = pos({\n type: type,\n nodes: [open]\n });\n\n define(node, 'rest', this.input);\n define(node, 'parsed', parsed);\n define(node, 'prefix', m[1]);\n define(node, 'parent', prev);\n define(open, 'parent', node);\n\n if (typeof fn === 'function') {\n fn.call(this, open, node);\n }\n\n this.push(type, node);\n prev.nodes.push(node);\n });\n\n /**\n * Close\n */\n\n this.set(type + '.close', function() {\n var pos = this.position();\n var m = this.match(closeRegex);\n if (!m || !m[0]) return;\n\n var parent = this.pop(type);\n var node = pos({\n type: type + '.close',\n rest: this.input,\n suffix: m[1],\n val: m[0]\n });\n\n if (!this.isType(parent, type)) {\n if (this.options.strict) {\n throw new Error('missing opening \"' + type + '\"');\n }\n\n this.setCount--;\n node.escaped = true;\n return node;\n }\n\n if (node.suffix === '\\\\') {\n parent.escaped = true;\n node.escaped = true;\n }\n\n parent.nodes.push(node);\n define(node, 'parent', parent);\n });\n\n return this;\n },\n\n /**\n * Capture end-of-string\n */\n\n eos: function() {\n var pos = this.position();\n if (this.input) return;\n var prev = this.prev();\n\n while (prev.type !== 'root' && !prev.visited) {\n if (this.options.strict === true) {\n throw new SyntaxError('invalid syntax:' + util.inspect(prev, null, 2));\n }\n\n if (!hasDelims(prev)) {\n prev.parent.escaped = true;\n prev.escaped = true;\n }\n\n visit(prev, function(node) {\n if (!hasDelims(node.parent)) {\n node.parent.escaped = true;\n node.escaped = true;\n }\n });\n\n prev = prev.parent;\n }\n\n var tok = pos({\n type: 'eos',\n val: this.append || ''\n });\n\n define(tok, 'parent', this.ast);\n return tok;\n },\n\n /**\n * Run parsers to advance the cursor position\n */\n\n next: function() {\n var parsed = this.parsed;\n var len = this.types.length;\n var idx = -1;\n var tok;\n\n while (++idx < len) {\n if ((tok = this.parsers[this.types[idx]].call(this))) {\n define(tok, 'rest', this.input);\n define(tok, 'parsed', parsed);\n this.last = tok;\n return tok;\n }\n }\n },\n\n /**\n * Parse the given string.\n * @return {Array}\n */\n\n parse: function(input) {\n if (typeof input !== 'string') {\n throw new TypeError('expected a string');\n }\n\n this.init(this.options);\n this.orig = input;\n this.input = input;\n var self = this;\n\n function parse() {\n // check input before calling `.next()`\n input = self.input;\n\n // get the next AST ndoe\n var node = self.next();\n if (node) {\n var prev = self.prev();\n if (prev) {\n define(node, 'parent', prev);\n if (prev.nodes) {\n prev.nodes.push(node);\n }\n }\n\n if (self.sets.hasOwnProperty(prev.type)) {\n self.currentType = prev.type;\n }\n }\n\n // if we got here but input is not changed, throw an error\n if (self.input && input === self.input) {\n throw new Error('no parsers registered for: \"' + self.input.slice(0, 5) + '\"');\n }\n }\n\n while (this.input) parse();\n if (this.stack.length && this.options.strict) {\n var node = this.stack.pop();\n throw this.error('missing opening ' + node.type + ': \"' + this.orig + '\"');\n }\n\n var eos = this.eos();\n var tok = this.prev();\n if (tok.type !== 'eos') {\n this.ast.nodes.push(eos);\n }\n\n return this.ast;\n }\n};\n\n/**\n * Visit `node` with the given `fn`\n */\n\nfunction visit(node, fn) {\n if (!node.visited) {\n define(node, 'visited', true);\n return node.nodes ? mapVisit(node.nodes, fn) : fn(node);\n }\n return node;\n}\n\n/**\n * Map visit over array of `nodes`.\n */\n\nfunction mapVisit(nodes, fn) {\n var len = nodes.length;\n var idx = -1;\n while (++idx < len) {\n visit(nodes[idx], fn);\n }\n}\n\nfunction hasOpen(node) {\n return node.nodes && node.nodes[0].type === (node.type + '.open');\n}\n\nfunction hasClose(node) {\n return node.nodes && utils.last(node.nodes).type === (node.type + '.close');\n}\n\nfunction hasDelims(node) {\n return hasOpen(node) && hasClose(node);\n}\n\n/**\n * Expose `Parser`\n */\n\nmodule.exports = Parser;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/snapdragon/lib/parser.js?"); + +/***/ }), + +/***/ "./node_modules/snapdragon/lib/position.js": +/*!*************************************************!*\ + !*** ./node_modules/snapdragon/lib/position.js ***! + \*************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar define = __webpack_require__(/*! define-property */ \"./node_modules/define-property/index.js\");\n\n/**\n * Store position for a node\n */\n\nmodule.exports = function Position(start, parser) {\n this.start = start;\n this.end = { line: parser.line, column: parser.column };\n define(this, 'content', parser.orig);\n define(this, 'source', parser.options.source);\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/snapdragon/lib/position.js?"); + +/***/ }), + +/***/ "./node_modules/snapdragon/lib/source-maps.js": +/*!****************************************************!*\ + !*** ./node_modules/snapdragon/lib/source-maps.js ***! + \****************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar fs = __webpack_require__(/*! fs */ \"fs\");\nvar path = __webpack_require__(/*! path */ \"path\");\nvar define = __webpack_require__(/*! define-property */ \"./node_modules/define-property/index.js\");\nvar utils = __webpack_require__(/*! ./utils */ \"./node_modules/snapdragon/lib/utils.js\");\n\n/**\n * Expose `mixin()`.\n * This code is based on `source-maps-support.js` in reworkcss/css\n * https://github.com/reworkcss/css/blob/master/lib/stringify/source-map-support.js\n * Copyright (c) 2012 TJ Holowaychuk \n */\n\nmodule.exports = mixin;\n\n/**\n * Mixin source map support into `compiler`.\n *\n * @param {Object} `compiler`\n * @api public\n */\n\nfunction mixin(compiler) {\n define(compiler, '_comment', compiler.comment);\n compiler.map = new utils.SourceMap.SourceMapGenerator();\n compiler.position = { line: 1, column: 1 };\n compiler.content = {};\n compiler.files = {};\n\n for (var key in exports) {\n define(compiler, key, exports[key]);\n }\n}\n\n/**\n * Update position.\n *\n * @param {String} str\n */\n\nexports.updatePosition = function(str) {\n var lines = str.match(/\\n/g);\n if (lines) this.position.line += lines.length;\n var i = str.lastIndexOf('\\n');\n this.position.column = ~i ? str.length - i : this.position.column + str.length;\n};\n\n/**\n * Emit `str` with `position`.\n *\n * @param {String} str\n * @param {Object} [pos]\n * @return {String}\n */\n\nexports.emit = function(str, node) {\n var position = node.position || {};\n var source = position.source;\n if (source) {\n if (position.filepath) {\n source = utils.unixify(position.filepath);\n }\n\n this.map.addMapping({\n source: source,\n generated: {\n line: this.position.line,\n column: Math.max(this.position.column - 1, 0)\n },\n original: {\n line: position.start.line,\n column: position.start.column - 1\n }\n });\n\n if (position.content) {\n this.addContent(source, position);\n }\n if (position.filepath) {\n this.addFile(source, position);\n }\n\n this.updatePosition(str);\n this.output += str;\n }\n return str;\n};\n\n/**\n * Adds a file to the source map output if it has not already been added\n * @param {String} `file`\n * @param {Object} `pos`\n */\n\nexports.addFile = function(file, position) {\n if (typeof position.content !== 'string') return;\n if (Object.prototype.hasOwnProperty.call(this.files, file)) return;\n this.files[file] = position.content;\n};\n\n/**\n * Adds a content source to the source map output if it has not already been added\n * @param {String} `source`\n * @param {Object} `position`\n */\n\nexports.addContent = function(source, position) {\n if (typeof position.content !== 'string') return;\n if (Object.prototype.hasOwnProperty.call(this.content, source)) return;\n this.map.setSourceContent(source, position.content);\n};\n\n/**\n * Applies any original source maps to the output and embeds the source file\n * contents in the source map.\n */\n\nexports.applySourceMaps = function() {\n Object.keys(this.files).forEach(function(file) {\n var content = this.files[file];\n this.map.setSourceContent(file, content);\n\n if (this.options.inputSourcemaps === true) {\n var originalMap = utils.sourceMapResolve.resolveSync(content, file, fs.readFileSync);\n if (originalMap) {\n var map = new utils.SourceMap.SourceMapConsumer(originalMap.map);\n var relativeTo = originalMap.sourcesRelativeTo;\n this.map.applySourceMap(map, file, utils.unixify(path.dirname(relativeTo)));\n }\n }\n }, this);\n};\n\n/**\n * Process comments, drops sourceMap comments.\n * @param {Object} node\n */\n\nexports.comment = function(node) {\n if (/^# sourceMappingURL=/.test(node.comment)) {\n return this.emit('', node.position);\n }\n return this._comment(node);\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/snapdragon/lib/source-maps.js?"); + +/***/ }), + +/***/ "./node_modules/snapdragon/lib/utils.js": +/*!**********************************************!*\ + !*** ./node_modules/snapdragon/lib/utils.js ***! + \**********************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +eval("\n\n/**\n * Module dependencies\n */\n\nexports.extend = __webpack_require__(/*! extend-shallow */ \"./node_modules/extend-shallow/index.js\");\nexports.SourceMap = __webpack_require__(/*! source-map */ \"./node_modules/snapdragon/node_modules/source-map/source-map.js\");\nexports.sourceMapResolve = __webpack_require__(/*! source-map-resolve */ \"./node_modules/source-map-resolve/lib/source-map-resolve-node.js\");\n\n/**\n * Convert backslash in the given string to forward slashes\n */\n\nexports.unixify = function(fp) {\n return fp.split(/\\\\+/).join('/');\n};\n\n/**\n * Return true if `val` is a non-empty string\n *\n * @param {String} `str`\n * @return {Boolean}\n */\n\nexports.isString = function(str) {\n return str && typeof str === 'string';\n};\n\n/**\n * Cast `val` to an array\n * @return {Array}\n */\n\nexports.arrayify = function(val) {\n if (typeof val === 'string') return [val];\n return val ? (Array.isArray(val) ? val : [val]) : [];\n};\n\n/**\n * Get the last `n` element from the given `array`\n * @param {Array} `array`\n * @return {*}\n */\n\nexports.last = function(arr, n) {\n return arr[arr.length - (n || 1)];\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/snapdragon/lib/utils.js?"); + +/***/ }), + +/***/ "./node_modules/snapdragon/node_modules/source-map/lib/array-set.js": +/*!**************************************************************************!*\ + !*** ./node_modules/snapdragon/node_modules/source-map/lib/array-set.js ***! + \**************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = __webpack_require__(/*! ./util */ \"./node_modules/snapdragon/node_modules/source-map/lib/util.js\");\nvar has = Object.prototype.hasOwnProperty;\nvar hasNativeMap = typeof Map !== \"undefined\";\n\n/**\n * A data structure which is a combination of an array and a set. Adding a new\n * member is O(1), testing for membership is O(1), and finding the index of an\n * element is O(1). Removing elements from the set is not supported. Only\n * strings are supported for membership.\n */\nfunction ArraySet() {\n this._array = [];\n this._set = hasNativeMap ? new Map() : Object.create(null);\n}\n\n/**\n * Static method for creating ArraySet instances from an existing array.\n */\nArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n var set = new ArraySet();\n for (var i = 0, len = aArray.length; i < len; i++) {\n set.add(aArray[i], aAllowDuplicates);\n }\n return set;\n};\n\n/**\n * Return how many unique items are in this ArraySet. If duplicates have been\n * added, than those do not count towards the size.\n *\n * @returns Number\n */\nArraySet.prototype.size = function ArraySet_size() {\n return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;\n};\n\n/**\n * Add the given string to this set.\n *\n * @param String aStr\n */\nArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n var sStr = hasNativeMap ? aStr : util.toSetString(aStr);\n var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);\n var idx = this._array.length;\n if (!isDuplicate || aAllowDuplicates) {\n this._array.push(aStr);\n }\n if (!isDuplicate) {\n if (hasNativeMap) {\n this._set.set(aStr, idx);\n } else {\n this._set[sStr] = idx;\n }\n }\n};\n\n/**\n * Is the given string a member of this set?\n *\n * @param String aStr\n */\nArraySet.prototype.has = function ArraySet_has(aStr) {\n if (hasNativeMap) {\n return this._set.has(aStr);\n } else {\n var sStr = util.toSetString(aStr);\n return has.call(this._set, sStr);\n }\n};\n\n/**\n * What is the index of the given string in the array?\n *\n * @param String aStr\n */\nArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n if (hasNativeMap) {\n var idx = this._set.get(aStr);\n if (idx >= 0) {\n return idx;\n }\n } else {\n var sStr = util.toSetString(aStr);\n if (has.call(this._set, sStr)) {\n return this._set[sStr];\n }\n }\n\n throw new Error('\"' + aStr + '\" is not in the set.');\n};\n\n/**\n * What is the element at the given index?\n *\n * @param Number aIdx\n */\nArraySet.prototype.at = function ArraySet_at(aIdx) {\n if (aIdx >= 0 && aIdx < this._array.length) {\n return this._array[aIdx];\n }\n throw new Error('No element indexed by ' + aIdx);\n};\n\n/**\n * Returns the array representation of this set (which has the proper indices\n * indicated by indexOf). Note that this is a copy of the internal array used\n * for storing the members so that no one can mess with internal state.\n */\nArraySet.prototype.toArray = function ArraySet_toArray() {\n return this._array.slice();\n};\n\nexports.ArraySet = ArraySet;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/snapdragon/node_modules/source-map/lib/array-set.js?"); + +/***/ }), + +/***/ "./node_modules/snapdragon/node_modules/source-map/lib/base64-vlq.js": +/*!***************************************************************************!*\ + !*** ./node_modules/snapdragon/node_modules/source-map/lib/base64-vlq.js ***! + \***************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n *\n * Based on the Base 64 VLQ implementation in Closure Compiler:\n * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n *\n * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nvar base64 = __webpack_require__(/*! ./base64 */ \"./node_modules/snapdragon/node_modules/source-map/lib/base64.js\");\n\n// A single base 64 digit can contain 6 bits of data. For the base 64 variable\n// length quantities we use in the source map spec, the first bit is the sign,\n// the next four bits are the actual value, and the 6th bit is the\n// continuation bit. The continuation bit tells us whether there are more\n// digits in this value following this digit.\n//\n// Continuation\n// | Sign\n// | |\n// V V\n// 101011\n\nvar VLQ_BASE_SHIFT = 5;\n\n// binary: 100000\nvar VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\n// binary: 011111\nvar VLQ_BASE_MASK = VLQ_BASE - 1;\n\n// binary: 100000\nvar VLQ_CONTINUATION_BIT = VLQ_BASE;\n\n/**\n * Converts from a two-complement value to a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n */\nfunction toVLQSigned(aValue) {\n return aValue < 0\n ? ((-aValue) << 1) + 1\n : (aValue << 1) + 0;\n}\n\n/**\n * Converts to a two-complement value from a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n */\nfunction fromVLQSigned(aValue) {\n var isNegative = (aValue & 1) === 1;\n var shifted = aValue >> 1;\n return isNegative\n ? -shifted\n : shifted;\n}\n\n/**\n * Returns the base 64 VLQ encoded value.\n */\nexports.encode = function base64VLQ_encode(aValue) {\n var encoded = \"\";\n var digit;\n\n var vlq = toVLQSigned(aValue);\n\n do {\n digit = vlq & VLQ_BASE_MASK;\n vlq >>>= VLQ_BASE_SHIFT;\n if (vlq > 0) {\n // There are still more digits in this value, so we must make sure the\n // continuation bit is marked.\n digit |= VLQ_CONTINUATION_BIT;\n }\n encoded += base64.encode(digit);\n } while (vlq > 0);\n\n return encoded;\n};\n\n/**\n * Decodes the next base 64 VLQ value from the given string and returns the\n * value and the rest of the string via the out parameter.\n */\nexports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {\n var strLen = aStr.length;\n var result = 0;\n var shift = 0;\n var continuation, digit;\n\n do {\n if (aIndex >= strLen) {\n throw new Error(\"Expected more digits in base 64 VLQ value.\");\n }\n\n digit = base64.decode(aStr.charCodeAt(aIndex++));\n if (digit === -1) {\n throw new Error(\"Invalid base64 digit: \" + aStr.charAt(aIndex - 1));\n }\n\n continuation = !!(digit & VLQ_CONTINUATION_BIT);\n digit &= VLQ_BASE_MASK;\n result = result + (digit << shift);\n shift += VLQ_BASE_SHIFT;\n } while (continuation);\n\n aOutParam.value = fromVLQSigned(result);\n aOutParam.rest = aIndex;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/snapdragon/node_modules/source-map/lib/base64-vlq.js?"); + +/***/ }), + +/***/ "./node_modules/snapdragon/node_modules/source-map/lib/base64.js": +/*!***********************************************************************!*\ + !*** ./node_modules/snapdragon/node_modules/source-map/lib/base64.js ***! + \***********************************************************************/ +/***/ ((__unused_webpack_module, exports) => { + +eval("/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n\n/**\n * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n */\nexports.encode = function (number) {\n if (0 <= number && number < intToCharMap.length) {\n return intToCharMap[number];\n }\n throw new TypeError(\"Must be between 0 and 63: \" + number);\n};\n\n/**\n * Decode a single base 64 character code digit to an integer. Returns -1 on\n * failure.\n */\nexports.decode = function (charCode) {\n var bigA = 65; // 'A'\n var bigZ = 90; // 'Z'\n\n var littleA = 97; // 'a'\n var littleZ = 122; // 'z'\n\n var zero = 48; // '0'\n var nine = 57; // '9'\n\n var plus = 43; // '+'\n var slash = 47; // '/'\n\n var littleOffset = 26;\n var numberOffset = 52;\n\n // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n if (bigA <= charCode && charCode <= bigZ) {\n return (charCode - bigA);\n }\n\n // 26 - 51: abcdefghijklmnopqrstuvwxyz\n if (littleA <= charCode && charCode <= littleZ) {\n return (charCode - littleA + littleOffset);\n }\n\n // 52 - 61: 0123456789\n if (zero <= charCode && charCode <= nine) {\n return (charCode - zero + numberOffset);\n }\n\n // 62: +\n if (charCode == plus) {\n return 62;\n }\n\n // 63: /\n if (charCode == slash) {\n return 63;\n }\n\n // Invalid base64 digit.\n return -1;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/snapdragon/node_modules/source-map/lib/base64.js?"); + +/***/ }), + +/***/ "./node_modules/snapdragon/node_modules/source-map/lib/binary-search.js": +/*!******************************************************************************!*\ + !*** ./node_modules/snapdragon/node_modules/source-map/lib/binary-search.js ***! + \******************************************************************************/ +/***/ ((__unused_webpack_module, exports) => { + +eval("/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nexports.GREATEST_LOWER_BOUND = 1;\nexports.LEAST_UPPER_BOUND = 2;\n\n/**\n * Recursive implementation of binary search.\n *\n * @param aLow Indices here and lower do not contain the needle.\n * @param aHigh Indices here and higher do not contain the needle.\n * @param aNeedle The element being searched for.\n * @param aHaystack The non-empty array being searched.\n * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n */\nfunction recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {\n // This function terminates when one of the following is true:\n //\n // 1. We find the exact element we are looking for.\n //\n // 2. We did not find the exact element, but we can return the index of\n // the next-closest element.\n //\n // 3. We did not find the exact element, and there is no next-closest\n // element than the one we are searching for, so we return -1.\n var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n var cmp = aCompare(aNeedle, aHaystack[mid], true);\n if (cmp === 0) {\n // Found the element we are looking for.\n return mid;\n }\n else if (cmp > 0) {\n // Our needle is greater than aHaystack[mid].\n if (aHigh - mid > 1) {\n // The element is in the upper half.\n return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // The exact needle element was not found in this haystack. Determine if\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return aHigh < aHaystack.length ? aHigh : -1;\n } else {\n return mid;\n }\n }\n else {\n // Our needle is less than aHaystack[mid].\n if (mid - aLow > 1) {\n // The element is in the lower half.\n return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return mid;\n } else {\n return aLow < 0 ? -1 : aLow;\n }\n }\n}\n\n/**\n * This is an implementation of binary search which will always try and return\n * the index of the closest element if there is no exact hit. This is because\n * mappings between original and generated line/col pairs are single points,\n * and there is an implicit region between each of them, so a miss just means\n * that you aren't on the very start of a region.\n *\n * @param aNeedle The element you are looking for.\n * @param aHaystack The array that is being searched.\n * @param aCompare A function which takes the needle and an element in the\n * array and returns -1, 0, or 1 depending on whether the needle is less\n * than, equal to, or greater than the element, respectively.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.\n */\nexports.search = function search(aNeedle, aHaystack, aCompare, aBias) {\n if (aHaystack.length === 0) {\n return -1;\n }\n\n var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,\n aCompare, aBias || exports.GREATEST_LOWER_BOUND);\n if (index < 0) {\n return -1;\n }\n\n // We have found either the exact element, or the next-closest element than\n // the one we are searching for. However, there may be more than one such\n // element. Make sure we always return the smallest of these.\n while (index - 1 >= 0) {\n if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {\n break;\n }\n --index;\n }\n\n return index;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/snapdragon/node_modules/source-map/lib/binary-search.js?"); + +/***/ }), + +/***/ "./node_modules/snapdragon/node_modules/source-map/lib/mapping-list.js": +/*!*****************************************************************************!*\ + !*** ./node_modules/snapdragon/node_modules/source-map/lib/mapping-list.js ***! + \*****************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2014 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = __webpack_require__(/*! ./util */ \"./node_modules/snapdragon/node_modules/source-map/lib/util.js\");\n\n/**\n * Determine whether mappingB is after mappingA with respect to generated\n * position.\n */\nfunction generatedPositionAfter(mappingA, mappingB) {\n // Optimized for most common case\n var lineA = mappingA.generatedLine;\n var lineB = mappingB.generatedLine;\n var columnA = mappingA.generatedColumn;\n var columnB = mappingB.generatedColumn;\n return lineB > lineA || lineB == lineA && columnB >= columnA ||\n util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;\n}\n\n/**\n * A data structure to provide a sorted view of accumulated mappings in a\n * performance conscious manner. It trades a neglibable overhead in general\n * case for a large speedup in case of mappings being added in order.\n */\nfunction MappingList() {\n this._array = [];\n this._sorted = true;\n // Serves as infimum\n this._last = {generatedLine: -1, generatedColumn: 0};\n}\n\n/**\n * Iterate through internal items. This method takes the same arguments that\n * `Array.prototype.forEach` takes.\n *\n * NOTE: The order of the mappings is NOT guaranteed.\n */\nMappingList.prototype.unsortedForEach =\n function MappingList_forEach(aCallback, aThisArg) {\n this._array.forEach(aCallback, aThisArg);\n };\n\n/**\n * Add the given source mapping.\n *\n * @param Object aMapping\n */\nMappingList.prototype.add = function MappingList_add(aMapping) {\n if (generatedPositionAfter(this._last, aMapping)) {\n this._last = aMapping;\n this._array.push(aMapping);\n } else {\n this._sorted = false;\n this._array.push(aMapping);\n }\n};\n\n/**\n * Returns the flat, sorted array of mappings. The mappings are sorted by\n * generated position.\n *\n * WARNING: This method returns internal data without copying, for\n * performance. The return value must NOT be mutated, and should be treated as\n * an immutable borrow. If you want to take ownership, you must make your own\n * copy.\n */\nMappingList.prototype.toArray = function MappingList_toArray() {\n if (!this._sorted) {\n this._array.sort(util.compareByGeneratedPositionsInflated);\n this._sorted = true;\n }\n return this._array;\n};\n\nexports.MappingList = MappingList;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/snapdragon/node_modules/source-map/lib/mapping-list.js?"); + +/***/ }), + +/***/ "./node_modules/snapdragon/node_modules/source-map/lib/quick-sort.js": +/*!***************************************************************************!*\ + !*** ./node_modules/snapdragon/node_modules/source-map/lib/quick-sort.js ***! + \***************************************************************************/ +/***/ ((__unused_webpack_module, exports) => { + +eval("/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n// It turns out that some (most?) JavaScript engines don't self-host\n// `Array.prototype.sort`. This makes sense because C++ will likely remain\n// faster than JS when doing raw CPU-intensive sorting. However, when using a\n// custom comparator function, calling back and forth between the VM's C++ and\n// JIT'd JS is rather slow *and* loses JIT type information, resulting in\n// worse generated code for the comparator function than would be optimal. In\n// fact, when sorting with a comparator, these costs outweigh the benefits of\n// sorting in C++. By using our own JS-implemented Quick Sort (below), we get\n// a ~3500ms mean speed-up in `bench/bench.html`.\n\n/**\n * Swap the elements indexed by `x` and `y` in the array `ary`.\n *\n * @param {Array} ary\n * The array.\n * @param {Number} x\n * The index of the first item.\n * @param {Number} y\n * The index of the second item.\n */\nfunction swap(ary, x, y) {\n var temp = ary[x];\n ary[x] = ary[y];\n ary[y] = temp;\n}\n\n/**\n * Returns a random integer within the range `low .. high` inclusive.\n *\n * @param {Number} low\n * The lower bound on the range.\n * @param {Number} high\n * The upper bound on the range.\n */\nfunction randomIntInRange(low, high) {\n return Math.round(low + (Math.random() * (high - low)));\n}\n\n/**\n * The Quick Sort algorithm.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n * @param {Number} p\n * Start index of the array\n * @param {Number} r\n * End index of the array\n */\nfunction doQuickSort(ary, comparator, p, r) {\n // If our lower bound is less than our upper bound, we (1) partition the\n // array into two pieces and (2) recurse on each half. If it is not, this is\n // the empty array and our base case.\n\n if (p < r) {\n // (1) Partitioning.\n //\n // The partitioning chooses a pivot between `p` and `r` and moves all\n // elements that are less than or equal to the pivot to the before it, and\n // all the elements that are greater than it after it. The effect is that\n // once partition is done, the pivot is in the exact place it will be when\n // the array is put in sorted order, and it will not need to be moved\n // again. This runs in O(n) time.\n\n // Always choose a random pivot so that an input array which is reverse\n // sorted does not cause O(n^2) running time.\n var pivotIndex = randomIntInRange(p, r);\n var i = p - 1;\n\n swap(ary, pivotIndex, r);\n var pivot = ary[r];\n\n // Immediately after `j` is incremented in this loop, the following hold\n // true:\n //\n // * Every element in `ary[p .. i]` is less than or equal to the pivot.\n //\n // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.\n for (var j = p; j < r; j++) {\n if (comparator(ary[j], pivot) <= 0) {\n i += 1;\n swap(ary, i, j);\n }\n }\n\n swap(ary, i + 1, j);\n var q = i + 1;\n\n // (2) Recurse on each half.\n\n doQuickSort(ary, comparator, p, q - 1);\n doQuickSort(ary, comparator, q + 1, r);\n }\n}\n\n/**\n * Sort the given array in-place with the given comparator function.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n */\nexports.quickSort = function (ary, comparator) {\n doQuickSort(ary, comparator, 0, ary.length - 1);\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/snapdragon/node_modules/source-map/lib/quick-sort.js?"); + +/***/ }), + +/***/ "./node_modules/snapdragon/node_modules/source-map/lib/source-map-consumer.js": +/*!************************************************************************************!*\ + !*** ./node_modules/snapdragon/node_modules/source-map/lib/source-map-consumer.js ***! + \************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = __webpack_require__(/*! ./util */ \"./node_modules/snapdragon/node_modules/source-map/lib/util.js\");\nvar binarySearch = __webpack_require__(/*! ./binary-search */ \"./node_modules/snapdragon/node_modules/source-map/lib/binary-search.js\");\nvar ArraySet = __webpack_require__(/*! ./array-set */ \"./node_modules/snapdragon/node_modules/source-map/lib/array-set.js\").ArraySet;\nvar base64VLQ = __webpack_require__(/*! ./base64-vlq */ \"./node_modules/snapdragon/node_modules/source-map/lib/base64-vlq.js\");\nvar quickSort = __webpack_require__(/*! ./quick-sort */ \"./node_modules/snapdragon/node_modules/source-map/lib/quick-sort.js\").quickSort;\n\nfunction SourceMapConsumer(aSourceMap) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = JSON.parse(aSourceMap.replace(/^\\)\\]\\}'/, ''));\n }\n\n return sourceMap.sections != null\n ? new IndexedSourceMapConsumer(sourceMap)\n : new BasicSourceMapConsumer(sourceMap);\n}\n\nSourceMapConsumer.fromSourceMap = function(aSourceMap) {\n return BasicSourceMapConsumer.fromSourceMap(aSourceMap);\n}\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nSourceMapConsumer.prototype._version = 3;\n\n// `__generatedMappings` and `__originalMappings` are arrays that hold the\n// parsed mapping coordinates from the source map's \"mappings\" attribute. They\n// are lazily instantiated, accessed via the `_generatedMappings` and\n// `_originalMappings` getters respectively, and we only parse the mappings\n// and create these arrays once queried for a source location. We jump through\n// these hoops because there can be many thousands of mappings, and parsing\n// them is expensive, so we only want to do it if we must.\n//\n// Each object in the arrays is of the form:\n//\n// {\n// generatedLine: The line number in the generated code,\n// generatedColumn: The column number in the generated code,\n// source: The path to the original source file that generated this\n// chunk of code,\n// originalLine: The line number in the original source that\n// corresponds to this chunk of generated code,\n// originalColumn: The column number in the original source that\n// corresponds to this chunk of generated code,\n// name: The name of the original symbol which generated this chunk of\n// code.\n// }\n//\n// All properties except for `generatedLine` and `generatedColumn` can be\n// `null`.\n//\n// `_generatedMappings` is ordered by the generated positions.\n//\n// `_originalMappings` is ordered by the original positions.\n\nSourceMapConsumer.prototype.__generatedMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n get: function () {\n if (!this.__generatedMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__generatedMappings;\n }\n});\n\nSourceMapConsumer.prototype.__originalMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n get: function () {\n if (!this.__originalMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__originalMappings;\n }\n});\n\nSourceMapConsumer.prototype._charIsMappingSeparator =\n function SourceMapConsumer_charIsMappingSeparator(aStr, index) {\n var c = aStr.charAt(index);\n return c === \";\" || c === \",\";\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n throw new Error(\"Subclasses must implement _parseMappings\");\n };\n\nSourceMapConsumer.GENERATED_ORDER = 1;\nSourceMapConsumer.ORIGINAL_ORDER = 2;\n\nSourceMapConsumer.GREATEST_LOWER_BOUND = 1;\nSourceMapConsumer.LEAST_UPPER_BOUND = 2;\n\n/**\n * Iterate over each mapping between an original source/line/column and a\n * generated line/column in this source map.\n *\n * @param Function aCallback\n * The function that is called with each mapping.\n * @param Object aContext\n * Optional. If specified, this object will be the value of `this` every\n * time that `aCallback` is called.\n * @param aOrder\n * Either `SourceMapConsumer.GENERATED_ORDER` or\n * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n * iterate over the mappings sorted by the generated file's line/column\n * order or the original's source/line/column order, respectively. Defaults to\n * `SourceMapConsumer.GENERATED_ORDER`.\n */\nSourceMapConsumer.prototype.eachMapping =\n function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n var context = aContext || null;\n var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\n var mappings;\n switch (order) {\n case SourceMapConsumer.GENERATED_ORDER:\n mappings = this._generatedMappings;\n break;\n case SourceMapConsumer.ORIGINAL_ORDER:\n mappings = this._originalMappings;\n break;\n default:\n throw new Error(\"Unknown order of iteration.\");\n }\n\n var sourceRoot = this.sourceRoot;\n mappings.map(function (mapping) {\n var source = mapping.source === null ? null : this._sources.at(mapping.source);\n if (source != null && sourceRoot != null) {\n source = util.join(sourceRoot, source);\n }\n return {\n source: source,\n generatedLine: mapping.generatedLine,\n generatedColumn: mapping.generatedColumn,\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: mapping.name === null ? null : this._names.at(mapping.name)\n };\n }, this).forEach(aCallback, context);\n };\n\n/**\n * Returns all generated line and column information for the original source,\n * line, and column provided. If no column is provided, returns all mappings\n * corresponding to a either the line we are searching for or the next\n * closest line that has any mappings. Otherwise, returns all mappings\n * corresponding to the given line and either the column we are searching for\n * or the next closest column that has any offsets.\n *\n * The only argument is an object with the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source.\n * - column: Optional. the column number in the original source.\n *\n * and an array of objects is returned, each with the following properties:\n *\n * - line: The line number in the generated source, or null.\n * - column: The column number in the generated source, or null.\n */\nSourceMapConsumer.prototype.allGeneratedPositionsFor =\n function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {\n var line = util.getArg(aArgs, 'line');\n\n // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping\n // returns the index of the closest mapping less than the needle. By\n // setting needle.originalColumn to 0, we thus find the last mapping for\n // the given line, provided such a mapping exists.\n var needle = {\n source: util.getArg(aArgs, 'source'),\n originalLine: line,\n originalColumn: util.getArg(aArgs, 'column', 0)\n };\n\n if (this.sourceRoot != null) {\n needle.source = util.relative(this.sourceRoot, needle.source);\n }\n if (!this._sources.has(needle.source)) {\n return [];\n }\n needle.source = this._sources.indexOf(needle.source);\n\n var mappings = [];\n\n var index = this._findMapping(needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n binarySearch.LEAST_UPPER_BOUND);\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (aArgs.column === undefined) {\n var originalLine = mapping.originalLine;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we found. Since\n // mappings are sorted, this is guaranteed to find all mappings for\n // the line we found.\n while (mapping && mapping.originalLine === originalLine) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n } else {\n var originalColumn = mapping.originalColumn;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we were searching for.\n // Since mappings are sorted, this is guaranteed to find all mappings for\n // the line we are searching for.\n while (mapping &&\n mapping.originalLine === line &&\n mapping.originalColumn == originalColumn) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n }\n }\n\n return mappings;\n };\n\nexports.SourceMapConsumer = SourceMapConsumer;\n\n/**\n * A BasicSourceMapConsumer instance represents a parsed source map which we can\n * query for information about the original file positions by giving it a file\n * position in the generated source.\n *\n * The only parameter is the raw source map (either as a JSON string, or\n * already parsed to an object). According to the spec, source maps have the\n * following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - sources: An array of URLs to the original source files.\n * - names: An array of identifiers which can be referrenced by individual mappings.\n * - sourceRoot: Optional. The URL root from which all sources are relative.\n * - sourcesContent: Optional. An array of contents of the original source files.\n * - mappings: A string of base64 VLQs which contain the actual mappings.\n * - file: Optional. The generated file this source map is associated with.\n *\n * Here is an example source map, taken from the source map spec[0]:\n *\n * {\n * version : 3,\n * file: \"out.js\",\n * sourceRoot : \"\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AA,AB;;ABCDE;\"\n * }\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n */\nfunction BasicSourceMapConsumer(aSourceMap) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = JSON.parse(aSourceMap.replace(/^\\)\\]\\}'/, ''));\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sources = util.getArg(sourceMap, 'sources');\n // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n // requires the array) to play nice here.\n var names = util.getArg(sourceMap, 'names', []);\n var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n var mappings = util.getArg(sourceMap, 'mappings');\n var file = util.getArg(sourceMap, 'file', null);\n\n // Once again, Sass deviates from the spec and supplies the version as a\n // string rather than a number, so we use loose equality checking here.\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n sources = sources\n .map(String)\n // Some source maps produce relative source paths like \"./foo.js\" instead of\n // \"foo.js\". Normalize these first so that future comparisons will succeed.\n // See bugzil.la/1090768.\n .map(util.normalize)\n // Always ensure that absolute sources are internally stored relative to\n // the source root, if the source root is absolute. Not doing this would\n // be particularly problematic when the source root is a prefix of the\n // source (valid, but why??). See github issue #199 and bugzil.la/1188982.\n .map(function (source) {\n return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)\n ? util.relative(sourceRoot, source)\n : source;\n });\n\n // Pass `true` below to allow duplicate names and sources. While source maps\n // are intended to be compressed and deduplicated, the TypeScript compiler\n // sometimes generates source maps with duplicates in them. See Github issue\n // #72 and bugzil.la/889492.\n this._names = ArraySet.fromArray(names.map(String), true);\n this._sources = ArraySet.fromArray(sources, true);\n\n this.sourceRoot = sourceRoot;\n this.sourcesContent = sourcesContent;\n this._mappings = mappings;\n this.file = file;\n}\n\nBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\n/**\n * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n *\n * @param SourceMapGenerator aSourceMap\n * The source map that will be consumed.\n * @returns BasicSourceMapConsumer\n */\nBasicSourceMapConsumer.fromSourceMap =\n function SourceMapConsumer_fromSourceMap(aSourceMap) {\n var smc = Object.create(BasicSourceMapConsumer.prototype);\n\n var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n smc.sourceRoot = aSourceMap._sourceRoot;\n smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n smc.sourceRoot);\n smc.file = aSourceMap._file;\n\n // Because we are modifying the entries (by converting string sources and\n // names to indices into the sources and names ArraySets), we have to make\n // a copy of the entry or else bad things happen. Shared mutable state\n // strikes again! See github issue #191.\n\n var generatedMappings = aSourceMap._mappings.toArray().slice();\n var destGeneratedMappings = smc.__generatedMappings = [];\n var destOriginalMappings = smc.__originalMappings = [];\n\n for (var i = 0, length = generatedMappings.length; i < length; i++) {\n var srcMapping = generatedMappings[i];\n var destMapping = new Mapping;\n destMapping.generatedLine = srcMapping.generatedLine;\n destMapping.generatedColumn = srcMapping.generatedColumn;\n\n if (srcMapping.source) {\n destMapping.source = sources.indexOf(srcMapping.source);\n destMapping.originalLine = srcMapping.originalLine;\n destMapping.originalColumn = srcMapping.originalColumn;\n\n if (srcMapping.name) {\n destMapping.name = names.indexOf(srcMapping.name);\n }\n\n destOriginalMappings.push(destMapping);\n }\n\n destGeneratedMappings.push(destMapping);\n }\n\n quickSort(smc.__originalMappings, util.compareByOriginalPositions);\n\n return smc;\n };\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nBasicSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {\n get: function () {\n return this._sources.toArray().map(function (s) {\n return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s;\n }, this);\n }\n});\n\n/**\n * Provide the JIT with a nice shape / hidden class.\n */\nfunction Mapping() {\n this.generatedLine = 0;\n this.generatedColumn = 0;\n this.source = null;\n this.originalLine = null;\n this.originalColumn = null;\n this.name = null;\n}\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nBasicSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n var generatedLine = 1;\n var previousGeneratedColumn = 0;\n var previousOriginalLine = 0;\n var previousOriginalColumn = 0;\n var previousSource = 0;\n var previousName = 0;\n var length = aStr.length;\n var index = 0;\n var cachedSegments = {};\n var temp = {};\n var originalMappings = [];\n var generatedMappings = [];\n var mapping, str, segment, end, value;\n\n while (index < length) {\n if (aStr.charAt(index) === ';') {\n generatedLine++;\n index++;\n previousGeneratedColumn = 0;\n }\n else if (aStr.charAt(index) === ',') {\n index++;\n }\n else {\n mapping = new Mapping();\n mapping.generatedLine = generatedLine;\n\n // Because each offset is encoded relative to the previous one,\n // many segments often have the same encoding. We can exploit this\n // fact by caching the parsed variable length fields of each segment,\n // allowing us to avoid a second parse if we encounter the same\n // segment again.\n for (end = index; end < length; end++) {\n if (this._charIsMappingSeparator(aStr, end)) {\n break;\n }\n }\n str = aStr.slice(index, end);\n\n segment = cachedSegments[str];\n if (segment) {\n index += str.length;\n } else {\n segment = [];\n while (index < end) {\n base64VLQ.decode(aStr, index, temp);\n value = temp.value;\n index = temp.rest;\n segment.push(value);\n }\n\n if (segment.length === 2) {\n throw new Error('Found a source, but no line and column');\n }\n\n if (segment.length === 3) {\n throw new Error('Found a source and line, but no column');\n }\n\n cachedSegments[str] = segment;\n }\n\n // Generated column.\n mapping.generatedColumn = previousGeneratedColumn + segment[0];\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (segment.length > 1) {\n // Original source.\n mapping.source = previousSource + segment[1];\n previousSource += segment[1];\n\n // Original line.\n mapping.originalLine = previousOriginalLine + segment[2];\n previousOriginalLine = mapping.originalLine;\n // Lines are stored 0-based\n mapping.originalLine += 1;\n\n // Original column.\n mapping.originalColumn = previousOriginalColumn + segment[3];\n previousOriginalColumn = mapping.originalColumn;\n\n if (segment.length > 4) {\n // Original name.\n mapping.name = previousName + segment[4];\n previousName += segment[4];\n }\n }\n\n generatedMappings.push(mapping);\n if (typeof mapping.originalLine === 'number') {\n originalMappings.push(mapping);\n }\n }\n }\n\n quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);\n this.__generatedMappings = generatedMappings;\n\n quickSort(originalMappings, util.compareByOriginalPositions);\n this.__originalMappings = originalMappings;\n };\n\n/**\n * Find the mapping that best matches the hypothetical \"needle\" mapping that\n * we are searching for in the given \"haystack\" of mappings.\n */\nBasicSourceMapConsumer.prototype._findMapping =\n function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n aColumnName, aComparator, aBias) {\n // To return the position we are searching for, we must first find the\n // mapping for the given position and then return the opposite position it\n // points to. Because the mappings are sorted, we can use binary search to\n // find the best mapping.\n\n if (aNeedle[aLineName] <= 0) {\n throw new TypeError('Line must be greater than or equal to 1, got '\n + aNeedle[aLineName]);\n }\n if (aNeedle[aColumnName] < 0) {\n throw new TypeError('Column must be greater than or equal to 0, got '\n + aNeedle[aColumnName]);\n }\n\n return binarySearch.search(aNeedle, aMappings, aComparator, aBias);\n };\n\n/**\n * Compute the last column for each generated mapping. The last column is\n * inclusive.\n */\nBasicSourceMapConsumer.prototype.computeColumnSpans =\n function SourceMapConsumer_computeColumnSpans() {\n for (var index = 0; index < this._generatedMappings.length; ++index) {\n var mapping = this._generatedMappings[index];\n\n // Mappings do not contain a field for the last generated columnt. We\n // can come up with an optimistic estimate, however, by assuming that\n // mappings are contiguous (i.e. given two consecutive mappings, the\n // first mapping ends where the second one starts).\n if (index + 1 < this._generatedMappings.length) {\n var nextMapping = this._generatedMappings[index + 1];\n\n if (mapping.generatedLine === nextMapping.generatedLine) {\n mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;\n continue;\n }\n }\n\n // The last mapping for each line spans the entire line.\n mapping.lastGeneratedColumn = Infinity;\n }\n };\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source.\n * - column: The column number in the generated source.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null.\n * - column: The column number in the original source, or null.\n * - name: The original identifier, or null.\n */\nBasicSourceMapConsumer.prototype.originalPositionFor =\n function SourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._generatedMappings,\n \"generatedLine\",\n \"generatedColumn\",\n util.compareByGeneratedPositionsDeflated,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._generatedMappings[index];\n\n if (mapping.generatedLine === needle.generatedLine) {\n var source = util.getArg(mapping, 'source', null);\n if (source !== null) {\n source = this._sources.at(source);\n if (this.sourceRoot != null) {\n source = util.join(this.sourceRoot, source);\n }\n }\n var name = util.getArg(mapping, 'name', null);\n if (name !== null) {\n name = this._names.at(name);\n }\n return {\n source: source,\n line: util.getArg(mapping, 'originalLine', null),\n column: util.getArg(mapping, 'originalColumn', null),\n name: name\n };\n }\n }\n\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nBasicSourceMapConsumer.prototype.hasContentsOfAllSources =\n function BasicSourceMapConsumer_hasContentsOfAllSources() {\n if (!this.sourcesContent) {\n return false;\n }\n return this.sourcesContent.length >= this._sources.size() &&\n !this.sourcesContent.some(function (sc) { return sc == null; });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nBasicSourceMapConsumer.prototype.sourceContentFor =\n function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n if (!this.sourcesContent) {\n return null;\n }\n\n if (this.sourceRoot != null) {\n aSource = util.relative(this.sourceRoot, aSource);\n }\n\n if (this._sources.has(aSource)) {\n return this.sourcesContent[this._sources.indexOf(aSource)];\n }\n\n var url;\n if (this.sourceRoot != null\n && (url = util.urlParse(this.sourceRoot))) {\n // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n // many users. We can help them out when they expect file:// URIs to\n // behave like it would if they were running a local HTTP server. See\n // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n var fileUriAbsPath = aSource.replace(/^file:\\/\\//, \"\");\n if (url.scheme == \"file\"\n && this._sources.has(fileUriAbsPath)) {\n return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n }\n\n if ((!url.path || url.path == \"/\")\n && this._sources.has(\"/\" + aSource)) {\n return this.sourcesContent[this._sources.indexOf(\"/\" + aSource)];\n }\n }\n\n // This function is used recursively from\n // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we\n // don't want to throw if we can't find the source - we just want to\n // return null, so we provide a flag to exit gracefully.\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source.\n * - column: The column number in the original source.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null.\n * - column: The column number in the generated source, or null.\n */\nBasicSourceMapConsumer.prototype.generatedPositionFor =\n function SourceMapConsumer_generatedPositionFor(aArgs) {\n var source = util.getArg(aArgs, 'source');\n if (this.sourceRoot != null) {\n source = util.relative(this.sourceRoot, source);\n }\n if (!this._sources.has(source)) {\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n }\n source = this._sources.indexOf(source);\n\n var needle = {\n source: source,\n originalLine: util.getArg(aArgs, 'line'),\n originalColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (mapping.source === needle.source) {\n return {\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n };\n }\n }\n\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n };\n\nexports.BasicSourceMapConsumer = BasicSourceMapConsumer;\n\n/**\n * An IndexedSourceMapConsumer instance represents a parsed source map which\n * we can query for information. It differs from BasicSourceMapConsumer in\n * that it takes \"indexed\" source maps (i.e. ones with a \"sections\" field) as\n * input.\n *\n * The only parameter is a raw source map (either as a JSON string, or already\n * parsed to an object). According to the spec for indexed source maps, they\n * have the following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - file: Optional. The generated file this source map is associated with.\n * - sections: A list of section definitions.\n *\n * Each value under the \"sections\" field has two fields:\n * - offset: The offset into the original specified at which this section\n * begins to apply, defined as an object with a \"line\" and \"column\"\n * field.\n * - map: A source map definition. This source map could also be indexed,\n * but doesn't have to be.\n *\n * Instead of the \"map\" field, it's also possible to have a \"url\" field\n * specifying a URL to retrieve a source map from, but that's currently\n * unsupported.\n *\n * Here's an example source map, taken from the source map spec[0], but\n * modified to omit a section which uses the \"url\" field.\n *\n * {\n * version : 3,\n * file: \"app.js\",\n * sections: [{\n * offset: {line:100, column:10},\n * map: {\n * version : 3,\n * file: \"section.js\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AAAA,E;;ABCDE;\"\n * }\n * }],\n * }\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n */\nfunction IndexedSourceMapConsumer(aSourceMap) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = JSON.parse(aSourceMap.replace(/^\\)\\]\\}'/, ''));\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sections = util.getArg(sourceMap, 'sections');\n\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n this._sources = new ArraySet();\n this._names = new ArraySet();\n\n var lastOffset = {\n line: -1,\n column: 0\n };\n this._sections = sections.map(function (s) {\n if (s.url) {\n // The url field will require support for asynchronicity.\n // See https://github.com/mozilla/source-map/issues/16\n throw new Error('Support for url field in sections not implemented.');\n }\n var offset = util.getArg(s, 'offset');\n var offsetLine = util.getArg(offset, 'line');\n var offsetColumn = util.getArg(offset, 'column');\n\n if (offsetLine < lastOffset.line ||\n (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {\n throw new Error('Section offsets must be ordered and non-overlapping.');\n }\n lastOffset = offset;\n\n return {\n generatedOffset: {\n // The offset fields are 0-based, but we use 1-based indices when\n // encoding/decoding from VLQ.\n generatedLine: offsetLine + 1,\n generatedColumn: offsetColumn + 1\n },\n consumer: new SourceMapConsumer(util.getArg(s, 'map'))\n }\n });\n}\n\nIndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nIndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nIndexedSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {\n get: function () {\n var sources = [];\n for (var i = 0; i < this._sections.length; i++) {\n for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {\n sources.push(this._sections[i].consumer.sources[j]);\n }\n }\n return sources;\n }\n});\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source.\n * - column: The column number in the generated source.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null.\n * - column: The column number in the original source, or null.\n * - name: The original identifier, or null.\n */\nIndexedSourceMapConsumer.prototype.originalPositionFor =\n function IndexedSourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n // Find the section containing the generated position we're trying to map\n // to an original position.\n var sectionIndex = binarySearch.search(needle, this._sections,\n function(needle, section) {\n var cmp = needle.generatedLine - section.generatedOffset.generatedLine;\n if (cmp) {\n return cmp;\n }\n\n return (needle.generatedColumn -\n section.generatedOffset.generatedColumn);\n });\n var section = this._sections[sectionIndex];\n\n if (!section) {\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n }\n\n return section.consumer.originalPositionFor({\n line: needle.generatedLine -\n (section.generatedOffset.generatedLine - 1),\n column: needle.generatedColumn -\n (section.generatedOffset.generatedLine === needle.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n bias: aArgs.bias\n });\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nIndexedSourceMapConsumer.prototype.hasContentsOfAllSources =\n function IndexedSourceMapConsumer_hasContentsOfAllSources() {\n return this._sections.every(function (s) {\n return s.consumer.hasContentsOfAllSources();\n });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nIndexedSourceMapConsumer.prototype.sourceContentFor =\n function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n var content = section.consumer.sourceContentFor(aSource, true);\n if (content) {\n return content;\n }\n }\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source.\n * - column: The column number in the original source.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null.\n * - column: The column number in the generated source, or null.\n */\nIndexedSourceMapConsumer.prototype.generatedPositionFor =\n function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n // Only consider this section if the requested source is in the list of\n // sources of the consumer.\n if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) {\n continue;\n }\n var generatedPosition = section.consumer.generatedPositionFor(aArgs);\n if (generatedPosition) {\n var ret = {\n line: generatedPosition.line +\n (section.generatedOffset.generatedLine - 1),\n column: generatedPosition.column +\n (section.generatedOffset.generatedLine === generatedPosition.line\n ? section.generatedOffset.generatedColumn - 1\n : 0)\n };\n return ret;\n }\n }\n\n return {\n line: null,\n column: null\n };\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nIndexedSourceMapConsumer.prototype._parseMappings =\n function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n this.__generatedMappings = [];\n this.__originalMappings = [];\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n var sectionMappings = section.consumer._generatedMappings;\n for (var j = 0; j < sectionMappings.length; j++) {\n var mapping = sectionMappings[j];\n\n var source = section.consumer._sources.at(mapping.source);\n if (section.consumer.sourceRoot !== null) {\n source = util.join(section.consumer.sourceRoot, source);\n }\n this._sources.add(source);\n source = this._sources.indexOf(source);\n\n var name = section.consumer._names.at(mapping.name);\n this._names.add(name);\n name = this._names.indexOf(name);\n\n // The mappings coming from the consumer for the section have\n // generated positions relative to the start of the section, so we\n // need to offset them to be relative to the start of the concatenated\n // generated file.\n var adjustedMapping = {\n source: source,\n generatedLine: mapping.generatedLine +\n (section.generatedOffset.generatedLine - 1),\n generatedColumn: mapping.generatedColumn +\n (section.generatedOffset.generatedLine === mapping.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: name\n };\n\n this.__generatedMappings.push(adjustedMapping);\n if (typeof adjustedMapping.originalLine === 'number') {\n this.__originalMappings.push(adjustedMapping);\n }\n }\n }\n\n quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);\n quickSort(this.__originalMappings, util.compareByOriginalPositions);\n };\n\nexports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/snapdragon/node_modules/source-map/lib/source-map-consumer.js?"); + +/***/ }), + +/***/ "./node_modules/snapdragon/node_modules/source-map/lib/source-map-generator.js": +/*!*************************************************************************************!*\ + !*** ./node_modules/snapdragon/node_modules/source-map/lib/source-map-generator.js ***! + \*************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar base64VLQ = __webpack_require__(/*! ./base64-vlq */ \"./node_modules/snapdragon/node_modules/source-map/lib/base64-vlq.js\");\nvar util = __webpack_require__(/*! ./util */ \"./node_modules/snapdragon/node_modules/source-map/lib/util.js\");\nvar ArraySet = __webpack_require__(/*! ./array-set */ \"./node_modules/snapdragon/node_modules/source-map/lib/array-set.js\").ArraySet;\nvar MappingList = __webpack_require__(/*! ./mapping-list */ \"./node_modules/snapdragon/node_modules/source-map/lib/mapping-list.js\").MappingList;\n\n/**\n * An instance of the SourceMapGenerator represents a source map which is\n * being built incrementally. You may pass an object with the following\n * properties:\n *\n * - file: The filename of the generated source.\n * - sourceRoot: A root for all relative URLs in this source map.\n */\nfunction SourceMapGenerator(aArgs) {\n if (!aArgs) {\n aArgs = {};\n }\n this._file = util.getArg(aArgs, 'file', null);\n this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);\n this._skipValidation = util.getArg(aArgs, 'skipValidation', false);\n this._sources = new ArraySet();\n this._names = new ArraySet();\n this._mappings = new MappingList();\n this._sourcesContents = null;\n}\n\nSourceMapGenerator.prototype._version = 3;\n\n/**\n * Creates a new SourceMapGenerator based on a SourceMapConsumer\n *\n * @param aSourceMapConsumer The SourceMap.\n */\nSourceMapGenerator.fromSourceMap =\n function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {\n var sourceRoot = aSourceMapConsumer.sourceRoot;\n var generator = new SourceMapGenerator({\n file: aSourceMapConsumer.file,\n sourceRoot: sourceRoot\n });\n aSourceMapConsumer.eachMapping(function (mapping) {\n var newMapping = {\n generated: {\n line: mapping.generatedLine,\n column: mapping.generatedColumn\n }\n };\n\n if (mapping.source != null) {\n newMapping.source = mapping.source;\n if (sourceRoot != null) {\n newMapping.source = util.relative(sourceRoot, newMapping.source);\n }\n\n newMapping.original = {\n line: mapping.originalLine,\n column: mapping.originalColumn\n };\n\n if (mapping.name != null) {\n newMapping.name = mapping.name;\n }\n }\n\n generator.addMapping(newMapping);\n });\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n generator.setSourceContent(sourceFile, content);\n }\n });\n return generator;\n };\n\n/**\n * Add a single mapping from original source line and column to the generated\n * source's line and column for this source map being created. The mapping\n * object should have the following properties:\n *\n * - generated: An object with the generated line and column positions.\n * - original: An object with the original line and column positions.\n * - source: The original source file (relative to the sourceRoot).\n * - name: An optional original token name for this mapping.\n */\nSourceMapGenerator.prototype.addMapping =\n function SourceMapGenerator_addMapping(aArgs) {\n var generated = util.getArg(aArgs, 'generated');\n var original = util.getArg(aArgs, 'original', null);\n var source = util.getArg(aArgs, 'source', null);\n var name = util.getArg(aArgs, 'name', null);\n\n if (!this._skipValidation) {\n this._validateMapping(generated, original, source, name);\n }\n\n if (source != null) {\n source = String(source);\n if (!this._sources.has(source)) {\n this._sources.add(source);\n }\n }\n\n if (name != null) {\n name = String(name);\n if (!this._names.has(name)) {\n this._names.add(name);\n }\n }\n\n this._mappings.add({\n generatedLine: generated.line,\n generatedColumn: generated.column,\n originalLine: original != null && original.line,\n originalColumn: original != null && original.column,\n source: source,\n name: name\n });\n };\n\n/**\n * Set the source content for a source file.\n */\nSourceMapGenerator.prototype.setSourceContent =\n function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {\n var source = aSourceFile;\n if (this._sourceRoot != null) {\n source = util.relative(this._sourceRoot, source);\n }\n\n if (aSourceContent != null) {\n // Add the source content to the _sourcesContents map.\n // Create a new _sourcesContents map if the property is null.\n if (!this._sourcesContents) {\n this._sourcesContents = Object.create(null);\n }\n this._sourcesContents[util.toSetString(source)] = aSourceContent;\n } else if (this._sourcesContents) {\n // Remove the source file from the _sourcesContents map.\n // If the _sourcesContents map is empty, set the property to null.\n delete this._sourcesContents[util.toSetString(source)];\n if (Object.keys(this._sourcesContents).length === 0) {\n this._sourcesContents = null;\n }\n }\n };\n\n/**\n * Applies the mappings of a sub-source-map for a specific source file to the\n * source map being generated. Each mapping to the supplied source file is\n * rewritten using the supplied source map. Note: The resolution for the\n * resulting mappings is the minimium of this map and the supplied map.\n *\n * @param aSourceMapConsumer The source map to be applied.\n * @param aSourceFile Optional. The filename of the source file.\n * If omitted, SourceMapConsumer's file property will be used.\n * @param aSourceMapPath Optional. The dirname of the path to the source map\n * to be applied. If relative, it is relative to the SourceMapConsumer.\n * This parameter is needed when the two source maps aren't in the same\n * directory, and the source map to be applied contains relative source\n * paths. If so, those relative source paths need to be rewritten\n * relative to the SourceMapGenerator.\n */\nSourceMapGenerator.prototype.applySourceMap =\n function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {\n var sourceFile = aSourceFile;\n // If aSourceFile is omitted, we will use the file property of the SourceMap\n if (aSourceFile == null) {\n if (aSourceMapConsumer.file == null) {\n throw new Error(\n 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +\n 'or the source map\\'s \"file\" property. Both were omitted.'\n );\n }\n sourceFile = aSourceMapConsumer.file;\n }\n var sourceRoot = this._sourceRoot;\n // Make \"sourceFile\" relative if an absolute Url is passed.\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n // Applying the SourceMap can add and remove items from the sources and\n // the names array.\n var newSources = new ArraySet();\n var newNames = new ArraySet();\n\n // Find mappings for the \"sourceFile\"\n this._mappings.unsortedForEach(function (mapping) {\n if (mapping.source === sourceFile && mapping.originalLine != null) {\n // Check if it can be mapped by the source map, then update the mapping.\n var original = aSourceMapConsumer.originalPositionFor({\n line: mapping.originalLine,\n column: mapping.originalColumn\n });\n if (original.source != null) {\n // Copy mapping\n mapping.source = original.source;\n if (aSourceMapPath != null) {\n mapping.source = util.join(aSourceMapPath, mapping.source)\n }\n if (sourceRoot != null) {\n mapping.source = util.relative(sourceRoot, mapping.source);\n }\n mapping.originalLine = original.line;\n mapping.originalColumn = original.column;\n if (original.name != null) {\n mapping.name = original.name;\n }\n }\n }\n\n var source = mapping.source;\n if (source != null && !newSources.has(source)) {\n newSources.add(source);\n }\n\n var name = mapping.name;\n if (name != null && !newNames.has(name)) {\n newNames.add(name);\n }\n\n }, this);\n this._sources = newSources;\n this._names = newNames;\n\n // Copy sourcesContents of applied map.\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aSourceMapPath != null) {\n sourceFile = util.join(aSourceMapPath, sourceFile);\n }\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n this.setSourceContent(sourceFile, content);\n }\n }, this);\n };\n\n/**\n * A mapping can have one of the three levels of data:\n *\n * 1. Just the generated position.\n * 2. The Generated position, original position, and original source.\n * 3. Generated and original position, original source, as well as a name\n * token.\n *\n * To maintain consistency, we validate that any new mapping being added falls\n * in to one of these categories.\n */\nSourceMapGenerator.prototype._validateMapping =\n function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,\n aName) {\n // When aOriginal is truthy but has empty values for .line and .column,\n // it is most likely a programmer error. In this case we throw a very\n // specific error message to try to guide them the right way.\n // For example: https://github.com/Polymer/polymer-bundler/pull/519\n if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {\n throw new Error(\n 'original.line and original.column are not numbers -- you probably meant to omit ' +\n 'the original mapping entirely and only map the generated position. If so, pass ' +\n 'null for the original mapping instead of an object with empty or null values.'\n );\n }\n\n if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aGenerated.line > 0 && aGenerated.column >= 0\n && !aOriginal && !aSource && !aName) {\n // Case 1.\n return;\n }\n else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n && aGenerated.line > 0 && aGenerated.column >= 0\n && aOriginal.line > 0 && aOriginal.column >= 0\n && aSource) {\n // Cases 2 and 3.\n return;\n }\n else {\n throw new Error('Invalid mapping: ' + JSON.stringify({\n generated: aGenerated,\n source: aSource,\n original: aOriginal,\n name: aName\n }));\n }\n };\n\n/**\n * Serialize the accumulated mappings in to the stream of base 64 VLQs\n * specified by the source map format.\n */\nSourceMapGenerator.prototype._serializeMappings =\n function SourceMapGenerator_serializeMappings() {\n var previousGeneratedColumn = 0;\n var previousGeneratedLine = 1;\n var previousOriginalColumn = 0;\n var previousOriginalLine = 0;\n var previousName = 0;\n var previousSource = 0;\n var result = '';\n var next;\n var mapping;\n var nameIdx;\n var sourceIdx;\n\n var mappings = this._mappings.toArray();\n for (var i = 0, len = mappings.length; i < len; i++) {\n mapping = mappings[i];\n next = ''\n\n if (mapping.generatedLine !== previousGeneratedLine) {\n previousGeneratedColumn = 0;\n while (mapping.generatedLine !== previousGeneratedLine) {\n next += ';';\n previousGeneratedLine++;\n }\n }\n else {\n if (i > 0) {\n if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {\n continue;\n }\n next += ',';\n }\n }\n\n next += base64VLQ.encode(mapping.generatedColumn\n - previousGeneratedColumn);\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (mapping.source != null) {\n sourceIdx = this._sources.indexOf(mapping.source);\n next += base64VLQ.encode(sourceIdx - previousSource);\n previousSource = sourceIdx;\n\n // lines are stored 0-based in SourceMap spec version 3\n next += base64VLQ.encode(mapping.originalLine - 1\n - previousOriginalLine);\n previousOriginalLine = mapping.originalLine - 1;\n\n next += base64VLQ.encode(mapping.originalColumn\n - previousOriginalColumn);\n previousOriginalColumn = mapping.originalColumn;\n\n if (mapping.name != null) {\n nameIdx = this._names.indexOf(mapping.name);\n next += base64VLQ.encode(nameIdx - previousName);\n previousName = nameIdx;\n }\n }\n\n result += next;\n }\n\n return result;\n };\n\nSourceMapGenerator.prototype._generateSourcesContent =\n function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n return aSources.map(function (source) {\n if (!this._sourcesContents) {\n return null;\n }\n if (aSourceRoot != null) {\n source = util.relative(aSourceRoot, source);\n }\n var key = util.toSetString(source);\n return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)\n ? this._sourcesContents[key]\n : null;\n }, this);\n };\n\n/**\n * Externalize the source map.\n */\nSourceMapGenerator.prototype.toJSON =\n function SourceMapGenerator_toJSON() {\n var map = {\n version: this._version,\n sources: this._sources.toArray(),\n names: this._names.toArray(),\n mappings: this._serializeMappings()\n };\n if (this._file != null) {\n map.file = this._file;\n }\n if (this._sourceRoot != null) {\n map.sourceRoot = this._sourceRoot;\n }\n if (this._sourcesContents) {\n map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n }\n\n return map;\n };\n\n/**\n * Render the source map being generated to a string.\n */\nSourceMapGenerator.prototype.toString =\n function SourceMapGenerator_toString() {\n return JSON.stringify(this.toJSON());\n };\n\nexports.SourceMapGenerator = SourceMapGenerator;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/snapdragon/node_modules/source-map/lib/source-map-generator.js?"); + +/***/ }), + +/***/ "./node_modules/snapdragon/node_modules/source-map/lib/source-node.js": +/*!****************************************************************************!*\ + !*** ./node_modules/snapdragon/node_modules/source-map/lib/source-node.js ***! + \****************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar SourceMapGenerator = __webpack_require__(/*! ./source-map-generator */ \"./node_modules/snapdragon/node_modules/source-map/lib/source-map-generator.js\").SourceMapGenerator;\nvar util = __webpack_require__(/*! ./util */ \"./node_modules/snapdragon/node_modules/source-map/lib/util.js\");\n\n// Matches a Windows-style `\\r\\n` newline or a `\\n` newline used by all other\n// operating systems these days (capturing the result).\nvar REGEX_NEWLINE = /(\\r?\\n)/;\n\n// Newline character code for charCodeAt() comparisons\nvar NEWLINE_CODE = 10;\n\n// Private symbol for identifying `SourceNode`s when multiple versions of\n// the source-map library are loaded. This MUST NOT CHANGE across\n// versions!\nvar isSourceNode = \"$$$isSourceNode$$$\";\n\n/**\n * SourceNodes provide a way to abstract over interpolating/concatenating\n * snippets of generated JavaScript source code while maintaining the line and\n * column information associated with the original source code.\n *\n * @param aLine The original line number.\n * @param aColumn The original column number.\n * @param aSource The original source's filename.\n * @param aChunks Optional. An array of strings which are snippets of\n * generated JS, or other SourceNodes.\n * @param aName The original identifier.\n */\nfunction SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n this.children = [];\n this.sourceContents = {};\n this.line = aLine == null ? null : aLine;\n this.column = aColumn == null ? null : aColumn;\n this.source = aSource == null ? null : aSource;\n this.name = aName == null ? null : aName;\n this[isSourceNode] = true;\n if (aChunks != null) this.add(aChunks);\n}\n\n/**\n * Creates a SourceNode from generated code and a SourceMapConsumer.\n *\n * @param aGeneratedCode The generated code\n * @param aSourceMapConsumer The SourceMap for the generated code\n * @param aRelativePath Optional. The path that relative sources in the\n * SourceMapConsumer should be relative to.\n */\nSourceNode.fromStringWithSourceMap =\n function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {\n // The SourceNode we want to fill with the generated code\n // and the SourceMap\n var node = new SourceNode();\n\n // All even indices of this array are one line of the generated code,\n // while all odd indices are the newlines between two adjacent lines\n // (since `REGEX_NEWLINE` captures its match).\n // Processed fragments are accessed by calling `shiftNextLine`.\n var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);\n var remainingLinesIndex = 0;\n var shiftNextLine = function() {\n var lineContents = getNextLine();\n // The last line of a file might not have a newline.\n var newLine = getNextLine() || \"\";\n return lineContents + newLine;\n\n function getNextLine() {\n return remainingLinesIndex < remainingLines.length ?\n remainingLines[remainingLinesIndex++] : undefined;\n }\n };\n\n // We need to remember the position of \"remainingLines\"\n var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\n // The generate SourceNodes we need a code range.\n // To extract it current and last mapping is used.\n // Here we store the last mapping.\n var lastMapping = null;\n\n aSourceMapConsumer.eachMapping(function (mapping) {\n if (lastMapping !== null) {\n // We add the code from \"lastMapping\" to \"mapping\":\n // First check if there is a new line in between.\n if (lastGeneratedLine < mapping.generatedLine) {\n // Associate first line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n lastGeneratedLine++;\n lastGeneratedColumn = 0;\n // The remaining code is added without mapping\n } else {\n // There is no new line in between.\n // Associate the code between \"lastGeneratedColumn\" and\n // \"mapping.generatedColumn\" with \"lastMapping\"\n var nextLine = remainingLines[remainingLinesIndex];\n var code = nextLine.substr(0, mapping.generatedColumn -\n lastGeneratedColumn);\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -\n lastGeneratedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n addMappingWithCode(lastMapping, code);\n // No more remaining code, continue\n lastMapping = mapping;\n return;\n }\n }\n // We add the generated code until the first mapping\n // to the SourceNode without any mapping.\n // Each line is added as separate string.\n while (lastGeneratedLine < mapping.generatedLine) {\n node.add(shiftNextLine());\n lastGeneratedLine++;\n }\n if (lastGeneratedColumn < mapping.generatedColumn) {\n var nextLine = remainingLines[remainingLinesIndex];\n node.add(nextLine.substr(0, mapping.generatedColumn));\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n }\n lastMapping = mapping;\n }, this);\n // We have processed all mappings.\n if (remainingLinesIndex < remainingLines.length) {\n if (lastMapping) {\n // Associate the remaining code in the current line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n }\n // and add the remaining lines without any mapping\n node.add(remainingLines.splice(remainingLinesIndex).join(\"\"));\n }\n\n // Copy sourcesContent into SourceNode\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aRelativePath != null) {\n sourceFile = util.join(aRelativePath, sourceFile);\n }\n node.setSourceContent(sourceFile, content);\n }\n });\n\n return node;\n\n function addMappingWithCode(mapping, code) {\n if (mapping === null || mapping.source === undefined) {\n node.add(code);\n } else {\n var source = aRelativePath\n ? util.join(aRelativePath, mapping.source)\n : mapping.source;\n node.add(new SourceNode(mapping.originalLine,\n mapping.originalColumn,\n source,\n code,\n mapping.name));\n }\n }\n };\n\n/**\n * Add a chunk of generated JS to this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.add = function SourceNode_add(aChunk) {\n if (Array.isArray(aChunk)) {\n aChunk.forEach(function (chunk) {\n this.add(chunk);\n }, this);\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n if (aChunk) {\n this.children.push(aChunk);\n }\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Add a chunk of generated JS to the beginning of this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n if (Array.isArray(aChunk)) {\n for (var i = aChunk.length-1; i >= 0; i--) {\n this.prepend(aChunk[i]);\n }\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n this.children.unshift(aChunk);\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Walk over the tree of JS snippets in this node and its children. The\n * walking function is called once for each snippet of JS and is passed that\n * snippet and the its original associated source's line/column location.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walk = function SourceNode_walk(aFn) {\n var chunk;\n for (var i = 0, len = this.children.length; i < len; i++) {\n chunk = this.children[i];\n if (chunk[isSourceNode]) {\n chunk.walk(aFn);\n }\n else {\n if (chunk !== '') {\n aFn(chunk, { source: this.source,\n line: this.line,\n column: this.column,\n name: this.name });\n }\n }\n }\n};\n\n/**\n * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n * each of `this.children`.\n *\n * @param aSep The separator.\n */\nSourceNode.prototype.join = function SourceNode_join(aSep) {\n var newChildren;\n var i;\n var len = this.children.length;\n if (len > 0) {\n newChildren = [];\n for (i = 0; i < len-1; i++) {\n newChildren.push(this.children[i]);\n newChildren.push(aSep);\n }\n newChildren.push(this.children[i]);\n this.children = newChildren;\n }\n return this;\n};\n\n/**\n * Call String.prototype.replace on the very right-most source snippet. Useful\n * for trimming whitespace from the end of a source node, etc.\n *\n * @param aPattern The pattern to replace.\n * @param aReplacement The thing to replace the pattern with.\n */\nSourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n var lastChild = this.children[this.children.length - 1];\n if (lastChild[isSourceNode]) {\n lastChild.replaceRight(aPattern, aReplacement);\n }\n else if (typeof lastChild === 'string') {\n this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n }\n else {\n this.children.push(''.replace(aPattern, aReplacement));\n }\n return this;\n};\n\n/**\n * Set the source content for a source file. This will be added to the SourceMapGenerator\n * in the sourcesContent field.\n *\n * @param aSourceFile The filename of the source file\n * @param aSourceContent The content of the source file\n */\nSourceNode.prototype.setSourceContent =\n function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n };\n\n/**\n * Walk over the tree of SourceNodes. The walking function is called for each\n * source file content and is passed the filename and source content.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walkSourceContents =\n function SourceNode_walkSourceContents(aFn) {\n for (var i = 0, len = this.children.length; i < len; i++) {\n if (this.children[i][isSourceNode]) {\n this.children[i].walkSourceContents(aFn);\n }\n }\n\n var sources = Object.keys(this.sourceContents);\n for (var i = 0, len = sources.length; i < len; i++) {\n aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n }\n };\n\n/**\n * Return the string representation of this source node. Walks over the tree\n * and concatenates all the various snippets together to one string.\n */\nSourceNode.prototype.toString = function SourceNode_toString() {\n var str = \"\";\n this.walk(function (chunk) {\n str += chunk;\n });\n return str;\n};\n\n/**\n * Returns the string representation of this source node along with a source\n * map.\n */\nSourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n var generated = {\n code: \"\",\n line: 1,\n column: 0\n };\n var map = new SourceMapGenerator(aArgs);\n var sourceMappingActive = false;\n var lastOriginalSource = null;\n var lastOriginalLine = null;\n var lastOriginalColumn = null;\n var lastOriginalName = null;\n this.walk(function (chunk, original) {\n generated.code += chunk;\n if (original.source !== null\n && original.line !== null\n && original.column !== null) {\n if(lastOriginalSource !== original.source\n || lastOriginalLine !== original.line\n || lastOriginalColumn !== original.column\n || lastOriginalName !== original.name) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n lastOriginalSource = original.source;\n lastOriginalLine = original.line;\n lastOriginalColumn = original.column;\n lastOriginalName = original.name;\n sourceMappingActive = true;\n } else if (sourceMappingActive) {\n map.addMapping({\n generated: {\n line: generated.line,\n column: generated.column\n }\n });\n lastOriginalSource = null;\n sourceMappingActive = false;\n }\n for (var idx = 0, length = chunk.length; idx < length; idx++) {\n if (chunk.charCodeAt(idx) === NEWLINE_CODE) {\n generated.line++;\n generated.column = 0;\n // Mappings end at eol\n if (idx + 1 === length) {\n lastOriginalSource = null;\n sourceMappingActive = false;\n } else if (sourceMappingActive) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n } else {\n generated.column++;\n }\n }\n });\n this.walkSourceContents(function (sourceFile, sourceContent) {\n map.setSourceContent(sourceFile, sourceContent);\n });\n\n return { code: generated.code, map: map };\n};\n\nexports.SourceNode = SourceNode;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/snapdragon/node_modules/source-map/lib/source-node.js?"); + +/***/ }), + +/***/ "./node_modules/snapdragon/node_modules/source-map/lib/util.js": +/*!*********************************************************************!*\ + !*** ./node_modules/snapdragon/node_modules/source-map/lib/util.js ***! + \*********************************************************************/ +/***/ ((__unused_webpack_module, exports) => { + +eval("/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n/**\n * This is a helper function for getting values from parameter/options\n * objects.\n *\n * @param args The object we are extracting values from\n * @param name The name of the property we are getting.\n * @param defaultValue An optional value to return if the property is missing\n * from the object. If this is not specified and the property is missing, an\n * error will be thrown.\n */\nfunction getArg(aArgs, aName, aDefaultValue) {\n if (aName in aArgs) {\n return aArgs[aName];\n } else if (arguments.length === 3) {\n return aDefaultValue;\n } else {\n throw new Error('\"' + aName + '\" is a required argument.');\n }\n}\nexports.getArg = getArg;\n\nvar urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.]*)(?::(\\d+))?(\\S*)$/;\nvar dataUrlRegexp = /^data:.+\\,.+$/;\n\nfunction urlParse(aUrl) {\n var match = aUrl.match(urlRegexp);\n if (!match) {\n return null;\n }\n return {\n scheme: match[1],\n auth: match[2],\n host: match[3],\n port: match[4],\n path: match[5]\n };\n}\nexports.urlParse = urlParse;\n\nfunction urlGenerate(aParsedUrl) {\n var url = '';\n if (aParsedUrl.scheme) {\n url += aParsedUrl.scheme + ':';\n }\n url += '//';\n if (aParsedUrl.auth) {\n url += aParsedUrl.auth + '@';\n }\n if (aParsedUrl.host) {\n url += aParsedUrl.host;\n }\n if (aParsedUrl.port) {\n url += \":\" + aParsedUrl.port\n }\n if (aParsedUrl.path) {\n url += aParsedUrl.path;\n }\n return url;\n}\nexports.urlGenerate = urlGenerate;\n\n/**\n * Normalizes a path, or the path portion of a URL:\n *\n * - Replaces consecutive slashes with one slash.\n * - Removes unnecessary '.' parts.\n * - Removes unnecessary '/..' parts.\n *\n * Based on code in the Node.js 'path' core module.\n *\n * @param aPath The path or url to normalize.\n */\nfunction normalize(aPath) {\n var path = aPath;\n var url = urlParse(aPath);\n if (url) {\n if (!url.path) {\n return aPath;\n }\n path = url.path;\n }\n var isAbsolute = exports.isAbsolute(path);\n\n var parts = path.split(/\\/+/);\n for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n part = parts[i];\n if (part === '.') {\n parts.splice(i, 1);\n } else if (part === '..') {\n up++;\n } else if (up > 0) {\n if (part === '') {\n // The first part is blank if the path is absolute. Trying to go\n // above the root is a no-op. Therefore we can remove all '..' parts\n // directly after the root.\n parts.splice(i + 1, up);\n up = 0;\n } else {\n parts.splice(i, 2);\n up--;\n }\n }\n }\n path = parts.join('/');\n\n if (path === '') {\n path = isAbsolute ? '/' : '.';\n }\n\n if (url) {\n url.path = path;\n return urlGenerate(url);\n }\n return path;\n}\nexports.normalize = normalize;\n\n/**\n * Joins two paths/URLs.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be joined with the root.\n *\n * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n * scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n * first.\n * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n * is updated with the result and aRoot is returned. Otherwise the result\n * is returned.\n * - If aPath is absolute, the result is aPath.\n * - Otherwise the two paths are joined with a slash.\n * - Joining for example 'http://' and 'www.example.com' is also supported.\n */\nfunction join(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n if (aPath === \"\") {\n aPath = \".\";\n }\n var aPathUrl = urlParse(aPath);\n var aRootUrl = urlParse(aRoot);\n if (aRootUrl) {\n aRoot = aRootUrl.path || '/';\n }\n\n // `join(foo, '//www.example.org')`\n if (aPathUrl && !aPathUrl.scheme) {\n if (aRootUrl) {\n aPathUrl.scheme = aRootUrl.scheme;\n }\n return urlGenerate(aPathUrl);\n }\n\n if (aPathUrl || aPath.match(dataUrlRegexp)) {\n return aPath;\n }\n\n // `join('http://', 'www.example.com')`\n if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n aRootUrl.host = aPath;\n return urlGenerate(aRootUrl);\n }\n\n var joined = aPath.charAt(0) === '/'\n ? aPath\n : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\n if (aRootUrl) {\n aRootUrl.path = joined;\n return urlGenerate(aRootUrl);\n }\n return joined;\n}\nexports.join = join;\n\nexports.isAbsolute = function (aPath) {\n return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp);\n};\n\n/**\n * Make a path relative to a URL or another path.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be made relative to aRoot.\n */\nfunction relative(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n\n aRoot = aRoot.replace(/\\/$/, '');\n\n // It is possible for the path to be above the root. In this case, simply\n // checking whether the root is a prefix of the path won't work. Instead, we\n // need to remove components from the root one by one, until either we find\n // a prefix that fits, or we run out of components to remove.\n var level = 0;\n while (aPath.indexOf(aRoot + '/') !== 0) {\n var index = aRoot.lastIndexOf(\"/\");\n if (index < 0) {\n return aPath;\n }\n\n // If the only part of the root that is left is the scheme (i.e. http://,\n // file:///, etc.), one or more slashes (/), or simply nothing at all, we\n // have exhausted all components, so the path is not relative to the root.\n aRoot = aRoot.slice(0, index);\n if (aRoot.match(/^([^\\/]+:\\/)?\\/*$/)) {\n return aPath;\n }\n\n ++level;\n }\n\n // Make sure we add a \"../\" for each component we removed from the root.\n return Array(level + 1).join(\"../\") + aPath.substr(aRoot.length + 1);\n}\nexports.relative = relative;\n\nvar supportsNullProto = (function () {\n var obj = Object.create(null);\n return !('__proto__' in obj);\n}());\n\nfunction identity (s) {\n return s;\n}\n\n/**\n * Because behavior goes wacky when you set `__proto__` on objects, we\n * have to prefix all the strings in our set with an arbitrary character.\n *\n * See https://github.com/mozilla/source-map/pull/31 and\n * https://github.com/mozilla/source-map/issues/30\n *\n * @param String aStr\n */\nfunction toSetString(aStr) {\n if (isProtoString(aStr)) {\n return '$' + aStr;\n }\n\n return aStr;\n}\nexports.toSetString = supportsNullProto ? identity : toSetString;\n\nfunction fromSetString(aStr) {\n if (isProtoString(aStr)) {\n return aStr.slice(1);\n }\n\n return aStr;\n}\nexports.fromSetString = supportsNullProto ? identity : fromSetString;\n\nfunction isProtoString(s) {\n if (!s) {\n return false;\n }\n\n var length = s.length;\n\n if (length < 9 /* \"__proto__\".length */) {\n return false;\n }\n\n if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||\n s.charCodeAt(length - 2) !== 95 /* '_' */ ||\n s.charCodeAt(length - 3) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 4) !== 116 /* 't' */ ||\n s.charCodeAt(length - 5) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 6) !== 114 /* 'r' */ ||\n s.charCodeAt(length - 7) !== 112 /* 'p' */ ||\n s.charCodeAt(length - 8) !== 95 /* '_' */ ||\n s.charCodeAt(length - 9) !== 95 /* '_' */) {\n return false;\n }\n\n for (var i = length - 10; i >= 0; i--) {\n if (s.charCodeAt(i) !== 36 /* '$' */) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Comparator between two mappings where the original positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same original source/line/column, but different generated\n * line and column the same. Useful when searching for a mapping with a\n * stubbed out mapping.\n */\nfunction compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n var cmp = mappingA.source - mappingB.source;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0 || onlyCompareOriginal) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n return mappingA.name - mappingB.name;\n}\nexports.compareByOriginalPositions = compareByOriginalPositions;\n\n/**\n * Comparator between two mappings with deflated source and name indices where\n * the generated positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same generated line and column, but different\n * source/name/original line and column the same. Useful when searching for a\n * mapping with a stubbed out mapping.\n */\nfunction compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0 || onlyCompareGenerated) {\n return cmp;\n }\n\n cmp = mappingA.source - mappingB.source;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return mappingA.name - mappingB.name;\n}\nexports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\nfunction strcmp(aStr1, aStr2) {\n if (aStr1 === aStr2) {\n return 0;\n }\n\n if (aStr1 > aStr2) {\n return 1;\n }\n\n return -1;\n}\n\n/**\n * Comparator between two mappings with inflated source and name strings where\n * the generated positions are compared.\n */\nfunction compareByGeneratedPositionsInflated(mappingA, mappingB) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/snapdragon/node_modules/source-map/lib/util.js?"); + +/***/ }), + +/***/ "./node_modules/snapdragon/node_modules/source-map/source-map.js": +/*!***********************************************************************!*\ + !*** ./node_modules/snapdragon/node_modules/source-map/source-map.js ***! + \***********************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("/*\n * Copyright 2009-2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE.txt or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\nexports.SourceMapGenerator = __webpack_require__(/*! ./lib/source-map-generator */ \"./node_modules/snapdragon/node_modules/source-map/lib/source-map-generator.js\").SourceMapGenerator;\nexports.SourceMapConsumer = __webpack_require__(/*! ./lib/source-map-consumer */ \"./node_modules/snapdragon/node_modules/source-map/lib/source-map-consumer.js\").SourceMapConsumer;\nexports.SourceNode = __webpack_require__(/*! ./lib/source-node */ \"./node_modules/snapdragon/node_modules/source-map/lib/source-node.js\").SourceNode;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/snapdragon/node_modules/source-map/source-map.js?"); + +/***/ }), + +/***/ "./node_modules/source-map-resolve/lib/decode-uri-component.js": +/*!*********************************************************************!*\ + !*** ./node_modules/source-map-resolve/lib/decode-uri-component.js ***! + \*********************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var decodeUriComponent = __webpack_require__(/*! decode-uri-component */ \"./node_modules/decode-uri-component/index.js\")\n\nfunction customDecodeUriComponent(string) {\n // `decodeUriComponent` turns `+` into ` `, but that's not wanted.\n return decodeUriComponent(string.replace(/\\+/g, \"%2B\"))\n}\n\nmodule.exports = customDecodeUriComponent\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/source-map-resolve/lib/decode-uri-component.js?"); + +/***/ }), + +/***/ "./node_modules/source-map-resolve/lib/resolve-url.js": +/*!************************************************************!*\ + !*** ./node_modules/source-map-resolve/lib/resolve-url.js ***! + \************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var url = __webpack_require__(/*! url */ \"url\")\n\nfunction resolveUrl(/* ...urls */) {\n return Array.prototype.reduce.call(arguments, function(resolved, nextUrl) {\n return url.resolve(resolved, nextUrl)\n })\n}\n\nmodule.exports = resolveUrl\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/source-map-resolve/lib/resolve-url.js?"); + +/***/ }), + +/***/ "./node_modules/source-map-resolve/lib/source-map-resolve-node.js": +/*!************************************************************************!*\ + !*** ./node_modules/source-map-resolve/lib/source-map-resolve-node.js ***! + \************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var sourceMappingURL = __webpack_require__(/*! source-map-url */ \"./node_modules/source-map-url/source-map-url.js\")\n\nvar resolveUrl = __webpack_require__(/*! ./resolve-url */ \"./node_modules/source-map-resolve/lib/resolve-url.js\")\nvar decodeUriComponent = __webpack_require__(/*! ./decode-uri-component */ \"./node_modules/source-map-resolve/lib/decode-uri-component.js\")\nvar urix = __webpack_require__(/*! urix */ \"./node_modules/urix/index.js\")\nvar atob = __webpack_require__(/*! atob */ \"./node_modules/atob/node-atob.js\")\n\n\n\nfunction callbackAsync(callback, error, result) {\n setImmediate(function() { callback(error, result) })\n}\n\nfunction parseMapToJSON(string, data) {\n try {\n return JSON.parse(string.replace(/^\\)\\]\\}'/, \"\"))\n } catch (error) {\n error.sourceMapData = data\n throw error\n }\n}\n\nfunction readSync(read, url, data) {\n var readUrl = decodeUriComponent(url)\n try {\n return String(read(readUrl))\n } catch (error) {\n error.sourceMapData = data\n throw error\n }\n}\n\n\n\nfunction resolveSourceMap(code, codeUrl, read, callback) {\n var mapData\n try {\n mapData = resolveSourceMapHelper(code, codeUrl)\n } catch (error) {\n return callbackAsync(callback, error)\n }\n if (!mapData || mapData.map) {\n return callbackAsync(callback, null, mapData)\n }\n var readUrl = decodeUriComponent(mapData.url)\n read(readUrl, function(error, result) {\n if (error) {\n error.sourceMapData = mapData\n return callback(error)\n }\n mapData.map = String(result)\n try {\n mapData.map = parseMapToJSON(mapData.map, mapData)\n } catch (error) {\n return callback(error)\n }\n callback(null, mapData)\n })\n}\n\nfunction resolveSourceMapSync(code, codeUrl, read) {\n var mapData = resolveSourceMapHelper(code, codeUrl)\n if (!mapData || mapData.map) {\n return mapData\n }\n mapData.map = readSync(read, mapData.url, mapData)\n mapData.map = parseMapToJSON(mapData.map, mapData)\n return mapData\n}\n\nvar dataUriRegex = /^data:([^,;]*)(;[^,;]*)*(?:,(.*))?$/\n\n/**\n * The media type for JSON text is application/json.\n *\n * {@link https://tools.ietf.org/html/rfc8259#section-11 | IANA Considerations }\n *\n * `text/json` is non-standard media type\n */\nvar jsonMimeTypeRegex = /^(?:application|text)\\/json$/\n\n/**\n * JSON text exchanged between systems that are not part of a closed ecosystem\n * MUST be encoded using UTF-8.\n *\n * {@link https://tools.ietf.org/html/rfc8259#section-8.1 | Character Encoding}\n */\nvar jsonCharacterEncoding = \"utf-8\"\n\nfunction base64ToBuf(b64) {\n var binStr = atob(b64)\n var len = binStr.length\n var arr = new Uint8Array(len)\n for (var i = 0; i < len; i++) {\n arr[i] = binStr.charCodeAt(i)\n }\n return arr\n}\n\nfunction decodeBase64String(b64) {\n if (typeof TextDecoder === \"undefined\" || typeof Uint8Array === \"undefined\") {\n return atob(b64)\n }\n var buf = base64ToBuf(b64);\n // Note: `decoder.decode` method will throw a `DOMException` with the\n // `\"EncodingError\"` value when an coding error is found.\n var decoder = new TextDecoder(jsonCharacterEncoding, {fatal: true})\n return decoder.decode(buf);\n}\n\nfunction resolveSourceMapHelper(code, codeUrl) {\n codeUrl = urix(codeUrl)\n\n var url = sourceMappingURL.getFrom(code)\n if (!url) {\n return null\n }\n\n var dataUri = url.match(dataUriRegex)\n if (dataUri) {\n var mimeType = dataUri[1] || \"text/plain\"\n var lastParameter = dataUri[2] || \"\"\n var encoded = dataUri[3] || \"\"\n var data = {\n sourceMappingURL: url,\n url: null,\n sourcesRelativeTo: codeUrl,\n map: encoded\n }\n if (!jsonMimeTypeRegex.test(mimeType)) {\n var error = new Error(\"Unuseful data uri mime type: \" + mimeType)\n error.sourceMapData = data\n throw error\n }\n try {\n data.map = parseMapToJSON(\n lastParameter === \";base64\" ? decodeBase64String(encoded) : decodeURIComponent(encoded),\n data\n )\n } catch (error) {\n error.sourceMapData = data\n throw error\n }\n return data\n }\n\n var mapUrl = resolveUrl(codeUrl, url)\n return {\n sourceMappingURL: url,\n url: mapUrl,\n sourcesRelativeTo: mapUrl,\n map: null\n }\n}\n\n\n\nfunction resolveSources(map, mapUrl, read, options, callback) {\n if (typeof options === \"function\") {\n callback = options\n options = {}\n }\n var pending = map.sources ? map.sources.length : 0\n var result = {\n sourcesResolved: [],\n sourcesContent: []\n }\n\n if (pending === 0) {\n callbackAsync(callback, null, result)\n return\n }\n\n var done = function() {\n pending--\n if (pending === 0) {\n callback(null, result)\n }\n }\n\n resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) {\n result.sourcesResolved[index] = fullUrl\n if (typeof sourceContent === \"string\") {\n result.sourcesContent[index] = sourceContent\n callbackAsync(done, null)\n } else {\n var readUrl = decodeUriComponent(fullUrl)\n read(readUrl, function(error, source) {\n result.sourcesContent[index] = error ? error : String(source)\n done()\n })\n }\n })\n}\n\nfunction resolveSourcesSync(map, mapUrl, read, options) {\n var result = {\n sourcesResolved: [],\n sourcesContent: []\n }\n\n if (!map.sources || map.sources.length === 0) {\n return result\n }\n\n resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) {\n result.sourcesResolved[index] = fullUrl\n if (read !== null) {\n if (typeof sourceContent === \"string\") {\n result.sourcesContent[index] = sourceContent\n } else {\n var readUrl = decodeUriComponent(fullUrl)\n try {\n result.sourcesContent[index] = String(read(readUrl))\n } catch (error) {\n result.sourcesContent[index] = error\n }\n }\n }\n })\n\n return result\n}\n\nvar endingSlash = /\\/?$/\n\nfunction resolveSourcesHelper(map, mapUrl, options, fn) {\n options = options || {}\n mapUrl = urix(mapUrl)\n var fullUrl\n var sourceContent\n var sourceRoot\n for (var index = 0, len = map.sources.length; index < len; index++) {\n sourceRoot = null\n if (typeof options.sourceRoot === \"string\") {\n sourceRoot = options.sourceRoot\n } else if (typeof map.sourceRoot === \"string\" && options.sourceRoot !== false) {\n sourceRoot = map.sourceRoot\n }\n // If the sourceRoot is the empty string, it is equivalent to not setting\n // the property at all.\n if (sourceRoot === null || sourceRoot === '') {\n fullUrl = resolveUrl(mapUrl, map.sources[index])\n } else {\n // Make sure that the sourceRoot ends with a slash, so that `/scripts/subdir` becomes\n // `/scripts/subdir/`, not `/scripts/`. Pointing to a file as source root\n // does not make sense.\n fullUrl = resolveUrl(mapUrl, sourceRoot.replace(endingSlash, \"/\"), map.sources[index])\n }\n sourceContent = (map.sourcesContent || [])[index]\n fn(fullUrl, sourceContent, index)\n }\n}\n\n\n\nfunction resolve(code, codeUrl, read, options, callback) {\n if (typeof options === \"function\") {\n callback = options\n options = {}\n }\n if (code === null) {\n var mapUrl = codeUrl\n var data = {\n sourceMappingURL: null,\n url: mapUrl,\n sourcesRelativeTo: mapUrl,\n map: null\n }\n var readUrl = decodeUriComponent(mapUrl)\n read(readUrl, function(error, result) {\n if (error) {\n error.sourceMapData = data\n return callback(error)\n }\n data.map = String(result)\n try {\n data.map = parseMapToJSON(data.map, data)\n } catch (error) {\n return callback(error)\n }\n _resolveSources(data)\n })\n } else {\n resolveSourceMap(code, codeUrl, read, function(error, mapData) {\n if (error) {\n return callback(error)\n }\n if (!mapData) {\n return callback(null, null)\n }\n _resolveSources(mapData)\n })\n }\n\n function _resolveSources(mapData) {\n resolveSources(mapData.map, mapData.sourcesRelativeTo, read, options, function(error, result) {\n if (error) {\n return callback(error)\n }\n mapData.sourcesResolved = result.sourcesResolved\n mapData.sourcesContent = result.sourcesContent\n callback(null, mapData)\n })\n }\n}\n\nfunction resolveSync(code, codeUrl, read, options) {\n var mapData\n if (code === null) {\n var mapUrl = codeUrl\n mapData = {\n sourceMappingURL: null,\n url: mapUrl,\n sourcesRelativeTo: mapUrl,\n map: null\n }\n mapData.map = readSync(read, mapUrl, mapData)\n mapData.map = parseMapToJSON(mapData.map, mapData)\n } else {\n mapData = resolveSourceMapSync(code, codeUrl, read)\n if (!mapData) {\n return null\n }\n }\n var result = resolveSourcesSync(mapData.map, mapData.sourcesRelativeTo, read, options)\n mapData.sourcesResolved = result.sourcesResolved\n mapData.sourcesContent = result.sourcesContent\n return mapData\n}\n\n\n\nmodule.exports = {\n resolveSourceMap: resolveSourceMap,\n resolveSourceMapSync: resolveSourceMapSync,\n resolveSources: resolveSources,\n resolveSourcesSync: resolveSourcesSync,\n resolve: resolve,\n resolveSync: resolveSync,\n parseMapToJSON: parseMapToJSON\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/source-map-resolve/lib/source-map-resolve-node.js?"); + +/***/ }), + +/***/ "./node_modules/source-map-url/source-map-url.js": +/*!*******************************************************!*\ + !*** ./node_modules/source-map-url/source-map-url.js ***! + \*******************************************************/ +/***/ (function(module, exports, __webpack_require__) { + +eval("var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;// Copyright 2014 Simon Lydell\n// X11 (“MIT”) Licensed. (See LICENSE.)\n\nvoid (function(root, factory) {\n if (true) {\n !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),\n\t\t__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?\n\t\t(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :\n\t\t__WEBPACK_AMD_DEFINE_FACTORY__),\n\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))\n } else {}\n}(this, function() {\n\n var innerRegex = /[#@] sourceMappingURL=([^\\s'\"]*)/\n\n var regex = RegExp(\n \"(?:\" +\n \"/\\\\*\" +\n \"(?:\\\\s*\\r?\\n(?://)?)?\" +\n \"(?:\" + innerRegex.source + \")\" +\n \"\\\\s*\" +\n \"\\\\*/\" +\n \"|\" +\n \"//(?:\" + innerRegex.source + \")\" +\n \")\" +\n \"\\\\s*\"\n )\n\n return {\n\n regex: regex,\n _innerRegex: innerRegex,\n\n getFrom: function(code) {\n var match = code.match(regex)\n return (match ? match[1] || match[2] || \"\" : null)\n },\n\n existsIn: function(code) {\n return regex.test(code)\n },\n\n removeFrom: function(code) {\n return code.replace(regex, \"\")\n },\n\n insertBefore: function(code, string) {\n var match = code.match(regex)\n if (match) {\n return code.slice(0, match.index) + string + code.slice(match.index)\n } else {\n return code + string\n }\n }\n }\n\n}));\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/source-map-url/source-map-url.js?"); + +/***/ }), + +/***/ "./node_modules/split-string/index.js": +/*!********************************************!*\ + !*** ./node_modules/split-string/index.js ***! + \********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * split-string \n *\n * Copyright (c) 2015-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar extend = __webpack_require__(/*! extend-shallow */ \"./node_modules/split-string/node_modules/extend-shallow/index.js\");\n\nmodule.exports = function(str, options, fn) {\n if (typeof str !== 'string') {\n throw new TypeError('expected a string');\n }\n\n if (typeof options === 'function') {\n fn = options;\n options = null;\n }\n\n // allow separator to be defined as a string\n if (typeof options === 'string') {\n options = { sep: options };\n }\n\n var opts = extend({sep: '.'}, options);\n var quotes = opts.quotes || ['\"', \"'\", '`'];\n var brackets;\n\n if (opts.brackets === true) {\n brackets = {\n '<': '>',\n '(': ')',\n '[': ']',\n '{': '}'\n };\n } else if (opts.brackets) {\n brackets = opts.brackets;\n }\n\n var tokens = [];\n var stack = [];\n var arr = [''];\n var sep = opts.sep;\n var len = str.length;\n var idx = -1;\n var closeIdx;\n\n function expected() {\n if (brackets && stack.length) {\n return brackets[stack[stack.length - 1]];\n }\n }\n\n while (++idx < len) {\n var ch = str[idx];\n var next = str[idx + 1];\n var tok = { val: ch, idx: idx, arr: arr, str: str };\n tokens.push(tok);\n\n if (ch === '\\\\') {\n tok.val = keepEscaping(opts, str, idx) === true ? (ch + next) : next;\n tok.escaped = true;\n if (typeof fn === 'function') {\n fn(tok);\n }\n arr[arr.length - 1] += tok.val;\n idx++;\n continue;\n }\n\n if (brackets && brackets[ch]) {\n stack.push(ch);\n var e = expected();\n var i = idx + 1;\n\n if (str.indexOf(e, i + 1) !== -1) {\n while (stack.length && i < len) {\n var s = str[++i];\n if (s === '\\\\') {\n s++;\n continue;\n }\n\n if (quotes.indexOf(s) !== -1) {\n i = getClosingQuote(str, s, i + 1);\n continue;\n }\n\n e = expected();\n if (stack.length && str.indexOf(e, i + 1) === -1) {\n break;\n }\n\n if (brackets[s]) {\n stack.push(s);\n continue;\n }\n\n if (e === s) {\n stack.pop();\n }\n }\n }\n\n closeIdx = i;\n if (closeIdx === -1) {\n arr[arr.length - 1] += ch;\n continue;\n }\n\n ch = str.slice(idx, closeIdx + 1);\n tok.val = ch;\n tok.idx = idx = closeIdx;\n }\n\n if (quotes.indexOf(ch) !== -1) {\n closeIdx = getClosingQuote(str, ch, idx + 1);\n if (closeIdx === -1) {\n arr[arr.length - 1] += ch;\n continue;\n }\n\n if (keepQuotes(ch, opts) === true) {\n ch = str.slice(idx, closeIdx + 1);\n } else {\n ch = str.slice(idx + 1, closeIdx);\n }\n\n tok.val = ch;\n tok.idx = idx = closeIdx;\n }\n\n if (typeof fn === 'function') {\n fn(tok, tokens);\n ch = tok.val;\n idx = tok.idx;\n }\n\n if (tok.val === sep && tok.split !== false) {\n arr.push('');\n continue;\n }\n\n arr[arr.length - 1] += tok.val;\n }\n\n return arr;\n};\n\nfunction getClosingQuote(str, ch, i, brackets) {\n var idx = str.indexOf(ch, i);\n if (str.charAt(idx - 1) === '\\\\') {\n return getClosingQuote(str, ch, idx + 1);\n }\n return idx;\n}\n\nfunction keepQuotes(ch, opts) {\n if (opts.keepDoubleQuotes === true && ch === '\"') return true;\n if (opts.keepSingleQuotes === true && ch === \"'\") return true;\n return opts.keepQuotes;\n}\n\nfunction keepEscaping(opts, str, idx) {\n if (typeof opts.keepEscaping === 'function') {\n return opts.keepEscaping(str, idx);\n }\n return opts.keepEscaping === true || str[idx + 1] === '\\\\';\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/split-string/index.js?"); + +/***/ }), + +/***/ "./node_modules/split-string/node_modules/extend-shallow/index.js": +/*!************************************************************************!*\ + !*** ./node_modules/split-string/node_modules/extend-shallow/index.js ***! + \************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar isExtendable = __webpack_require__(/*! is-extendable */ \"./node_modules/split-string/node_modules/is-extendable/index.js\");\nvar assignSymbols = __webpack_require__(/*! assign-symbols */ \"./node_modules/assign-symbols/index.js\");\n\nmodule.exports = Object.assign || function(obj/*, objects*/) {\n if (obj === null || typeof obj === 'undefined') {\n throw new TypeError('Cannot convert undefined or null to object');\n }\n if (!isObject(obj)) {\n obj = {};\n }\n for (var i = 1; i < arguments.length; i++) {\n var val = arguments[i];\n if (isString(val)) {\n val = toObject(val);\n }\n if (isObject(val)) {\n assign(obj, val);\n assignSymbols(obj, val);\n }\n }\n return obj;\n};\n\nfunction assign(a, b) {\n for (var key in b) {\n if (hasOwn(b, key)) {\n a[key] = b[key];\n }\n }\n}\n\nfunction isString(val) {\n return (val && typeof val === 'string');\n}\n\nfunction toObject(str) {\n var obj = {};\n for (var i in str) {\n obj[i] = str[i];\n }\n return obj;\n}\n\nfunction isObject(val) {\n return (val && typeof val === 'object') || isExtendable(val);\n}\n\n/**\n * Returns true if the given `key` is an own property of `obj`.\n */\n\nfunction hasOwn(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nfunction isEnum(obj, key) {\n return Object.prototype.propertyIsEnumerable.call(obj, key);\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/split-string/node_modules/extend-shallow/index.js?"); + +/***/ }), + +/***/ "./node_modules/split-string/node_modules/is-extendable/index.js": +/*!***********************************************************************!*\ + !*** ./node_modules/split-string/node_modules/is-extendable/index.js ***! + \***********************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * is-extendable \n *\n * Copyright (c) 2015-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar isPlainObject = __webpack_require__(/*! is-plain-object */ \"./node_modules/is-plain-object/index.js\");\n\nmodule.exports = function isExtendable(val) {\n return isPlainObject(val) || typeof val === 'function' || Array.isArray(val);\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/split-string/node_modules/is-extendable/index.js?"); + +/***/ }), + +/***/ "./node_modules/static-extend/index.js": +/*!*********************************************!*\ + !*** ./node_modules/static-extend/index.js ***! + \*********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * static-extend \n *\n * Copyright (c) 2016, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n\n\nvar copy = __webpack_require__(/*! object-copy */ \"./node_modules/object-copy/index.js\");\nvar define = __webpack_require__(/*! define-property */ \"./node_modules/define-property/index.js\");\nvar util = __webpack_require__(/*! util */ \"util\");\n\n/**\n * Returns a function for extending the static properties,\n * prototype properties, and descriptors from the `Parent`\n * constructor onto `Child` constructors.\n *\n * ```js\n * var extend = require('static-extend');\n * Parent.extend = extend(Parent);\n *\n * // optionally pass a custom merge function as the second arg\n * Parent.extend = extend(Parent, function(Child) {\n * Child.prototype.mixin = function(key, val) {\n * Child.prototype[key] = val;\n * };\n * });\n *\n * // extend \"child\" constructors\n * Parent.extend(Child);\n *\n * // optionally define prototype methods as the second arg\n * Parent.extend(Child, {\n * foo: function() {},\n * bar: function() {}\n * });\n * ```\n * @param {Function} `Parent` Parent ctor\n * @param {Function} `extendFn` Optional extend function for handling any necessary custom merging. Useful when updating methods that require a specific prototype.\n * @param {Function} `Child` Child ctor\n * @param {Object} `proto` Optionally pass additional prototype properties to inherit.\n * @return {Object}\n * @api public\n */\n\nfunction extend(Parent, extendFn) {\n if (typeof Parent !== 'function') {\n throw new TypeError('expected Parent to be a function.');\n }\n\n return function(Ctor, proto) {\n if (typeof Ctor !== 'function') {\n throw new TypeError('expected Ctor to be a function.');\n }\n\n util.inherits(Ctor, Parent);\n copy(Ctor, Parent);\n\n // proto can be null or a plain object\n if (typeof proto === 'object') {\n var obj = Object.create(proto);\n\n for (var k in obj) {\n Ctor.prototype[k] = obj[k];\n }\n }\n\n // keep a reference to the parent prototype\n define(Ctor.prototype, '_parent_', {\n configurable: true,\n set: function() {},\n get: function() {\n return Parent.prototype;\n }\n });\n\n if (typeof extendFn === 'function') {\n extendFn(Ctor, Parent);\n }\n\n Ctor.extend = extend(Ctor, extendFn);\n };\n};\n\n/**\n * Expose `extend`\n */\n\nmodule.exports = extend;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/static-extend/index.js?"); + +/***/ }), + +/***/ "./node_modules/string_decoder/lib/string_decoder.js": +/*!***********************************************************!*\ + !*** ./node_modules/string_decoder/lib/string_decoder.js ***! + \***********************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n\n/**/\n\nvar Buffer = __webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer;\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/string_decoder/lib/string_decoder.js?"); + +/***/ }), + +/***/ "./node_modules/to-object-path/index.js": +/*!**********************************************!*\ + !*** ./node_modules/to-object-path/index.js ***! + \**********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * to-object-path \n *\n * Copyright (c) 2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n\n\nvar typeOf = __webpack_require__(/*! kind-of */ \"./node_modules/to-object-path/node_modules/kind-of/index.js\");\n\nmodule.exports = function toPath(args) {\n if (typeOf(args) !== 'arguments') {\n args = arguments;\n }\n return filter(args).join('.');\n};\n\nfunction filter(arr) {\n var len = arr.length;\n var idx = -1;\n var res = [];\n\n while (++idx < len) {\n var ele = arr[idx];\n if (typeOf(ele) === 'arguments' || Array.isArray(ele)) {\n res.push.apply(res, filter(ele));\n } else if (typeof ele === 'string') {\n res.push(ele);\n }\n }\n return res;\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/to-object-path/index.js?"); + +/***/ }), + +/***/ "./node_modules/to-object-path/node_modules/kind-of/index.js": +/*!*******************************************************************!*\ + !*** ./node_modules/to-object-path/node_modules/kind-of/index.js ***! + \*******************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var isBuffer = __webpack_require__(/*! is-buffer */ \"./node_modules/is-buffer/index.js\");\nvar toString = Object.prototype.toString;\n\n/**\n * Get the native `typeof` a value.\n *\n * @param {*} `val`\n * @return {*} Native javascript type\n */\n\nmodule.exports = function kindOf(val) {\n // primitivies\n if (typeof val === 'undefined') {\n return 'undefined';\n }\n if (val === null) {\n return 'null';\n }\n if (val === true || val === false || val instanceof Boolean) {\n return 'boolean';\n }\n if (typeof val === 'string' || val instanceof String) {\n return 'string';\n }\n if (typeof val === 'number' || val instanceof Number) {\n return 'number';\n }\n\n // functions\n if (typeof val === 'function' || val instanceof Function) {\n return 'function';\n }\n\n // array\n if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {\n return 'array';\n }\n\n // check for instances of RegExp and Date before calling `toString`\n if (val instanceof RegExp) {\n return 'regexp';\n }\n if (val instanceof Date) {\n return 'date';\n }\n\n // other objects\n var type = toString.call(val);\n\n if (type === '[object RegExp]') {\n return 'regexp';\n }\n if (type === '[object Date]') {\n return 'date';\n }\n if (type === '[object Arguments]') {\n return 'arguments';\n }\n if (type === '[object Error]') {\n return 'error';\n }\n\n // buffer\n if (isBuffer(val)) {\n return 'buffer';\n }\n\n // es6: Map, WeakMap, Set, WeakSet\n if (type === '[object Set]') {\n return 'set';\n }\n if (type === '[object WeakSet]') {\n return 'weakset';\n }\n if (type === '[object Map]') {\n return 'map';\n }\n if (type === '[object WeakMap]') {\n return 'weakmap';\n }\n if (type === '[object Symbol]') {\n return 'symbol';\n }\n\n // typed arrays\n if (type === '[object Int8Array]') {\n return 'int8array';\n }\n if (type === '[object Uint8Array]') {\n return 'uint8array';\n }\n if (type === '[object Uint8ClampedArray]') {\n return 'uint8clampedarray';\n }\n if (type === '[object Int16Array]') {\n return 'int16array';\n }\n if (type === '[object Uint16Array]') {\n return 'uint16array';\n }\n if (type === '[object Int32Array]') {\n return 'int32array';\n }\n if (type === '[object Uint32Array]') {\n return 'uint32array';\n }\n if (type === '[object Float32Array]') {\n return 'float32array';\n }\n if (type === '[object Float64Array]') {\n return 'float64array';\n }\n\n // must be a plain object\n return 'object';\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/to-object-path/node_modules/kind-of/index.js?"); + +/***/ }), + +/***/ "./node_modules/to-regex-range/index.js": +/*!**********************************************!*\ + !*** ./node_modules/to-regex-range/index.js ***! + \**********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * to-regex-range \n *\n * Copyright (c) 2015, 2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar repeat = __webpack_require__(/*! repeat-string */ \"./node_modules/repeat-string/index.js\");\nvar isNumber = __webpack_require__(/*! is-number */ \"./node_modules/is-number/index.js\");\nvar cache = {};\n\nfunction toRegexRange(min, max, options) {\n if (isNumber(min) === false) {\n throw new RangeError('toRegexRange: first argument is invalid.');\n }\n\n if (typeof max === 'undefined' || min === max) {\n return String(min);\n }\n\n if (isNumber(max) === false) {\n throw new RangeError('toRegexRange: second argument is invalid.');\n }\n\n options = options || {};\n var relax = String(options.relaxZeros);\n var shorthand = String(options.shorthand);\n var capture = String(options.capture);\n var key = min + ':' + max + '=' + relax + shorthand + capture;\n if (cache.hasOwnProperty(key)) {\n return cache[key].result;\n }\n\n var a = Math.min(min, max);\n var b = Math.max(min, max);\n\n if (Math.abs(a - b) === 1) {\n var result = min + '|' + max;\n if (options.capture) {\n return '(' + result + ')';\n }\n return result;\n }\n\n var isPadded = padding(min) || padding(max);\n var positives = [];\n var negatives = [];\n\n var tok = {min: min, max: max, a: a, b: b};\n if (isPadded) {\n tok.isPadded = isPadded;\n tok.maxLen = String(tok.max).length;\n }\n\n if (a < 0) {\n var newMin = b < 0 ? Math.abs(b) : 1;\n var newMax = Math.abs(a);\n negatives = splitToPatterns(newMin, newMax, tok, options);\n a = tok.a = 0;\n }\n\n if (b >= 0) {\n positives = splitToPatterns(a, b, tok, options);\n }\n\n tok.negatives = negatives;\n tok.positives = positives;\n tok.result = siftPatterns(negatives, positives, options);\n\n if (options.capture && (positives.length + negatives.length) > 1) {\n tok.result = '(' + tok.result + ')';\n }\n\n cache[key] = tok;\n return tok.result;\n}\n\nfunction siftPatterns(neg, pos, options) {\n var onlyNegative = filterPatterns(neg, pos, '-', false, options) || [];\n var onlyPositive = filterPatterns(pos, neg, '', false, options) || [];\n var intersected = filterPatterns(neg, pos, '-?', true, options) || [];\n var subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);\n return subpatterns.join('|');\n}\n\nfunction splitToRanges(min, max) {\n min = Number(min);\n max = Number(max);\n\n var nines = 1;\n var stops = [max];\n var stop = +countNines(min, nines);\n\n while (min <= stop && stop <= max) {\n stops = push(stops, stop);\n nines += 1;\n stop = +countNines(min, nines);\n }\n\n var zeros = 1;\n stop = countZeros(max + 1, zeros) - 1;\n\n while (min < stop && stop <= max) {\n stops = push(stops, stop);\n zeros += 1;\n stop = countZeros(max + 1, zeros) - 1;\n }\n\n stops.sort(compare);\n return stops;\n}\n\n/**\n * Convert a range to a regex pattern\n * @param {Number} `start`\n * @param {Number} `stop`\n * @return {String}\n */\n\nfunction rangeToPattern(start, stop, options) {\n if (start === stop) {\n return {pattern: String(start), digits: []};\n }\n\n var zipped = zip(String(start), String(stop));\n var len = zipped.length, i = -1;\n\n var pattern = '';\n var digits = 0;\n\n while (++i < len) {\n var numbers = zipped[i];\n var startDigit = numbers[0];\n var stopDigit = numbers[1];\n\n if (startDigit === stopDigit) {\n pattern += startDigit;\n\n } else if (startDigit !== '0' || stopDigit !== '9') {\n pattern += toCharacterClass(startDigit, stopDigit);\n\n } else {\n digits += 1;\n }\n }\n\n if (digits) {\n pattern += options.shorthand ? '\\\\d' : '[0-9]';\n }\n\n return { pattern: pattern, digits: [digits] };\n}\n\nfunction splitToPatterns(min, max, tok, options) {\n var ranges = splitToRanges(min, max);\n var len = ranges.length;\n var idx = -1;\n\n var tokens = [];\n var start = min;\n var prev;\n\n while (++idx < len) {\n var range = ranges[idx];\n var obj = rangeToPattern(start, range, options);\n var zeros = '';\n\n if (!tok.isPadded && prev && prev.pattern === obj.pattern) {\n if (prev.digits.length > 1) {\n prev.digits.pop();\n }\n prev.digits.push(obj.digits[0]);\n prev.string = prev.pattern + toQuantifier(prev.digits);\n start = range + 1;\n continue;\n }\n\n if (tok.isPadded) {\n zeros = padZeros(range, tok);\n }\n\n obj.string = zeros + obj.pattern + toQuantifier(obj.digits);\n tokens.push(obj);\n start = range + 1;\n prev = obj;\n }\n\n return tokens;\n}\n\nfunction filterPatterns(arr, comparison, prefix, intersection, options) {\n var res = [];\n\n for (var i = 0; i < arr.length; i++) {\n var tok = arr[i];\n var ele = tok.string;\n\n if (options.relaxZeros !== false) {\n if (prefix === '-' && ele.charAt(0) === '0') {\n if (ele.charAt(1) === '{') {\n ele = '0*' + ele.replace(/^0\\{\\d+\\}/, '');\n } else {\n ele = '0*' + ele.slice(1);\n }\n }\n }\n\n if (!intersection && !contains(comparison, 'string', ele)) {\n res.push(prefix + ele);\n }\n\n if (intersection && contains(comparison, 'string', ele)) {\n res.push(prefix + ele);\n }\n }\n return res;\n}\n\n/**\n * Zip strings (`for in` can be used on string characters)\n */\n\nfunction zip(a, b) {\n var arr = [];\n for (var ch in a) arr.push([a[ch], b[ch]]);\n return arr;\n}\n\nfunction compare(a, b) {\n return a > b ? 1 : b > a ? -1 : 0;\n}\n\nfunction push(arr, ele) {\n if (arr.indexOf(ele) === -1) arr.push(ele);\n return arr;\n}\n\nfunction contains(arr, key, val) {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i][key] === val) {\n return true;\n }\n }\n return false;\n}\n\nfunction countNines(min, len) {\n return String(min).slice(0, -len) + repeat('9', len);\n}\n\nfunction countZeros(integer, zeros) {\n return integer - (integer % Math.pow(10, zeros));\n}\n\nfunction toQuantifier(digits) {\n var start = digits[0];\n var stop = digits[1] ? (',' + digits[1]) : '';\n if (!stop && (!start || start === 1)) {\n return '';\n }\n return '{' + start + stop + '}';\n}\n\nfunction toCharacterClass(a, b) {\n return '[' + a + ((b - a === 1) ? '' : '-') + b + ']';\n}\n\nfunction padding(str) {\n return /^-?(0+)\\d/.exec(str);\n}\n\nfunction padZeros(val, tok) {\n if (tok.isPadded) {\n var diff = Math.abs(tok.maxLen - String(val).length);\n switch (diff) {\n case 0:\n return '';\n case 1:\n return '0';\n default: {\n return '0{' + diff + '}';\n }\n }\n }\n return val;\n}\n\n/**\n * Expose `toRegexRange`\n */\n\nmodule.exports = toRegexRange;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/to-regex-range/index.js?"); + +/***/ }), + +/***/ "./node_modules/to-regex/index.js": +/*!****************************************!*\ + !*** ./node_modules/to-regex/index.js ***! + \****************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar safe = __webpack_require__(/*! safe-regex */ \"./node_modules/safe-regex/index.js\");\nvar define = __webpack_require__(/*! define-property */ \"./node_modules/to-regex/node_modules/define-property/index.js\");\nvar extend = __webpack_require__(/*! extend-shallow */ \"./node_modules/to-regex/node_modules/extend-shallow/index.js\");\nvar not = __webpack_require__(/*! regex-not */ \"./node_modules/regex-not/index.js\");\nvar MAX_LENGTH = 1024 * 64;\n\n/**\n * Session cache\n */\n\nvar cache = {};\n\n/**\n * Create a regular expression from the given `pattern` string.\n *\n * @param {String|RegExp} `pattern` Pattern can be a string or regular expression.\n * @param {Object} `options`\n * @return {RegExp}\n * @api public\n */\n\nmodule.exports = function(patterns, options) {\n if (!Array.isArray(patterns)) {\n return makeRe(patterns, options);\n }\n return makeRe(patterns.join('|'), options);\n};\n\n/**\n * Create a regular expression from the given `pattern` string.\n *\n * @param {String|RegExp} `pattern` Pattern can be a string or regular expression.\n * @param {Object} `options`\n * @return {RegExp}\n * @api public\n */\n\nfunction makeRe(pattern, options) {\n if (pattern instanceof RegExp) {\n return pattern;\n }\n\n if (typeof pattern !== 'string') {\n throw new TypeError('expected a string');\n }\n\n if (pattern.length > MAX_LENGTH) {\n throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters');\n }\n\n var key = pattern;\n // do this before shallow cloning options, it's a lot faster\n if (!options || (options && options.cache !== false)) {\n key = createKey(pattern, options);\n\n if (cache.hasOwnProperty(key)) {\n return cache[key];\n }\n }\n\n var opts = extend({}, options);\n if (opts.contains === true) {\n if (opts.negate === true) {\n opts.strictNegate = false;\n } else {\n opts.strict = false;\n }\n }\n\n if (opts.strict === false) {\n opts.strictOpen = false;\n opts.strictClose = false;\n }\n\n var open = opts.strictOpen !== false ? '^' : '';\n var close = opts.strictClose !== false ? '$' : '';\n var flags = opts.flags || '';\n var regex;\n\n if (opts.nocase === true && !/i/.test(flags)) {\n flags += 'i';\n }\n\n try {\n if (opts.negate || typeof opts.strictNegate === 'boolean') {\n pattern = not.create(pattern, opts);\n }\n\n var str = open + '(?:' + pattern + ')' + close;\n regex = new RegExp(str, flags);\n\n if (opts.safe === true && safe(regex) === false) {\n throw new Error('potentially unsafe regular expression: ' + regex.source);\n }\n\n } catch (err) {\n if (opts.strictErrors === true || opts.safe === true) {\n err.key = key;\n err.pattern = pattern;\n err.originalOptions = options;\n err.createdOptions = opts;\n throw err;\n }\n\n try {\n regex = new RegExp('^' + pattern.replace(/(\\W)/g, '\\\\$1') + '$');\n } catch (err) {\n regex = /.^/; //<= match nothing\n }\n }\n\n if (opts.cache !== false) {\n memoize(regex, key, pattern, opts);\n }\n return regex;\n}\n\n/**\n * Memoize generated regex. This can result in dramatic speed improvements\n * and simplify debugging by adding options and pattern to the regex. It can be\n * disabled by passing setting `options.cache` to false.\n */\n\nfunction memoize(regex, key, pattern, options) {\n define(regex, 'cached', true);\n define(regex, 'pattern', pattern);\n define(regex, 'options', options);\n define(regex, 'key', key);\n cache[key] = regex;\n}\n\n/**\n * Create the key to use for memoization. The key is generated\n * by iterating over the options and concatenating key-value pairs\n * to the pattern string.\n */\n\nfunction createKey(pattern, options) {\n if (!options) return pattern;\n var key = pattern;\n for (var prop in options) {\n if (options.hasOwnProperty(prop)) {\n key += ';' + prop + '=' + String(options[prop]);\n }\n }\n return key;\n}\n\n/**\n * Expose `makeRe`\n */\n\nmodule.exports.makeRe = makeRe;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/to-regex/index.js?"); + +/***/ }), + +/***/ "./node_modules/to-regex/node_modules/define-property/index.js": +/*!*********************************************************************!*\ + !*** ./node_modules/to-regex/node_modules/define-property/index.js ***! + \*********************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * define-property \n *\n * Copyright (c) 2015-2018, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar isobject = __webpack_require__(/*! isobject */ \"./node_modules/isobject/index.js\");\nvar isDescriptor = __webpack_require__(/*! is-descriptor */ \"./node_modules/is-descriptor/index.js\");\nvar define = (typeof Reflect !== 'undefined' && Reflect.defineProperty)\n ? Reflect.defineProperty\n : Object.defineProperty;\n\nmodule.exports = function defineProperty(obj, key, val) {\n if (!isobject(obj) && typeof obj !== 'function' && !Array.isArray(obj)) {\n throw new TypeError('expected an object, function, or array');\n }\n\n if (typeof key !== 'string') {\n throw new TypeError('expected \"key\" to be a string');\n }\n\n if (isDescriptor(val)) {\n define(obj, key, val);\n return obj;\n }\n\n define(obj, key, {\n configurable: true,\n enumerable: false,\n writable: true,\n value: val\n });\n\n return obj;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/to-regex/node_modules/define-property/index.js?"); + +/***/ }), + +/***/ "./node_modules/to-regex/node_modules/extend-shallow/index.js": +/*!********************************************************************!*\ + !*** ./node_modules/to-regex/node_modules/extend-shallow/index.js ***! + \********************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar isExtendable = __webpack_require__(/*! is-extendable */ \"./node_modules/to-regex/node_modules/is-extendable/index.js\");\nvar assignSymbols = __webpack_require__(/*! assign-symbols */ \"./node_modules/assign-symbols/index.js\");\n\nmodule.exports = Object.assign || function(obj/*, objects*/) {\n if (obj === null || typeof obj === 'undefined') {\n throw new TypeError('Cannot convert undefined or null to object');\n }\n if (!isObject(obj)) {\n obj = {};\n }\n for (var i = 1; i < arguments.length; i++) {\n var val = arguments[i];\n if (isString(val)) {\n val = toObject(val);\n }\n if (isObject(val)) {\n assign(obj, val);\n assignSymbols(obj, val);\n }\n }\n return obj;\n};\n\nfunction assign(a, b) {\n for (var key in b) {\n if (hasOwn(b, key)) {\n a[key] = b[key];\n }\n }\n}\n\nfunction isString(val) {\n return (val && typeof val === 'string');\n}\n\nfunction toObject(str) {\n var obj = {};\n for (var i in str) {\n obj[i] = str[i];\n }\n return obj;\n}\n\nfunction isObject(val) {\n return (val && typeof val === 'object') || isExtendable(val);\n}\n\n/**\n * Returns true if the given `key` is an own property of `obj`.\n */\n\nfunction hasOwn(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nfunction isEnum(obj, key) {\n return Object.prototype.propertyIsEnumerable.call(obj, key);\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/to-regex/node_modules/extend-shallow/index.js?"); + +/***/ }), + +/***/ "./node_modules/to-regex/node_modules/is-extendable/index.js": +/*!*******************************************************************!*\ + !*** ./node_modules/to-regex/node_modules/is-extendable/index.js ***! + \*******************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * is-extendable \n *\n * Copyright (c) 2015-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar isPlainObject = __webpack_require__(/*! is-plain-object */ \"./node_modules/is-plain-object/index.js\");\n\nmodule.exports = function isExtendable(val) {\n return isPlainObject(val) || typeof val === 'function' || Array.isArray(val);\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/to-regex/node_modules/is-extendable/index.js?"); + +/***/ }), + +/***/ "./node_modules/union-value/index.js": +/*!*******************************************!*\ + !*** ./node_modules/union-value/index.js ***! + \*******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar isObject = __webpack_require__(/*! is-extendable */ \"./node_modules/is-extendable/index.js\");\nvar union = __webpack_require__(/*! arr-union */ \"./node_modules/arr-union/index.js\");\nvar get = __webpack_require__(/*! get-value */ \"./node_modules/get-value/index.js\");\nvar set = __webpack_require__(/*! set-value */ \"./node_modules/set-value/index.js\");\n\nmodule.exports = function unionValue(obj, prop, value) {\n if (!isObject(obj)) {\n throw new TypeError('union-value expects the first argument to be an object.');\n }\n\n if (typeof prop !== 'string') {\n throw new TypeError('union-value expects `prop` to be a string.');\n }\n\n var arr = arrayify(get(obj, prop));\n set(obj, prop, union(arr, arrayify(value)));\n return obj;\n};\n\nfunction arrayify(val) {\n if (val === null || typeof val === 'undefined') {\n return [];\n }\n if (Array.isArray(val)) {\n return val;\n }\n return [val];\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/union-value/index.js?"); + +/***/ }), + +/***/ "./node_modules/unset-value/index.js": +/*!*******************************************!*\ + !*** ./node_modules/unset-value/index.js ***! + \*******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * unset-value \n *\n * Copyright (c) 2015, 2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nvar isObject = __webpack_require__(/*! isobject */ \"./node_modules/isobject/index.js\");\nvar has = __webpack_require__(/*! has-value */ \"./node_modules/unset-value/node_modules/has-value/index.js\");\n\nmodule.exports = function unset(obj, prop) {\n if (!isObject(obj)) {\n throw new TypeError('expected an object.');\n }\n if (obj.hasOwnProperty(prop)) {\n delete obj[prop];\n return true;\n }\n\n if (has(obj, prop)) {\n var segs = prop.split('.');\n var last = segs.pop();\n while (segs.length && segs[segs.length - 1].slice(-1) === '\\\\') {\n last = segs.pop().slice(0, -1) + '.' + last;\n }\n while (segs.length) obj = obj[prop = segs.shift()];\n return (delete obj[last]);\n }\n return true;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/unset-value/index.js?"); + +/***/ }), + +/***/ "./node_modules/unset-value/node_modules/has-value/index.js": +/*!******************************************************************!*\ + !*** ./node_modules/unset-value/node_modules/has-value/index.js ***! + \******************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * has-value \n *\n * Copyright (c) 2014-2016, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n\n\nvar isObject = __webpack_require__(/*! isobject */ \"./node_modules/unset-value/node_modules/has-value/node_modules/isobject/index.js\");\nvar hasValues = __webpack_require__(/*! has-values */ \"./node_modules/unset-value/node_modules/has-values/index.js\");\nvar get = __webpack_require__(/*! get-value */ \"./node_modules/get-value/index.js\");\n\nmodule.exports = function(obj, prop, noZero) {\n if (isObject(obj)) {\n return hasValues(get(obj, prop), noZero);\n }\n return hasValues(obj, prop);\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/unset-value/node_modules/has-value/index.js?"); + +/***/ }), + +/***/ "./node_modules/unset-value/node_modules/has-value/node_modules/isobject/index.js": +/*!****************************************************************************************!*\ + !*** ./node_modules/unset-value/node_modules/has-value/node_modules/isobject/index.js ***! + \****************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * isobject \n *\n * Copyright (c) 2014-2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n\n\nvar isArray = __webpack_require__(/*! isarray */ \"./node_modules/isarray/index.js\");\n\nmodule.exports = function isObject(val) {\n return val != null && typeof val === 'object' && isArray(val) === false;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/unset-value/node_modules/has-value/node_modules/isobject/index.js?"); + +/***/ }), + +/***/ "./node_modules/unset-value/node_modules/has-values/index.js": +/*!*******************************************************************!*\ + !*** ./node_modules/unset-value/node_modules/has-values/index.js ***! + \*******************************************************************/ +/***/ ((module) => { + +"use strict"; +eval("/*!\n * has-values \n *\n * Copyright (c) 2014-2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n\n\nmodule.exports = function hasValue(o, noZero) {\n if (o === null || o === undefined) {\n return false;\n }\n\n if (typeof o === 'boolean') {\n return true;\n }\n\n if (typeof o === 'number') {\n if (o === 0 && noZero === true) {\n return false;\n }\n return true;\n }\n\n if (o.length !== undefined) {\n return o.length !== 0;\n }\n\n for (var key in o) {\n if (o.hasOwnProperty(key)) {\n return true;\n }\n }\n return false;\n};\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/unset-value/node_modules/has-values/index.js?"); + +/***/ }), + +/***/ "./node_modules/upath/build/code/upath.js": +/*!************************************************!*\ + !*** ./node_modules/upath/build/code/upath.js ***! + \************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("/**\n* upath http://github.com/anodynos/upath/\n*\n* A proxy to `path`, replacing `\\` with `/` for all results & new methods to normalize & join keeping leading `./` and add, change, default, trim file extensions.\n* Version 1.2.0 - Compiled on 2019-09-02 23:33:57\n* Repository git://github.com/anodynos/upath\n* Copyright(c) 2019 Angelos Pikoulas \n* License MIT\n*/\n\n// Generated by uRequire v0.7.0-beta.33 target: 'lib' template: 'nodejs'\n\n\nvar VERSION = '1.2.0'; // injected by urequire-rc-inject-version\n\nvar extraFn, extraFunctions, isFunction, isString, isValidExt, name, path, propName, propValue, toUnix, upath, slice = [].slice, indexOf = [].indexOf || function (item) {\n for (var i = 0, l = this.length; i < l; i++) {\n if (i in this && this[i] === item)\n return i;\n }\n return -1;\n }, hasProp = {}.hasOwnProperty;\npath = __webpack_require__(/*! path */ \"path\");\nisFunction = function (val) {\n return val instanceof Function;\n};\nisString = function (val) {\n return typeof val === \"string\" || !!val && typeof val === \"object\" && Object.prototype.toString.call(val) === \"[object String]\";\n};\nupath = exports;\nupath.VERSION = typeof VERSION !== \"undefined\" && VERSION !== null ? VERSION : \"NO-VERSION\";\ntoUnix = function (p) {\n var double;\n p = p.replace(/\\\\/g, \"/\");\n double = /\\/\\//;\n while (p.match(double)) {\n p = p.replace(double, \"/\");\n }\n return p;\n};\nfor (propName in path) {\n propValue = path[propName];\n if (isFunction(propValue)) {\n upath[propName] = function (propName) {\n return function () {\n var args, result;\n args = 1 <= arguments.length ? slice.call(arguments, 0) : [];\n args = args.map(function (p) {\n if (isString(p)) {\n return toUnix(p);\n } else {\n return p;\n }\n });\n result = path[propName].apply(path, args);\n if (isString(result)) {\n return toUnix(result);\n } else {\n return result;\n }\n };\n }(propName);\n } else {\n upath[propName] = propValue;\n }\n}\nupath.sep = \"/\";\nextraFunctions = {\n toUnix: toUnix,\n normalizeSafe: function (p) {\n p = toUnix(p);\n if (p.startsWith(\"./\")) {\n if (p.startsWith(\"./..\") || p === \"./\") {\n return upath.normalize(p);\n } else {\n return \"./\" + upath.normalize(p);\n }\n } else {\n return upath.normalize(p);\n }\n },\n normalizeTrim: function (p) {\n p = upath.normalizeSafe(p);\n if (p.endsWith(\"/\")) {\n return p.slice(0, +(p.length - 2) + 1 || 9000000000);\n } else {\n return p;\n }\n },\n joinSafe: function () {\n var p, result;\n p = 1 <= arguments.length ? slice.call(arguments, 0) : [];\n result = upath.join.apply(null, p);\n if (p[0].startsWith(\"./\") && !result.startsWith(\"./\")) {\n result = \"./\" + result;\n }\n return result;\n },\n addExt: function (file, ext) {\n if (!ext) {\n return file;\n } else {\n if (ext[0] !== \".\") {\n ext = \".\" + ext;\n }\n return file + (file.endsWith(ext) ? \"\" : ext);\n }\n },\n trimExt: function (filename, ignoreExts, maxSize) {\n var oldExt;\n if (maxSize == null) {\n maxSize = 7;\n }\n oldExt = upath.extname(filename);\n if (isValidExt(oldExt, ignoreExts, maxSize)) {\n return filename.slice(0, +(filename.length - oldExt.length - 1) + 1 || 9000000000);\n } else {\n return filename;\n }\n },\n removeExt: function (filename, ext) {\n if (!ext) {\n return filename;\n } else {\n ext = ext[0] === \".\" ? ext : \".\" + ext;\n if (upath.extname(filename) === ext) {\n return upath.trimExt(filename);\n } else {\n return filename;\n }\n }\n },\n changeExt: function (filename, ext, ignoreExts, maxSize) {\n if (maxSize == null) {\n maxSize = 7;\n }\n return upath.trimExt(filename, ignoreExts, maxSize) + (!ext ? \"\" : ext[0] === \".\" ? ext : \".\" + ext);\n },\n defaultExt: function (filename, ext, ignoreExts, maxSize) {\n var oldExt;\n if (maxSize == null) {\n maxSize = 7;\n }\n oldExt = upath.extname(filename);\n if (isValidExt(oldExt, ignoreExts, maxSize)) {\n return filename;\n } else {\n return upath.addExt(filename, ext);\n }\n }\n};\nisValidExt = function (ext, ignoreExts, maxSize) {\n if (ignoreExts == null) {\n ignoreExts = [];\n }\n return ext && ext.length <= maxSize && indexOf.call(ignoreExts.map(function (e) {\n return (e && e[0] !== \".\" ? \".\" : \"\") + e;\n }), ext) < 0;\n};\nfor (name in extraFunctions) {\n if (!hasProp.call(extraFunctions, name))\n continue;\n extraFn = extraFunctions[name];\n if (upath[name] !== void 0) {\n throw new Error(\"path.\" + name + \" already exists.\");\n } else {\n upath[name] = extraFn;\n }\n}\n\n;\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/upath/build/code/upath.js?"); + +/***/ }), + +/***/ "./node_modules/urix/index.js": +/*!************************************!*\ + !*** ./node_modules/urix/index.js ***! + \************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("// Copyright 2014 Simon Lydell\r\n// X11 (“MIT”) Licensed. (See LICENSE.)\r\n\r\nvar path = __webpack_require__(/*! path */ \"path\")\r\n\r\n\"use strict\"\r\n\r\nfunction urix(aPath) {\r\n if (path.sep === \"\\\\\") {\r\n return aPath\r\n .replace(/\\\\/g, \"/\")\r\n .replace(/^[a-z]:\\/?/i, \"/\")\r\n }\r\n return aPath\r\n}\r\n\r\nmodule.exports = urix\r\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/urix/index.js?"); + +/***/ }), + +/***/ "./node_modules/use/index.js": +/*!***********************************!*\ + !*** ./node_modules/use/index.js ***! + \***********************************/ +/***/ ((module) => { + +"use strict"; +eval("/*!\n * use \n *\n * Copyright (c) 2015-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n\n\nmodule.exports = function base(app, options) {\n if (!isObject(app) && typeof app !== 'function') {\n throw new TypeError('expected an object or function');\n }\n\n var opts = isObject(options) ? options : {};\n var prop = typeof opts.prop === 'string' ? opts.prop : 'fns';\n if (!Array.isArray(app[prop])) {\n define(app, prop, []);\n }\n\n /**\n * Define a plugin function to be passed to use. The only\n * parameter exposed to the plugin is `app`, the object or function.\n * passed to `use(app)`. `app` is also exposed as `this` in plugins.\n *\n * Additionally, **if a plugin returns a function, the function will\n * be pushed onto the `fns` array**, allowing the plugin to be\n * called at a later point by the `run` method.\n *\n * ```js\n * var use = require('use');\n *\n * // define a plugin\n * function foo(app) {\n * // do stuff\n * }\n *\n * var app = function(){};\n * use(app);\n *\n * // register plugins\n * app.use(foo);\n * app.use(bar);\n * app.use(baz);\n * ```\n * @name .use\n * @param {Function} `fn` plugin function to call\n * @api public\n */\n\n define(app, 'use', use);\n\n /**\n * Run all plugins on `fns`. Any plugin that returns a function\n * when called by `use` is pushed onto the `fns` array.\n *\n * ```js\n * var config = {};\n * app.run(config);\n * ```\n * @name .run\n * @param {Object} `value` Object to be modified by plugins.\n * @return {Object} Returns the object passed to `run`\n * @api public\n */\n\n define(app, 'run', function(val) {\n if (!isObject(val)) return;\n\n if (!val.use || !val.run) {\n define(val, prop, val[prop] || []);\n define(val, 'use', use);\n }\n\n if (!val[prop] || val[prop].indexOf(base) === -1) {\n val.use(base);\n }\n\n var self = this || app;\n var fns = self[prop];\n var len = fns.length;\n var idx = -1;\n\n while (++idx < len) {\n val.use(fns[idx]);\n }\n return val;\n });\n\n /**\n * Call plugin `fn`. If a function is returned push it into the\n * `fns` array to be called by the `run` method.\n */\n\n function use(type, fn, options) {\n var offset = 1;\n\n if (typeof type === 'string' || Array.isArray(type)) {\n fn = wrap(type, fn);\n offset++;\n } else {\n options = fn;\n fn = type;\n }\n\n if (typeof fn !== 'function') {\n throw new TypeError('expected a function');\n }\n\n var self = this || app;\n var fns = self[prop];\n\n var args = [].slice.call(arguments, offset);\n args.unshift(self);\n\n if (typeof opts.hook === 'function') {\n opts.hook.apply(self, args);\n }\n\n var val = fn.apply(self, args);\n if (typeof val === 'function' && fns.indexOf(val) === -1) {\n fns.push(val);\n }\n return self;\n }\n\n /**\n * Wrap a named plugin function so that it's only called on objects of the\n * given `type`\n *\n * @param {String} `type`\n * @param {Function} `fn` Plugin function\n * @return {Function}\n */\n\n function wrap(type, fn) {\n return function plugin() {\n return this.type === type ? fn.apply(this, arguments) : plugin;\n };\n }\n\n return app;\n};\n\nfunction isObject(val) {\n return val && typeof val === 'object' && !Array.isArray(val);\n}\n\nfunction define(obj, key, val) {\n Object.defineProperty(obj, key, {\n configurable: true,\n writable: true,\n value: val\n });\n}\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/use/index.js?"); + +/***/ }), + +/***/ "./node_modules/util-deprecate/node.js": +/*!*********************************************!*\ + !*** ./node_modules/util-deprecate/node.js ***! + \*********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("\n/**\n * For Node.js, simply re-export the core `util.deprecate` function.\n */\n\nmodule.exports = __webpack_require__(/*! util */ \"util\").deprecate;\n\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/util-deprecate/node.js?"); + +/***/ }), + +/***/ "assert": +/*!*************************!*\ + !*** external "assert" ***! + \*************************/ +/***/ ((module) => { + +"use strict"; +module.exports = require("assert"); + +/***/ }), + +/***/ "buffer": +/*!*************************!*\ + !*** external "buffer" ***! + \*************************/ +/***/ ((module) => { + +"use strict"; +module.exports = require("buffer"); + +/***/ }), + +/***/ "constants": +/*!****************************!*\ + !*** external "constants" ***! + \****************************/ +/***/ ((module) => { + +"use strict"; +module.exports = require("constants"); + +/***/ }), + +/***/ "events": +/*!*************************!*\ + !*** external "events" ***! + \*************************/ +/***/ ((module) => { + +"use strict"; +module.exports = require("events"); + +/***/ }), + +/***/ "fs": +/*!*********************!*\ + !*** external "fs" ***! + \*********************/ +/***/ ((module) => { + +"use strict"; +module.exports = require("fs"); + +/***/ }), + +/***/ "net": +/*!**********************!*\ + !*** external "net" ***! + \**********************/ +/***/ ((module) => { + +"use strict"; +module.exports = require("net"); + +/***/ }), + +/***/ "os": +/*!*********************!*\ + !*** external "os" ***! + \*********************/ +/***/ ((module) => { + +"use strict"; +module.exports = require("os"); + +/***/ }), + +/***/ "path": +/*!***********************!*\ + !*** external "path" ***! + \***********************/ +/***/ ((module) => { + +"use strict"; +module.exports = require("path"); + +/***/ }), + +/***/ "stream": +/*!*************************!*\ + !*** external "stream" ***! + \*************************/ +/***/ ((module) => { + +"use strict"; +module.exports = require("stream"); + +/***/ }), + +/***/ "tty": +/*!**********************!*\ + !*** external "tty" ***! + \**********************/ +/***/ ((module) => { + +"use strict"; +module.exports = require("tty"); + +/***/ }), + +/***/ "url": +/*!**********************!*\ + !*** external "url" ***! + \**********************/ +/***/ ((module) => { + +"use strict"; +module.exports = require("url"); + +/***/ }), + +/***/ "util": +/*!***********************!*\ + !*** external "util" ***! + \***********************/ +/***/ ((module) => { + +"use strict"; +module.exports = require("util"); + +/***/ }), + +/***/ "./node_modules/binary-extensions/binary-extensions.json": +/*!***************************************************************!*\ + !*** ./node_modules/binary-extensions/binary-extensions.json ***! + \***************************************************************/ +/***/ ((module) => { + +"use strict"; +eval("module.exports = JSON.parse('[\"3dm\",\"3ds\",\"3g2\",\"3gp\",\"7z\",\"a\",\"aac\",\"adp\",\"ai\",\"aif\",\"aiff\",\"alz\",\"ape\",\"apk\",\"ar\",\"arj\",\"asf\",\"au\",\"avi\",\"bak\",\"baml\",\"bh\",\"bin\",\"bk\",\"bmp\",\"btif\",\"bz2\",\"bzip2\",\"cab\",\"caf\",\"cgm\",\"class\",\"cmx\",\"cpio\",\"cr2\",\"cur\",\"dat\",\"dcm\",\"deb\",\"dex\",\"djvu\",\"dll\",\"dmg\",\"dng\",\"doc\",\"docm\",\"docx\",\"dot\",\"dotm\",\"dra\",\"DS_Store\",\"dsk\",\"dts\",\"dtshd\",\"dvb\",\"dwg\",\"dxf\",\"ecelp4800\",\"ecelp7470\",\"ecelp9600\",\"egg\",\"eol\",\"eot\",\"epub\",\"exe\",\"f4v\",\"fbs\",\"fh\",\"fla\",\"flac\",\"fli\",\"flv\",\"fpx\",\"fst\",\"fvt\",\"g3\",\"gh\",\"gif\",\"graffle\",\"gz\",\"gzip\",\"h261\",\"h263\",\"h264\",\"icns\",\"ico\",\"ief\",\"img\",\"ipa\",\"iso\",\"jar\",\"jpeg\",\"jpg\",\"jpgv\",\"jpm\",\"jxr\",\"key\",\"ktx\",\"lha\",\"lib\",\"lvp\",\"lz\",\"lzh\",\"lzma\",\"lzo\",\"m3u\",\"m4a\",\"m4v\",\"mar\",\"mdi\",\"mht\",\"mid\",\"midi\",\"mj2\",\"mka\",\"mkv\",\"mmr\",\"mng\",\"mobi\",\"mov\",\"movie\",\"mp3\",\"mp4\",\"mp4a\",\"mpeg\",\"mpg\",\"mpga\",\"mxu\",\"nef\",\"npx\",\"numbers\",\"nupkg\",\"o\",\"oga\",\"ogg\",\"ogv\",\"otf\",\"pages\",\"pbm\",\"pcx\",\"pdb\",\"pdf\",\"pea\",\"pgm\",\"pic\",\"png\",\"pnm\",\"pot\",\"potm\",\"potx\",\"ppa\",\"ppam\",\"ppm\",\"pps\",\"ppsm\",\"ppsx\",\"ppt\",\"pptm\",\"pptx\",\"psd\",\"pya\",\"pyc\",\"pyo\",\"pyv\",\"qt\",\"rar\",\"ras\",\"raw\",\"resources\",\"rgb\",\"rip\",\"rlc\",\"rmf\",\"rmvb\",\"rtf\",\"rz\",\"s3m\",\"s7z\",\"scpt\",\"sgi\",\"shar\",\"sil\",\"sketch\",\"slk\",\"smv\",\"snk\",\"so\",\"stl\",\"suo\",\"sub\",\"swf\",\"tar\",\"tbz\",\"tbz2\",\"tga\",\"tgz\",\"thmx\",\"tif\",\"tiff\",\"tlz\",\"ttc\",\"ttf\",\"txz\",\"udf\",\"uvh\",\"uvi\",\"uvm\",\"uvp\",\"uvs\",\"uvu\",\"viv\",\"vob\",\"war\",\"wav\",\"wax\",\"wbmp\",\"wdp\",\"weba\",\"webm\",\"webp\",\"whl\",\"wim\",\"wm\",\"wma\",\"wmv\",\"wmx\",\"woff\",\"woff2\",\"wrm\",\"wvx\",\"xbm\",\"xif\",\"xla\",\"xlam\",\"xls\",\"xlsb\",\"xlsm\",\"xlsx\",\"xlt\",\"xltm\",\"xltx\",\"xm\",\"xmind\",\"xpi\",\"xpm\",\"xwd\",\"xz\",\"z\",\"zip\",\"zipx\"]');\n\n//# sourceURL=webpack://@nicolo-ribaudo/chokidar-2/./node_modules/binary-extensions/binary-extensions.json?"); + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ +/******/ // startup +/******/ // Load entry module and return exports +/******/ // This entry module can't be inlined because the eval devtool is used. +/******/ var __webpack_exports__ = __webpack_require__("./chokidar/index.js"); +/******/ +/******/ })() +; \ No newline at end of file diff --git a/node_modules/@nicolo-ribaudo/chokidar-2/package.json b/node_modules/@nicolo-ribaudo/chokidar-2/package.json new file mode 100644 index 000000000..b67d94f37 --- /dev/null +++ b/node_modules/@nicolo-ribaudo/chokidar-2/package.json @@ -0,0 +1,36 @@ +{ + "name": "@nicolo-ribaudo/chokidar-2", + "version": "2.1.8-no-fsevents.3", + "description": "A wrapper around chokidar@2 to be able to specify both @2 and @3 as dependencies", + "main": "./dist/main.js", + "types": "./types.d.ts", + "scripts": { + "build": "./build-chokidar.sh", + "bundle": "webpack ./chokidar/index.js -o ./dist -t node --mode development" + }, + "dependencies": {}, + "author": "Nicolò Ribaudo ", + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "https://github.com/nicolo-ribaudo/chokidar-2" + }, + "devDependencies": { + "anymatch": "^2.0.0", + "async-each": "^1.0.1", + "braces": "^2.3.2", + "glob-parent": "^5.1.2", + "inherits": "^2.0.3", + "is-binary-path": "^1.0.0", + "is-glob": "^4.0.0", + "normalize-path": "^3.0.0", + "path-is-absolute": "^1.0.0", + "readdirp": "^2.2.1", + "upath": "^1.1.1", + "webpack": "^5.53.0", + "webpack-cli": "^4.8.0" + } +} diff --git a/node_modules/@nicolo-ribaudo/chokidar-2/types.d.ts b/node_modules/@nicolo-ribaudo/chokidar-2/types.d.ts new file mode 100644 index 000000000..9d3043f80 --- /dev/null +++ b/node_modules/@nicolo-ribaudo/chokidar-2/types.d.ts @@ -0,0 +1,191 @@ +// TypeScript Version: 3.0 + +/// + +import * as fs from "fs"; +import { EventEmitter } from "events"; + +/** + * The object's keys are all the directories (using absolute paths unless the `cwd` option was + * used), and the values are arrays of the names of the items contained in each directory. + */ +export interface WatchedPaths { + [directory: string]: string[]; +} + +export class FSWatcher extends EventEmitter implements fs.FSWatcher { + /** + * Constructs a new FSWatcher instance with optional WatchOptions parameter. + */ + constructor(options?: WatchOptions); + + /** + * Add files, directories, or glob patterns for tracking. Takes an array of strings or just one + * string. + */ + add(paths: string | string[]): void; + + /** + * Stop watching files, directories, or glob patterns. Takes an array of strings or just one + * string. + */ + unwatch(paths: string | string[]): void; + + /** + * Returns an object representing all the paths on the file system being watched by this + * `FSWatcher` instance. The object's keys are all the directories (using absolute paths unless + * the `cwd` option was used), and the values are arrays of the names of the items contained in + * each directory. + */ + getWatched(): WatchedPaths; + + /** + * Removes all listeners from watched files. + */ + close(): void; + + on(event: 'add'|'addDir'|'change', listener: (path: string, stats?: fs.Stats) => void): this; + + on(event: 'all', listener: (eventName: 'add'|'addDir'|'change'|'unlink'|'unlinkDir', path: string, stats?: fs.Stats) => void): this; + + /** + * Error occured + */ + on(event: 'error', listener: (error: Error) => void): this; + + /** + * Exposes the native Node `fs.FSWatcher events` + */ + on(event: 'raw', listener: (eventName: string, path: string, details: any) => void): this; + + /** + * Fires when the initial scan is complete + */ + on(event: 'ready', listener: () => void): this; + + on(event: 'unlink'|'unlinkDir', listener: (path: string) => void): this; + + on(event: string, listener: (...args: any[]) => void): this; +} + +export interface WatchOptions { + /** + * Indicates whether the process should continue to run as long as files are being watched. If + * set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`, + * even if the process continues to run. + */ + persistent?: boolean; + + /** + * ([anymatch](https://github.com/es128/anymatch)-compatible definition) Defines files/paths to + * be ignored. The whole relative or absolute path is tested, not just filename. If a function + * with two arguments is provided, it gets called twice per path - once with a single argument + * (the path), second time with two arguments (the path and the + * [`fs.Stats`](http://nodejs.org/api/fs.html#fs_class_fs_stats) object of that path). + */ + ignored?: any; + + /** + * If set to `false` then `add`/`addDir` events are also emitted for matching paths while + * instantiating the watching as chokidar discovers these file paths (before the `ready` event). + */ + ignoreInitial?: boolean; + + /** + * When `false`, only the symlinks themselves will be watched for changes instead of following + * the link references and bubbling events through the link's path. + */ + followSymlinks?: boolean; + + /** + * The base directory from which watch `paths` are to be derived. Paths emitted with events will + * be relative to this. + */ + cwd?: string; + + /** + * If set to true then the strings passed to .watch() and .add() are treated as literal path + * names, even if they look like globs. Default: false. + */ + disableGlobbing?: boolean; + + /** + * Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU + * utilization, consider setting this to `false`. It is typically necessary to **set this to + * `true` to successfully watch files over a network**, and it may be necessary to successfully + * watch files in other non-standard situations. Setting to `true` explicitly on OS X overrides + * the `useFsEvents` default. + */ + usePolling?: boolean; + + /** + * Whether to use the `fsevents` watching interface if available. When set to `true` explicitly + * and `fsevents` is available this supercedes the `usePolling` setting. When set to `false` on + * OS X, `usePolling: true` becomes the default. + */ + useFsEvents?: boolean; + + /** + * If relying upon the [`fs.Stats`](http://nodejs.org/api/fs.html#fs_class_fs_stats) object that + * may get passed with `add`, `addDir`, and `change` events, set this to `true` to ensure it is + * provided even in cases where it wasn't already available from the underlying watch events. + */ + alwaysStat?: boolean; + + /** + * If set, limits how many levels of subdirectories will be traversed. + */ + depth?: number; + + /** + * Interval of file system polling. + */ + interval?: number; + + /** + * Interval of file system polling for binary files. ([see list of binary extensions](https://gi + * thub.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json)) + */ + binaryInterval?: number; + + /** + * Indicates whether to watch files that don't have read permissions if possible. If watching + * fails due to `EPERM` or `EACCES` with this set to `true`, the errors will be suppressed + * silently. + */ + ignorePermissionErrors?: boolean; + + /** + * `true` if `useFsEvents` and `usePolling` are `false`). Automatically filters out artifacts + * that occur when using editors that use "atomic writes" instead of writing directly to the + * source file. If a file is re-added within 100 ms of being deleted, Chokidar emits a `change` + * event rather than `unlink` then `add`. If the default of 100 ms does not work well for you, + * you can override it by setting `atomic` to a custom value, in milliseconds. + */ + atomic?: boolean | number; + + /** + * can be set to an object in order to adjust timing params: + */ + awaitWriteFinish?: AwaitWriteFinishOptions | boolean; +} + +export interface AwaitWriteFinishOptions { + /** + * Amount of time in milliseconds for a file size to remain constant before emitting its event. + */ + stabilityThreshold?: number; + + /** + * File size polling interval. + */ + pollInterval?: number; +} + +/** + * produces an instance of `FSWatcher`. + */ +export function watch( + paths: string | string[], + options?: WatchOptions +): FSWatcher; diff --git a/node_modules/anymatch/index.d.ts b/node_modules/anymatch/index.d.ts index 196d06178..3ef7eaadd 100644 --- a/node_modules/anymatch/index.d.ts +++ b/node_modules/anymatch/index.d.ts @@ -10,6 +10,7 @@ type PicomatchOptions = {dot: boolean}; declare const anymatch: { (matchers: AnymatchMatcher): AnymatchTester; + (matchers: AnymatchMatcher, testString: null, returnIndex: true | PicomatchOptions): AnymatchTester; (matchers: AnymatchMatcher, testString: string|any[], returnIndex: true | PicomatchOptions): number; (matchers: AnymatchMatcher, testString: string|any[]): boolean; } diff --git a/node_modules/anymatch/index.js b/node_modules/anymatch/index.js index 24529c8a4..8eb73e9c9 100644 --- a/node_modules/anymatch/index.js +++ b/node_modules/anymatch/index.js @@ -47,7 +47,7 @@ const matchPatterns = (patterns, negPatterns, args, returnIndex) => { throw new TypeError('anymatch: second argument must be a string: got ' + Object.prototype.toString.call(_path)) } - const path = normalizePath(_path); + const path = normalizePath(_path, false); for (let index = 0; index < negPatterns.length; index++) { const nglob = negPatterns[index]; @@ -86,7 +86,9 @@ const anymatch = (matchers, testString, options = DEFAULT_OPTIONS) => { .filter(item => typeof item === 'string' && item.charAt(0) === BANG) .map(item => item.slice(1)) .map(item => picomatch(item, opts)); - const patterns = mtchers.map(matcher => createPattern(matcher, opts)); + const patterns = mtchers + .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG)) + .map(matcher => createPattern(matcher, opts)); if (testString == null) { return (testString, ri = false) => { diff --git a/node_modules/anymatch/package.json b/node_modules/anymatch/package.json index c55ee9436..2cb2307e4 100644 --- a/node_modules/anymatch/package.json +++ b/node_modules/anymatch/package.json @@ -1,53 +1,25 @@ { - "_from": "anymatch@^3.0.3", - "_id": "anymatch@3.1.1", - "_inBundle": false, - "_integrity": "sha512-mM8522psRCqzV+6LhomX5wgp25YVibjh8Wj23I5RPkPppSVSjyKD2A2mBJmWGa+KN7f2D6LNh9jkBCeyLktzjg==", - "_location": "/anymatch", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "anymatch@^3.0.3", - "name": "anymatch", - "escapedName": "anymatch", - "rawSpec": "^3.0.3", - "saveSpec": null, - "fetchSpec": "^3.0.3" - }, - "_requiredBy": [ - "/jest-haste-map" + "name": "anymatch", + "version": "3.1.3", + "description": "Matches strings against configurable strings, globs, regular expressions, and/or functions", + "files": [ + "index.js", + "index.d.ts" ], - "_resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.1.tgz", - "_shasum": "c55ecf02185e2469259399310c173ce31233b142", - "_spec": "anymatch@^3.0.3", - "_where": "/Users/hcliff/src/github-asana-action/node_modules/jest-haste-map", - "author": { - "name": "Elan Shanker", - "url": "https://github.com/es128" - }, - "bugs": { - "url": "https://github.com/micromatch/anymatch/issues" - }, - "bundleDependencies": false, "dependencies": { "normalize-path": "^3.0.0", "picomatch": "^2.0.4" }, - "deprecated": false, - "description": "Matches strings against configurable strings, globs, regular expressions, and/or functions", - "devDependencies": { - "mocha": "^6.1.3", - "nyc": "^14.0.0" - }, - "engines": { - "node": ">= 8" + "author": { + "name": "Elan Shanker", + "url": "https://github.com/es128" }, - "files": [ - "index.js", - "index.d.ts" - ], + "license": "ISC", "homepage": "https://github.com/micromatch/anymatch", + "repository": { + "type": "git", + "url": "https://github.com/micromatch/anymatch" + }, "keywords": [ "match", "any", @@ -62,15 +34,15 @@ "expression", "function" ], - "license": "ISC", - "name": "anymatch", - "repository": { - "type": "git", - "url": "git+https://github.com/micromatch/anymatch.git" - }, "scripts": { - "mocha": "mocha", - "test": "nyc mocha" + "test": "nyc mocha", + "mocha": "mocha" + }, + "devDependencies": { + "mocha": "^6.1.3", + "nyc": "^14.0.0" }, - "version": "3.1.1" + "engines": { + "node": ">= 8" + } } diff --git a/node_modules/asana/.babelrc b/node_modules/asana/.babelrc new file mode 100644 index 000000000..c73df9d50 --- /dev/null +++ b/node_modules/asana/.babelrc @@ -0,0 +1,33 @@ +{ + "presets": [ + "@babel/preset-env" + ], + "plugins": [ + "@babel/plugin-syntax-dynamic-import", + "@babel/plugin-syntax-import-meta", + "@babel/plugin-proposal-class-properties", + "@babel/plugin-proposal-json-strings", + [ + "@babel/plugin-proposal-decorators", + { + "legacy": true + } + ], + "@babel/plugin-proposal-function-sent", + "@babel/plugin-proposal-export-namespace-from", + "@babel/plugin-proposal-numeric-separator", + "@babel/plugin-proposal-throw-expressions", + "@babel/plugin-proposal-export-default-from", + "@babel/plugin-proposal-logical-assignment-operators", + "@babel/plugin-proposal-optional-chaining", + [ + "@babel/plugin-proposal-pipeline-operator", + { + "proposal": "minimal" + } + ], + "@babel/plugin-proposal-nullish-coalescing-operator", + "@babel/plugin-proposal-do-expressions", + "@babel/plugin-proposal-function-bind" + ] +} diff --git a/node_modules/asana/.github/workflows/publish.yaml b/node_modules/asana/.github/workflows/publish.yaml new file mode 100644 index 000000000..c584244d0 --- /dev/null +++ b/node_modules/asana/.github/workflows/publish.yaml @@ -0,0 +1,149 @@ +name: Generate Client Library + Publish 📦 to npmjs + Publish to GitHub Releases + +on: + workflow_dispatch: + inputs: + version: + required: true + +defaults: + run: + shell: bash + +permissions: + contents: read + id-token: write + +env: + GENERATOR_VERSION: 3.0.54 + GENERATOR_NAME: swagger-codegen-cli.jar + JAR_ASANA: codegen/swagger/target/AsanaClientCodegen-swagger-codegen-1.0.0.jar + ACTUAL_LANG: com.asana.codegen.JavascriptClientCodegenGenerator + NAME: asana + +jobs: + generate-javascript-library: + name: Generate JavaScript client library + runs-on: ubuntu-latest + steps: + - name: Authenticate to AWS + uses: aws-actions/configure-aws-credentials@v4 + with: + aws-region: us-east-1 + role-to-assume: arn:aws:iam::403483446840:role/autogen_role_beta_github_actions_release_asana_client_libraries + - name: Get GitHub app token + uses: asana/get-github-app-token@v1 + id: get-token + with: + github-app-name: asana-publish-client-libraries + - name: Checkout repo files and set the git token + uses: actions/checkout@v4 + with: + token: ${{ steps.get-token.outputs.app-token }} + - uses: actions/setup-java@v4 + with: + distribution: "temurin" + java-version: "17" + - name: Download generator + run: | + wget -q -O $GENERATOR_NAME https://repo1.maven.org/maven2/io/swagger/codegen/v3/swagger-codegen-cli/${{ env.GENERATOR_VERSION }}/swagger-codegen-cli-${{ env.GENERATOR_VERSION }}.jar + - name: Build custom code + run: | + pushd codegen/swagger >/dev/null + mvn package + popd >/dev/null + - name: Generate library + run: >- + java -cp "${{ env.JAR_ASANA }}:${{ env.GENERATOR_NAME }}" + io.swagger.codegen.v3.cli.SwaggerCodegen + generate + --input-spec https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_sdk_oas.yaml + --template-dir "codegen/templates" + --lang "${{ env.ACTUAL_LANG }}" + -DpackageName=${{ env.NAME }} + --additional-properties "projectVersion=${{ inputs.version }},projectName=${{ env.NAME }},packageName=${{ env.NAME }},usePromises=true,useES6=true" + - name: Clean up generator + run: rm -rf codegen/swagger/target ${{ env.GENERATOR_NAME }} + - name: Push changes to master branch + run: | + git config user.name asana-publish-client-libraries[bot] + git config user.email 159857493+asana-publish-client-libraries[bot]@users.noreply.github.com + git add . + git commit -m 'Updated JavaScript SDK: v${{ inputs.version }}' + git push origin master + git pull + git tag 'v${{ inputs.version }}' --force + git push origin --tags --force + publish-to-npmjs: + needs: generate-javascript-library + name: Build and publish 📦 to npmjs + runs-on: ubuntu-latest + steps: + - name: Authenticate to AWS + uses: aws-actions/configure-aws-credentials@v4 + with: + aws-region: us-east-1 + role-to-assume: arn:aws:iam::403483446840:role/autogen_role_beta_github_actions_release_asana_client_libraries + - name: Load secrets + uses: aws-actions/aws-secretsmanager-get-secrets@v1 + with: + secret-ids: NPM_API,prod/github_actions_release_asana_client_libraries/npm_api_key + # npm_api_key secret is stored as {key:"***..."}. + # GitHub Actions environment variable name is NPM_API so to access "key" from the json we can use NPM_API_KEY + parse-json-secrets: true + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + ref: master + - uses: actions/setup-node@v4 + with: + node-version: "18.x" + registry-url: "https://registry.npmjs.com" + - name: Build distribution + run: | + npm pkg set 'main'='dist/index.js' + npm pkg set 'scripts.build'='babel src -d dist' + npm pkg set 'scripts.prepare'='npm run build' + npm install + npm publish + env: + NODE_AUTH_TOKEN: ${{ env.NPM_API_KEY }} + publish-to-github-releases: + needs: publish-to-npmjs + name: Build and publish to GitHub Releases + runs-on: ubuntu-latest + steps: + - name: Authenticate to AWS + uses: aws-actions/configure-aws-credentials@v4 + with: + aws-region: us-east-1 + role-to-assume: arn:aws:iam::403483446840:role/autogen_role_beta_github_actions_release_asana_client_libraries + - name: Get GitHub app token + uses: asana/get-github-app-token@v1 + id: get-token + with: + github-app-name: asana-publish-client-libraries + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + ref: master + - uses: actions/setup-node@v4 + with: + node-version: "18.x" + registry-url: "https://registry.npmjs.com" + - name: Build distribution + run: | + npm pkg set 'main'='dist/index.js' + npm pkg set 'scripts.build'='babel src -d dist' + npm pkg set 'scripts.prepare'='npm run build' + npm install + - name: Bundle code for browser + run: | + npm install -g browserify + npm install -g uglify-js + browserify dist/index.js -s Asana | uglifyjs > dist/asana-min.js + browserify dist/index.js -s Asana > dist/asana.js + - name: Publish to GitHub Releases + run: gh release create v${{ inputs.version }} dist/asana.js dist/asana-min.js + env: + GH_TOKEN: ${{ steps.get-token.outputs.app-token }} diff --git a/node_modules/asana/.swagger-codegen-ignore b/node_modules/asana/.swagger-codegen-ignore index 2d1500626..c5fa491b4 100644 --- a/node_modules/asana/.swagger-codegen-ignore +++ b/node_modules/asana/.swagger-codegen-ignore @@ -1,3 +1,23 @@ # Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen -test/api/* +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/node_modules/asana/.swagger-codegen/VERSION b/node_modules/asana/.swagger-codegen/VERSION new file mode 100644 index 000000000..248908e60 --- /dev/null +++ b/node_modules/asana/.swagger-codegen/VERSION @@ -0,0 +1 @@ +3.0.54 \ No newline at end of file diff --git a/node_modules/asana/README.md b/node_modules/asana/README.md index 279e33cc8..0b1c18992 100644 --- a/node_modules/asana/README.md +++ b/node_modules/asana/README.md @@ -1,337 +1,1111 @@ -# Asana [![GitHub release][release-image]]() [![Build Status][travis-image]][travis-url] [![NPM Version][npm-image]][npm-url] +# asana [![GitHub release][release-image]][release-url] [![NPM Version][npm-image]][npm-url] -A JavaScript client (for both Node and browser) for the Asana API v1.0. +- API version: 1.0 +- Package version: 3.0.3 ## Installation -### Node +### For [Node.js](https://nodejs.org/) -Install with npm: +#### npm install from [npmjs](https://www.npmjs.com/package/asana) -```sh +```shell npm install asana --save ``` -### Browser +### For browser -Include the latest release directly from GitHub. +Include the latest release directly from GitHub: ```html - + ``` -**OR:** +Example usage (**NOTE**: be careful not to expose your access token): -1. Download the latest distribution in [releases](https://github.com/Asana/node-asana/releases). -2. Make sure to serve it from your webserver. -3. Include it on the client from a ` +``` -## Design Decisions +### Webpack Configuration + +Using Webpack you may encounter the following error: "Module not found: Error: +Cannot resolve module", most certainly you should disable AMD loader. Add/merge +the following section to your webpack config: + +```javascript +module: { + rules: [ + { + parser: { + amd: false + } + } + ] +} +``` + +## Getting Started -- **Thin Wrapper** This client is a thin wrapper, which means that the client - makes little attempt to verify the validity of the arguments locally. All errors - are reported by the server. We include custom Error types which contain - the response from the server. -- **Promises** Promises with [bluebird][bluebird] seem like the most neutral way - to support node's various async paradigms. If you want Promises, you get them - by default. If you want callbacks, bluebird promises support `nodeify`, which - takes a callback as parameter. For generators and streams, [co][co] and - [highland][highland] also support promises, respectively. Beyond that, other - major libraries such as mongoose, mocha, and elastic search (which uses - bluebird) also support Promises. +Please follow the [installation](#installation) instruction and execute the following JS code: -## Usage +```javascript +const Asana = require('asana'); -To do anything, you'll need always an instance of an `Asana.Client` configured -with your preferred authentication method (see the Authentication section below -for more complex scenarios) and other options. +let client = Asana.ApiClient.instance; +let token = client.authentications['token']; +token.accessToken = ''; -The most minimal example would be as follows: +let usersApiInstance = new Asana.UsersApi(); +let user_gid = "me"; // String | A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. +let opts = { + "opt_fields": "email,name,photo,photo.image_1024x1024,photo.image_128x128,photo.image_21x21,photo.image_27x27,photo.image_36x36,photo.image_60x60,workspaces,workspaces.name" // [String] | This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. +}; -```js -const asana = require('asana'); -const client = asana.Client.create().useAccessToken('my_access_token'); -client.users.me().then(function(me) { - console.log(me); +usersApiInstance.getUser(user_gid, opts).then((result) => { + console.log('API called successfully. Returned data: ' + JSON.stringify(result.data, null, 2)); +}, (error) => { + console.error(error.response.body); }); ``` -All resources are exposed as properties of the `Asana.Client` instance (e.g. `client.workspaces`). See the [developer documentation][api-reference] for docs on each of them. +### Example: GET, POST, PUT, DELETE on tasks -### Authentication +#### GET - get multiple tasks +```javascript +const Asana = require('asana'); -This module supports authenticating against the Asana API with either a Personal Access Token or through OAuth 2.0. +let client = Asana.ApiClient.instance; +let token = client.authentications['token']; +token.accessToken = ''; -#### Personal Access Token +let tasksApiInstance = new Asana.TasksApi(); +let opts = { + "limit": 50, // Number | Results per page. The number of objects to return per page. The value must be between 1 and 100. + "project": "", // String | The project to filter tasks on. + "modified_since": "2012-02-22T02:06:58.158Z", // Date | Only return tasks that have been modified since the given time. *Note: A task is considered “modified” if any of its properties change, or associations between it and other objects are modified (e.g. a task being added to a project). A task is not considered modified just because another object it is associated with (e.g. a subtask) is modified. Actions that count as modifying the task include assigning, renaming, completing, and adding stories.* + "opt_fields": "actual_time_minutes,approval_status,assignee,assignee.name,assignee_section,assignee_section.name,assignee_status,completed,completed_at,completed_by,completed_by.name,created_at,created_by,custom_fields,custom_fields.asana_created_field,custom_fields.created_by,custom_fields.created_by.name,custom_fields.currency_code,custom_fields.custom_label,custom_fields.custom_label_position,custom_fields.date_value,custom_fields.date_value.date,custom_fields.date_value.date_time,custom_fields.description,custom_fields.display_value,custom_fields.enabled,custom_fields.enum_options,custom_fields.enum_options.color,custom_fields.enum_options.enabled,custom_fields.enum_options.name,custom_fields.enum_value,custom_fields.enum_value.color,custom_fields.enum_value.enabled,custom_fields.enum_value.name,custom_fields.format,custom_fields.has_notifications_enabled,custom_fields.is_formula_field,custom_fields.is_global_to_workspace,custom_fields.is_value_read_only,custom_fields.multi_enum_values,custom_fields.multi_enum_values.color,custom_fields.multi_enum_values.enabled,custom_fields.multi_enum_values.name,custom_fields.name,custom_fields.number_value,custom_fields.people_value,custom_fields.people_value.name,custom_fields.precision,custom_fields.resource_subtype,custom_fields.text_value,custom_fields.type,dependencies,dependents,due_at,due_on,external,external.data,followers,followers.name,hearted,hearts,hearts.user,hearts.user.name,html_notes,is_rendered_as_separator,liked,likes,likes.user,likes.user.name,memberships,memberships.project,memberships.project.name,memberships.section,memberships.section.name,modified_at,name,notes,num_hearts,num_likes,num_subtasks,offset,parent,parent.created_by,parent.name,parent.resource_subtype,path,permalink_url,projects,projects.name,resource_subtype,start_at,start_on,tags,tags.name,uri,workspace,workspace.name" // [String] | This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. +}; -```js -const client = Asana.Client.create().useAccessToken('personal_access_token'); +// GET - get multiple tasks +tasksApiInstance.getTasks(opts).then((result) => { + console.log('API called successfully. Returned data: ' + JSON.stringify(result.data, null, 2)); +}, (error) => { + console.error(error.response.body); +}); ``` -#### OAuth 2.0 +#### POST - create a task +```javascript +const Asana = require('asana'); -Authenticating through OAuth2 is preferred. There are many ways you can do this. +let client = Asana.ApiClient.instance; +let token = client.authentications['token']; +token.accessToken = ''; + +let tasksApiInstance = new Asana.TasksApi(); +let body = { + "data": { + "name": "New Task", + "approval_status": "pending", + "assignee_status": "upcoming", + "completed": false, + "external": { + "gid": "1234", + "data": "A blob of information.", + }, + "html_notes": "Mittens really likes the stuff from Humboldt.", + "is_rendered_as_separator": false, + "liked": true, + "assignee": "me", + "projects": [""], + }, +}; +let opts = {}; -In all cases, you should create a `Client` that contains your app information. The values in the below snippet should be substituted with the real properties from your application's settings. +// POST - Create a task +tasksApiInstance.createTask(body, opts).then((result) => { + console.log('API called successfully. Returned data: ' + JSON.stringify(result.data, null, 2)); +}, (error) => { + console.error(error.response.body); +}); +``` + +#### PUT - update a task +```javascript +const Asana = require('asana'); + +let client = Asana.ApiClient.instance; +let token = client.authentications['token']; +token.accessToken = ''; -```js -const client = Asana.Client.create({ - clientId: 123, - clientSecret: 'my_client_secret', - redirectUri: 'my_redirect_uri' +let tasksApiInstance = new Asana.TasksApi(); +let task_gid = ""; +let body = { + "data": { + "name": "Updated Task", + }, +}; +let opts = {}; + +// PUT - Update a task +tasksApiInstance.updateTask(body, task_gid, opts).then((result) => { + console.log('API called successfully. Returned data: ' + JSON.stringify(result.data, null, 2)); +}, (error) => { + console.error(error.response.body); }); ``` -##### With a plain bearer token (doesn't support auto-refresh) +#### DELETE - delete a task +```javascript +const Asana = require('asana'); + +let client = Asana.ApiClient.instance; +let token = client.authentications['token']; +token.accessToken = ''; -If you have a plain bearer token obtained somewhere else and you don't mind not -having your token auto-refresh, you can authenticate with it as follows: +let tasksApiInstance = new Asana.TasksApi(); +let task_gid = ""; -```js -client.useOauth({ - credentials: 'my_access_token' +// DELETE - Delete a task +tasksApiInstance.deleteTask(task_gid).then((result) => { + console.log('API called successfully. Returned data: ' + JSON.stringify(result.data, null, 2)); +}, (error) => { + console.error(error.response.body); }); ``` -##### With a refresh token +## Documentation for API Endpoints + +All URIs are relative to *https://app.asana.com/api/1.0* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*Asana.AttachmentsApi* | [**createAttachmentForObject**](docs/AttachmentsApi.md#createAttachmentForObject) | **POST** /attachments | Upload an attachment +*Asana.AttachmentsApi* | [**deleteAttachment**](docs/AttachmentsApi.md#deleteAttachment) | **DELETE** /attachments/{attachment_gid} | Delete an attachment +*Asana.AttachmentsApi* | [**getAttachment**](docs/AttachmentsApi.md#getAttachment) | **GET** /attachments/{attachment_gid} | Get an attachment +*Asana.AttachmentsApi* | [**getAttachmentsForObject**](docs/AttachmentsApi.md#getAttachmentsForObject) | **GET** /attachments | Get attachments from an object +*Asana.AuditLogAPIApi* | [**getAuditLogEvents**](docs/AuditLogAPIApi.md#getAuditLogEvents) | **GET** /workspaces/{workspace_gid}/audit_log_events | Get audit log events +*Asana.BatchAPIApi* | [**createBatchRequest**](docs/BatchAPIApi.md#createBatchRequest) | **POST** /batch | Submit parallel requests +*Asana.CustomFieldSettingsApi* | [**getCustomFieldSettingsForPortfolio**](docs/CustomFieldSettingsApi.md#getCustomFieldSettingsForPortfolio) | **GET** /portfolios/{portfolio_gid}/custom_field_settings | Get a portfolio's custom fields +*Asana.CustomFieldSettingsApi* | [**getCustomFieldSettingsForProject**](docs/CustomFieldSettingsApi.md#getCustomFieldSettingsForProject) | **GET** /projects/{project_gid}/custom_field_settings | Get a project's custom fields +*Asana.CustomFieldsApi* | [**createCustomField**](docs/CustomFieldsApi.md#createCustomField) | **POST** /custom_fields | Create a custom field +*Asana.CustomFieldsApi* | [**createEnumOptionForCustomField**](docs/CustomFieldsApi.md#createEnumOptionForCustomField) | **POST** /custom_fields/{custom_field_gid}/enum_options | Create an enum option +*Asana.CustomFieldsApi* | [**deleteCustomField**](docs/CustomFieldsApi.md#deleteCustomField) | **DELETE** /custom_fields/{custom_field_gid} | Delete a custom field +*Asana.CustomFieldsApi* | [**getCustomField**](docs/CustomFieldsApi.md#getCustomField) | **GET** /custom_fields/{custom_field_gid} | Get a custom field +*Asana.CustomFieldsApi* | [**getCustomFieldsForWorkspace**](docs/CustomFieldsApi.md#getCustomFieldsForWorkspace) | **GET** /workspaces/{workspace_gid}/custom_fields | Get a workspace's custom fields +*Asana.CustomFieldsApi* | [**insertEnumOptionForCustomField**](docs/CustomFieldsApi.md#insertEnumOptionForCustomField) | **POST** /custom_fields/{custom_field_gid}/enum_options/insert | Reorder a custom field's enum +*Asana.CustomFieldsApi* | [**updateCustomField**](docs/CustomFieldsApi.md#updateCustomField) | **PUT** /custom_fields/{custom_field_gid} | Update a custom field +*Asana.CustomFieldsApi* | [**updateEnumOption**](docs/CustomFieldsApi.md#updateEnumOption) | **PUT** /enum_options/{enum_option_gid} | Update an enum option +*Asana.EventsApi* | [**getEvents**](docs/EventsApi.md#getEvents) | **GET** /events | Get events on a resource +*Asana.GoalRelationshipsApi* | [**addSupportingRelationship**](docs/GoalRelationshipsApi.md#addSupportingRelationship) | **POST** /goals/{goal_gid}/addSupportingRelationship | Add a supporting goal relationship +*Asana.GoalRelationshipsApi* | [**getGoalRelationship**](docs/GoalRelationshipsApi.md#getGoalRelationship) | **GET** /goal_relationships/{goal_relationship_gid} | Get a goal relationship +*Asana.GoalRelationshipsApi* | [**getGoalRelationships**](docs/GoalRelationshipsApi.md#getGoalRelationships) | **GET** /goal_relationships | Get goal relationships +*Asana.GoalRelationshipsApi* | [**removeSupportingRelationship**](docs/GoalRelationshipsApi.md#removeSupportingRelationship) | **POST** /goals/{goal_gid}/removeSupportingRelationship | Removes a supporting goal relationship +*Asana.GoalRelationshipsApi* | [**updateGoalRelationship**](docs/GoalRelationshipsApi.md#updateGoalRelationship) | **PUT** /goal_relationships/{goal_relationship_gid} | Update a goal relationship +*Asana.GoalsApi* | [**addFollowers**](docs/GoalsApi.md#addFollowers) | **POST** /goals/{goal_gid}/addFollowers | Add a collaborator to a goal +*Asana.GoalsApi* | [**createGoal**](docs/GoalsApi.md#createGoal) | **POST** /goals | Create a goal +*Asana.GoalsApi* | [**createGoalMetric**](docs/GoalsApi.md#createGoalMetric) | **POST** /goals/{goal_gid}/setMetric | Create a goal metric +*Asana.GoalsApi* | [**deleteGoal**](docs/GoalsApi.md#deleteGoal) | **DELETE** /goals/{goal_gid} | Delete a goal +*Asana.GoalsApi* | [**getGoal**](docs/GoalsApi.md#getGoal) | **GET** /goals/{goal_gid} | Get a goal +*Asana.GoalsApi* | [**getGoals**](docs/GoalsApi.md#getGoals) | **GET** /goals | Get goals +*Asana.GoalsApi* | [**getParentGoalsForGoal**](docs/GoalsApi.md#getParentGoalsForGoal) | **GET** /goals/{goal_gid}/parentGoals | Get parent goals from a goal +*Asana.GoalsApi* | [**removeFollowers**](docs/GoalsApi.md#removeFollowers) | **POST** /goals/{goal_gid}/removeFollowers | Remove a collaborator from a goal +*Asana.GoalsApi* | [**updateGoal**](docs/GoalsApi.md#updateGoal) | **PUT** /goals/{goal_gid} | Update a goal +*Asana.GoalsApi* | [**updateGoalMetric**](docs/GoalsApi.md#updateGoalMetric) | **POST** /goals/{goal_gid}/setMetricCurrentValue | Update a goal metric +*Asana.JobsApi* | [**getJob**](docs/JobsApi.md#getJob) | **GET** /jobs/{job_gid} | Get a job by id +*Asana.MembershipsApi* | [**createMembership**](docs/MembershipsApi.md#createMembership) | **POST** /memberships | Create a membership +*Asana.MembershipsApi* | [**deleteMembership**](docs/MembershipsApi.md#deleteMembership) | **DELETE** /memberships/{membership_gid} | Delete a membership +*Asana.MembershipsApi* | [**getMembership**](docs/MembershipsApi.md#getMembership) | **GET** /memberships/{membership_gid} | Get a membership +*Asana.MembershipsApi* | [**getMemberships**](docs/MembershipsApi.md#getMemberships) | **GET** /memberships | Get multiple memberships +*Asana.MembershipsApi* | [**updateMembership**](docs/MembershipsApi.md#updateMembership) | **PUT** /memberships/{membership_gid} | Update a membership +*Asana.OrganizationExportsApi* | [**createOrganizationExport**](docs/OrganizationExportsApi.md#createOrganizationExport) | **POST** /organization_exports | Create an organization export request +*Asana.OrganizationExportsApi* | [**getOrganizationExport**](docs/OrganizationExportsApi.md#getOrganizationExport) | **GET** /organization_exports/{organization_export_gid} | Get details on an org export request +*Asana.PortfolioMembershipsApi* | [**getPortfolioMembership**](docs/PortfolioMembershipsApi.md#getPortfolioMembership) | **GET** /portfolio_memberships/{portfolio_membership_gid} | Get a portfolio membership +*Asana.PortfolioMembershipsApi* | [**getPortfolioMemberships**](docs/PortfolioMembershipsApi.md#getPortfolioMemberships) | **GET** /portfolio_memberships | Get multiple portfolio memberships +*Asana.PortfolioMembershipsApi* | [**getPortfolioMembershipsForPortfolio**](docs/PortfolioMembershipsApi.md#getPortfolioMembershipsForPortfolio) | **GET** /portfolios/{portfolio_gid}/portfolio_memberships | Get memberships from a portfolio +*Asana.PortfoliosApi* | [**addCustomFieldSettingForPortfolio**](docs/PortfoliosApi.md#addCustomFieldSettingForPortfolio) | **POST** /portfolios/{portfolio_gid}/addCustomFieldSetting | Add a custom field to a portfolio +*Asana.PortfoliosApi* | [**addItemForPortfolio**](docs/PortfoliosApi.md#addItemForPortfolio) | **POST** /portfolios/{portfolio_gid}/addItem | Add a portfolio item +*Asana.PortfoliosApi* | [**addMembersForPortfolio**](docs/PortfoliosApi.md#addMembersForPortfolio) | **POST** /portfolios/{portfolio_gid}/addMembers | Add users to a portfolio +*Asana.PortfoliosApi* | [**createPortfolio**](docs/PortfoliosApi.md#createPortfolio) | **POST** /portfolios | Create a portfolio +*Asana.PortfoliosApi* | [**deletePortfolio**](docs/PortfoliosApi.md#deletePortfolio) | **DELETE** /portfolios/{portfolio_gid} | Delete a portfolio +*Asana.PortfoliosApi* | [**getItemsForPortfolio**](docs/PortfoliosApi.md#getItemsForPortfolio) | **GET** /portfolios/{portfolio_gid}/items | Get portfolio items +*Asana.PortfoliosApi* | [**getPortfolio**](docs/PortfoliosApi.md#getPortfolio) | **GET** /portfolios/{portfolio_gid} | Get a portfolio +*Asana.PortfoliosApi* | [**getPortfolios**](docs/PortfoliosApi.md#getPortfolios) | **GET** /portfolios | Get multiple portfolios +*Asana.PortfoliosApi* | [**removeCustomFieldSettingForPortfolio**](docs/PortfoliosApi.md#removeCustomFieldSettingForPortfolio) | **POST** /portfolios/{portfolio_gid}/removeCustomFieldSetting | Remove a custom field from a portfolio +*Asana.PortfoliosApi* | [**removeItemForPortfolio**](docs/PortfoliosApi.md#removeItemForPortfolio) | **POST** /portfolios/{portfolio_gid}/removeItem | Remove a portfolio item +*Asana.PortfoliosApi* | [**removeMembersForPortfolio**](docs/PortfoliosApi.md#removeMembersForPortfolio) | **POST** /portfolios/{portfolio_gid}/removeMembers | Remove users from a portfolio +*Asana.PortfoliosApi* | [**updatePortfolio**](docs/PortfoliosApi.md#updatePortfolio) | **PUT** /portfolios/{portfolio_gid} | Update a portfolio +*Asana.ProjectBriefsApi* | [**createProjectBrief**](docs/ProjectBriefsApi.md#createProjectBrief) | **POST** /projects/{project_gid}/project_briefs | Create a project brief +*Asana.ProjectBriefsApi* | [**deleteProjectBrief**](docs/ProjectBriefsApi.md#deleteProjectBrief) | **DELETE** /project_briefs/{project_brief_gid} | Delete a project brief +*Asana.ProjectBriefsApi* | [**getProjectBrief**](docs/ProjectBriefsApi.md#getProjectBrief) | **GET** /project_briefs/{project_brief_gid} | Get a project brief +*Asana.ProjectBriefsApi* | [**updateProjectBrief**](docs/ProjectBriefsApi.md#updateProjectBrief) | **PUT** /project_briefs/{project_brief_gid} | Update a project brief +*Asana.ProjectMembershipsApi* | [**getProjectMembership**](docs/ProjectMembershipsApi.md#getProjectMembership) | **GET** /project_memberships/{project_membership_gid} | Get a project membership +*Asana.ProjectMembershipsApi* | [**getProjectMembershipsForProject**](docs/ProjectMembershipsApi.md#getProjectMembershipsForProject) | **GET** /projects/{project_gid}/project_memberships | Get memberships from a project +*Asana.ProjectStatusesApi* | [**createProjectStatusForProject**](docs/ProjectStatusesApi.md#createProjectStatusForProject) | **POST** /projects/{project_gid}/project_statuses | Create a project status +*Asana.ProjectStatusesApi* | [**deleteProjectStatus**](docs/ProjectStatusesApi.md#deleteProjectStatus) | **DELETE** /project_statuses/{project_status_gid} | Delete a project status +*Asana.ProjectStatusesApi* | [**getProjectStatus**](docs/ProjectStatusesApi.md#getProjectStatus) | **GET** /project_statuses/{project_status_gid} | Get a project status +*Asana.ProjectStatusesApi* | [**getProjectStatusesForProject**](docs/ProjectStatusesApi.md#getProjectStatusesForProject) | **GET** /projects/{project_gid}/project_statuses | Get statuses from a project +*Asana.ProjectTemplatesApi* | [**deleteProjectTemplate**](docs/ProjectTemplatesApi.md#deleteProjectTemplate) | **DELETE** /project_templates/{project_template_gid} | Delete a project template +*Asana.ProjectTemplatesApi* | [**getProjectTemplate**](docs/ProjectTemplatesApi.md#getProjectTemplate) | **GET** /project_templates/{project_template_gid} | Get a project template +*Asana.ProjectTemplatesApi* | [**getProjectTemplates**](docs/ProjectTemplatesApi.md#getProjectTemplates) | **GET** /project_templates | Get multiple project templates +*Asana.ProjectTemplatesApi* | [**getProjectTemplatesForTeam**](docs/ProjectTemplatesApi.md#getProjectTemplatesForTeam) | **GET** /teams/{team_gid}/project_templates | Get a team's project templates +*Asana.ProjectTemplatesApi* | [**instantiateProject**](docs/ProjectTemplatesApi.md#instantiateProject) | **POST** /project_templates/{project_template_gid}/instantiateProject | Instantiate a project from a project template +*Asana.ProjectsApi* | [**addCustomFieldSettingForProject**](docs/ProjectsApi.md#addCustomFieldSettingForProject) | **POST** /projects/{project_gid}/addCustomFieldSetting | Add a custom field to a project +*Asana.ProjectsApi* | [**addFollowersForProject**](docs/ProjectsApi.md#addFollowersForProject) | **POST** /projects/{project_gid}/addFollowers | Add followers to a project +*Asana.ProjectsApi* | [**addMembersForProject**](docs/ProjectsApi.md#addMembersForProject) | **POST** /projects/{project_gid}/addMembers | Add users to a project +*Asana.ProjectsApi* | [**createProject**](docs/ProjectsApi.md#createProject) | **POST** /projects | Create a project +*Asana.ProjectsApi* | [**createProjectForTeam**](docs/ProjectsApi.md#createProjectForTeam) | **POST** /teams/{team_gid}/projects | Create a project in a team +*Asana.ProjectsApi* | [**createProjectForWorkspace**](docs/ProjectsApi.md#createProjectForWorkspace) | **POST** /workspaces/{workspace_gid}/projects | Create a project in a workspace +*Asana.ProjectsApi* | [**deleteProject**](docs/ProjectsApi.md#deleteProject) | **DELETE** /projects/{project_gid} | Delete a project +*Asana.ProjectsApi* | [**duplicateProject**](docs/ProjectsApi.md#duplicateProject) | **POST** /projects/{project_gid}/duplicate | Duplicate a project +*Asana.ProjectsApi* | [**getProject**](docs/ProjectsApi.md#getProject) | **GET** /projects/{project_gid} | Get a project +*Asana.ProjectsApi* | [**getProjects**](docs/ProjectsApi.md#getProjects) | **GET** /projects | Get multiple projects +*Asana.ProjectsApi* | [**getProjectsForTask**](docs/ProjectsApi.md#getProjectsForTask) | **GET** /tasks/{task_gid}/projects | Get projects a task is in +*Asana.ProjectsApi* | [**getProjectsForTeam**](docs/ProjectsApi.md#getProjectsForTeam) | **GET** /teams/{team_gid}/projects | Get a team's projects +*Asana.ProjectsApi* | [**getProjectsForWorkspace**](docs/ProjectsApi.md#getProjectsForWorkspace) | **GET** /workspaces/{workspace_gid}/projects | Get all projects in a workspace +*Asana.ProjectsApi* | [**getTaskCountsForProject**](docs/ProjectsApi.md#getTaskCountsForProject) | **GET** /projects/{project_gid}/task_counts | Get task count of a project +*Asana.ProjectsApi* | [**projectSaveAsTemplate**](docs/ProjectsApi.md#projectSaveAsTemplate) | **POST** /projects/{project_gid}/saveAsTemplate | Create a project template from a project +*Asana.ProjectsApi* | [**removeCustomFieldSettingForProject**](docs/ProjectsApi.md#removeCustomFieldSettingForProject) | **POST** /projects/{project_gid}/removeCustomFieldSetting | Remove a custom field from a project +*Asana.ProjectsApi* | [**removeFollowersForProject**](docs/ProjectsApi.md#removeFollowersForProject) | **POST** /projects/{project_gid}/removeFollowers | Remove followers from a project +*Asana.ProjectsApi* | [**removeMembersForProject**](docs/ProjectsApi.md#removeMembersForProject) | **POST** /projects/{project_gid}/removeMembers | Remove users from a project +*Asana.ProjectsApi* | [**updateProject**](docs/ProjectsApi.md#updateProject) | **PUT** /projects/{project_gid} | Update a project +*Asana.RulesApi* | [**triggerRule**](docs/RulesApi.md#triggerRule) | **POST** /rule_triggers/{rule_trigger_gid}/run | Trigger a rule +*Asana.SectionsApi* | [**addTaskForSection**](docs/SectionsApi.md#addTaskForSection) | **POST** /sections/{section_gid}/addTask | Add task to section +*Asana.SectionsApi* | [**createSectionForProject**](docs/SectionsApi.md#createSectionForProject) | **POST** /projects/{project_gid}/sections | Create a section in a project +*Asana.SectionsApi* | [**deleteSection**](docs/SectionsApi.md#deleteSection) | **DELETE** /sections/{section_gid} | Delete a section +*Asana.SectionsApi* | [**getSection**](docs/SectionsApi.md#getSection) | **GET** /sections/{section_gid} | Get a section +*Asana.SectionsApi* | [**getSectionsForProject**](docs/SectionsApi.md#getSectionsForProject) | **GET** /projects/{project_gid}/sections | Get sections in a project +*Asana.SectionsApi* | [**insertSectionForProject**](docs/SectionsApi.md#insertSectionForProject) | **POST** /projects/{project_gid}/sections/insert | Move or Insert sections +*Asana.SectionsApi* | [**updateSection**](docs/SectionsApi.md#updateSection) | **PUT** /sections/{section_gid} | Update a section +*Asana.StatusUpdatesApi* | [**createStatusForObject**](docs/StatusUpdatesApi.md#createStatusForObject) | **POST** /status_updates | Create a status update +*Asana.StatusUpdatesApi* | [**deleteStatus**](docs/StatusUpdatesApi.md#deleteStatus) | **DELETE** /status_updates/{status_update_gid} | Delete a status update +*Asana.StatusUpdatesApi* | [**getStatus**](docs/StatusUpdatesApi.md#getStatus) | **GET** /status_updates/{status_update_gid} | Get a status update +*Asana.StatusUpdatesApi* | [**getStatusesForObject**](docs/StatusUpdatesApi.md#getStatusesForObject) | **GET** /status_updates | Get status updates from an object +*Asana.StoriesApi* | [**createStoryForTask**](docs/StoriesApi.md#createStoryForTask) | **POST** /tasks/{task_gid}/stories | Create a story on a task +*Asana.StoriesApi* | [**deleteStory**](docs/StoriesApi.md#deleteStory) | **DELETE** /stories/{story_gid} | Delete a story +*Asana.StoriesApi* | [**getStoriesForTask**](docs/StoriesApi.md#getStoriesForTask) | **GET** /tasks/{task_gid}/stories | Get stories from a task +*Asana.StoriesApi* | [**getStory**](docs/StoriesApi.md#getStory) | **GET** /stories/{story_gid} | Get a story +*Asana.StoriesApi* | [**updateStory**](docs/StoriesApi.md#updateStory) | **PUT** /stories/{story_gid} | Update a story +*Asana.TagsApi* | [**createTag**](docs/TagsApi.md#createTag) | **POST** /tags | Create a tag +*Asana.TagsApi* | [**createTagForWorkspace**](docs/TagsApi.md#createTagForWorkspace) | **POST** /workspaces/{workspace_gid}/tags | Create a tag in a workspace +*Asana.TagsApi* | [**deleteTag**](docs/TagsApi.md#deleteTag) | **DELETE** /tags/{tag_gid} | Delete a tag +*Asana.TagsApi* | [**getTag**](docs/TagsApi.md#getTag) | **GET** /tags/{tag_gid} | Get a tag +*Asana.TagsApi* | [**getTags**](docs/TagsApi.md#getTags) | **GET** /tags | Get multiple tags +*Asana.TagsApi* | [**getTagsForTask**](docs/TagsApi.md#getTagsForTask) | **GET** /tasks/{task_gid}/tags | Get a task's tags +*Asana.TagsApi* | [**getTagsForWorkspace**](docs/TagsApi.md#getTagsForWorkspace) | **GET** /workspaces/{workspace_gid}/tags | Get tags in a workspace +*Asana.TagsApi* | [**updateTag**](docs/TagsApi.md#updateTag) | **PUT** /tags/{tag_gid} | Update a tag +*Asana.TaskTemplatesApi* | [**deleteTaskTemplate**](docs/TaskTemplatesApi.md#deleteTaskTemplate) | **DELETE** /task_templates/{task_template_gid} | Delete a task template +*Asana.TaskTemplatesApi* | [**getTaskTemplate**](docs/TaskTemplatesApi.md#getTaskTemplate) | **GET** /task_templates/{task_template_gid} | Get a task template +*Asana.TaskTemplatesApi* | [**getTaskTemplates**](docs/TaskTemplatesApi.md#getTaskTemplates) | **GET** /task_templates | Get multiple task templates +*Asana.TaskTemplatesApi* | [**instantiateTask**](docs/TaskTemplatesApi.md#instantiateTask) | **POST** /task_templates/{task_template_gid}/instantiateTask | Instantiate a task from a task template +*Asana.TasksApi* | [**addDependenciesForTask**](docs/TasksApi.md#addDependenciesForTask) | **POST** /tasks/{task_gid}/addDependencies | Set dependencies for a task +*Asana.TasksApi* | [**addDependentsForTask**](docs/TasksApi.md#addDependentsForTask) | **POST** /tasks/{task_gid}/addDependents | Set dependents for a task +*Asana.TasksApi* | [**addFollowersForTask**](docs/TasksApi.md#addFollowersForTask) | **POST** /tasks/{task_gid}/addFollowers | Add followers to a task +*Asana.TasksApi* | [**addProjectForTask**](docs/TasksApi.md#addProjectForTask) | **POST** /tasks/{task_gid}/addProject | Add a project to a task +*Asana.TasksApi* | [**addTagForTask**](docs/TasksApi.md#addTagForTask) | **POST** /tasks/{task_gid}/addTag | Add a tag to a task +*Asana.TasksApi* | [**createSubtaskForTask**](docs/TasksApi.md#createSubtaskForTask) | **POST** /tasks/{task_gid}/subtasks | Create a subtask +*Asana.TasksApi* | [**createTask**](docs/TasksApi.md#createTask) | **POST** /tasks | Create a task +*Asana.TasksApi* | [**deleteTask**](docs/TasksApi.md#deleteTask) | **DELETE** /tasks/{task_gid} | Delete a task +*Asana.TasksApi* | [**duplicateTask**](docs/TasksApi.md#duplicateTask) | **POST** /tasks/{task_gid}/duplicate | Duplicate a task +*Asana.TasksApi* | [**getDependenciesForTask**](docs/TasksApi.md#getDependenciesForTask) | **GET** /tasks/{task_gid}/dependencies | Get dependencies from a task +*Asana.TasksApi* | [**getDependentsForTask**](docs/TasksApi.md#getDependentsForTask) | **GET** /tasks/{task_gid}/dependents | Get dependents from a task +*Asana.TasksApi* | [**getSubtasksForTask**](docs/TasksApi.md#getSubtasksForTask) | **GET** /tasks/{task_gid}/subtasks | Get subtasks from a task +*Asana.TasksApi* | [**getTask**](docs/TasksApi.md#getTask) | **GET** /tasks/{task_gid} | Get a task +*Asana.TasksApi* | [**getTaskForCustomID**](docs/TasksApi.md#getTaskForCustomID) | **GET** /workspaces/{workspace_gid}/tasks/custom_id/{custom_id} | Get a task for a given custom ID +*Asana.TasksApi* | [**getTasks**](docs/TasksApi.md#getTasks) | **GET** /tasks | Get multiple tasks +*Asana.TasksApi* | [**getTasksForProject**](docs/TasksApi.md#getTasksForProject) | **GET** /projects/{project_gid}/tasks | Get tasks from a project +*Asana.TasksApi* | [**getTasksForSection**](docs/TasksApi.md#getTasksForSection) | **GET** /sections/{section_gid}/tasks | Get tasks from a section +*Asana.TasksApi* | [**getTasksForTag**](docs/TasksApi.md#getTasksForTag) | **GET** /tags/{tag_gid}/tasks | Get tasks from a tag +*Asana.TasksApi* | [**getTasksForUserTaskList**](docs/TasksApi.md#getTasksForUserTaskList) | **GET** /user_task_lists/{user_task_list_gid}/tasks | Get tasks from a user task list +*Asana.TasksApi* | [**removeDependenciesForTask**](docs/TasksApi.md#removeDependenciesForTask) | **POST** /tasks/{task_gid}/removeDependencies | Unlink dependencies from a task +*Asana.TasksApi* | [**removeDependentsForTask**](docs/TasksApi.md#removeDependentsForTask) | **POST** /tasks/{task_gid}/removeDependents | Unlink dependents from a task +*Asana.TasksApi* | [**removeFollowerForTask**](docs/TasksApi.md#removeFollowerForTask) | **POST** /tasks/{task_gid}/removeFollowers | Remove followers from a task +*Asana.TasksApi* | [**removeProjectForTask**](docs/TasksApi.md#removeProjectForTask) | **POST** /tasks/{task_gid}/removeProject | Remove a project from a task +*Asana.TasksApi* | [**removeTagForTask**](docs/TasksApi.md#removeTagForTask) | **POST** /tasks/{task_gid}/removeTag | Remove a tag from a task +*Asana.TasksApi* | [**searchTasksForWorkspace**](docs/TasksApi.md#searchTasksForWorkspace) | **GET** /workspaces/{workspace_gid}/tasks/search | Search tasks in a workspace +*Asana.TasksApi* | [**setParentForTask**](docs/TasksApi.md#setParentForTask) | **POST** /tasks/{task_gid}/setParent | Set the parent of a task +*Asana.TasksApi* | [**updateTask**](docs/TasksApi.md#updateTask) | **PUT** /tasks/{task_gid} | Update a task +*Asana.TeamMembershipsApi* | [**getTeamMembership**](docs/TeamMembershipsApi.md#getTeamMembership) | **GET** /team_memberships/{team_membership_gid} | Get a team membership +*Asana.TeamMembershipsApi* | [**getTeamMemberships**](docs/TeamMembershipsApi.md#getTeamMemberships) | **GET** /team_memberships | Get team memberships +*Asana.TeamMembershipsApi* | [**getTeamMembershipsForTeam**](docs/TeamMembershipsApi.md#getTeamMembershipsForTeam) | **GET** /teams/{team_gid}/team_memberships | Get memberships from a team +*Asana.TeamMembershipsApi* | [**getTeamMembershipsForUser**](docs/TeamMembershipsApi.md#getTeamMembershipsForUser) | **GET** /users/{user_gid}/team_memberships | Get memberships from a user +*Asana.TeamsApi* | [**addUserForTeam**](docs/TeamsApi.md#addUserForTeam) | **POST** /teams/{team_gid}/addUser | Add a user to a team +*Asana.TeamsApi* | [**createTeam**](docs/TeamsApi.md#createTeam) | **POST** /teams | Create a team +*Asana.TeamsApi* | [**getTeam**](docs/TeamsApi.md#getTeam) | **GET** /teams/{team_gid} | Get a team +*Asana.TeamsApi* | [**getTeamsForUser**](docs/TeamsApi.md#getTeamsForUser) | **GET** /users/{user_gid}/teams | Get teams for a user +*Asana.TeamsApi* | [**getTeamsForWorkspace**](docs/TeamsApi.md#getTeamsForWorkspace) | **GET** /workspaces/{workspace_gid}/teams | Get teams in a workspace +*Asana.TeamsApi* | [**removeUserForTeam**](docs/TeamsApi.md#removeUserForTeam) | **POST** /teams/{team_gid}/removeUser | Remove a user from a team +*Asana.TeamsApi* | [**updateTeam**](docs/TeamsApi.md#updateTeam) | **PUT** /teams/{team_gid} | Update a team +*Asana.TimePeriodsApi* | [**getTimePeriod**](docs/TimePeriodsApi.md#getTimePeriod) | **GET** /time_periods/{time_period_gid} | Get a time period +*Asana.TimePeriodsApi* | [**getTimePeriods**](docs/TimePeriodsApi.md#getTimePeriods) | **GET** /time_periods | Get time periods +*Asana.TimeTrackingEntriesApi* | [**createTimeTrackingEntry**](docs/TimeTrackingEntriesApi.md#createTimeTrackingEntry) | **POST** /tasks/{task_gid}/time_tracking_entries | Create a time tracking entry +*Asana.TimeTrackingEntriesApi* | [**deleteTimeTrackingEntry**](docs/TimeTrackingEntriesApi.md#deleteTimeTrackingEntry) | **DELETE** /time_tracking_entries/{time_tracking_entry_gid} | Delete a time tracking entry +*Asana.TimeTrackingEntriesApi* | [**getTimeTrackingEntriesForTask**](docs/TimeTrackingEntriesApi.md#getTimeTrackingEntriesForTask) | **GET** /tasks/{task_gid}/time_tracking_entries | Get time tracking entries for a task +*Asana.TimeTrackingEntriesApi* | [**getTimeTrackingEntry**](docs/TimeTrackingEntriesApi.md#getTimeTrackingEntry) | **GET** /time_tracking_entries/{time_tracking_entry_gid} | Get a time tracking entry +*Asana.TimeTrackingEntriesApi* | [**updateTimeTrackingEntry**](docs/TimeTrackingEntriesApi.md#updateTimeTrackingEntry) | **PUT** /time_tracking_entries/{time_tracking_entry_gid} | Update a time tracking entry +*Asana.TypeaheadApi* | [**typeaheadForWorkspace**](docs/TypeaheadApi.md#typeaheadForWorkspace) | **GET** /workspaces/{workspace_gid}/typeahead | Get objects via typeahead +*Asana.UserTaskListsApi* | [**getUserTaskList**](docs/UserTaskListsApi.md#getUserTaskList) | **GET** /user_task_lists/{user_task_list_gid} | Get a user task list +*Asana.UserTaskListsApi* | [**getUserTaskListForUser**](docs/UserTaskListsApi.md#getUserTaskListForUser) | **GET** /users/{user_gid}/user_task_list | Get a user's task list +*Asana.UsersApi* | [**getFavoritesForUser**](docs/UsersApi.md#getFavoritesForUser) | **GET** /users/{user_gid}/favorites | Get a user's favorites +*Asana.UsersApi* | [**getUser**](docs/UsersApi.md#getUser) | **GET** /users/{user_gid} | Get a user +*Asana.UsersApi* | [**getUsers**](docs/UsersApi.md#getUsers) | **GET** /users | Get multiple users +*Asana.UsersApi* | [**getUsersForTeam**](docs/UsersApi.md#getUsersForTeam) | **GET** /teams/{team_gid}/users | Get users in a team +*Asana.UsersApi* | [**getUsersForWorkspace**](docs/UsersApi.md#getUsersForWorkspace) | **GET** /workspaces/{workspace_gid}/users | Get users in a workspace or organization +*Asana.WebhooksApi* | [**createWebhook**](docs/WebhooksApi.md#createWebhook) | **POST** /webhooks | Establish a webhook +*Asana.WebhooksApi* | [**deleteWebhook**](docs/WebhooksApi.md#deleteWebhook) | **DELETE** /webhooks/{webhook_gid} | Delete a webhook +*Asana.WebhooksApi* | [**getWebhook**](docs/WebhooksApi.md#getWebhook) | **GET** /webhooks/{webhook_gid} | Get a webhook +*Asana.WebhooksApi* | [**getWebhooks**](docs/WebhooksApi.md#getWebhooks) | **GET** /webhooks | Get multiple webhooks +*Asana.WebhooksApi* | [**updateWebhook**](docs/WebhooksApi.md#updateWebhook) | **PUT** /webhooks/{webhook_gid} | Update a webhook +*Asana.WorkspaceMembershipsApi* | [**getWorkspaceMembership**](docs/WorkspaceMembershipsApi.md#getWorkspaceMembership) | **GET** /workspace_memberships/{workspace_membership_gid} | Get a workspace membership +*Asana.WorkspaceMembershipsApi* | [**getWorkspaceMembershipsForUser**](docs/WorkspaceMembershipsApi.md#getWorkspaceMembershipsForUser) | **GET** /users/{user_gid}/workspace_memberships | Get workspace memberships for a user +*Asana.WorkspaceMembershipsApi* | [**getWorkspaceMembershipsForWorkspace**](docs/WorkspaceMembershipsApi.md#getWorkspaceMembershipsForWorkspace) | **GET** /workspaces/{workspace_gid}/workspace_memberships | Get the workspace memberships for a workspace +*Asana.WorkspacesApi* | [**addUserForWorkspace**](docs/WorkspacesApi.md#addUserForWorkspace) | **POST** /workspaces/{workspace_gid}/addUser | Add a user to a workspace or organization +*Asana.WorkspacesApi* | [**getWorkspace**](docs/WorkspacesApi.md#getWorkspace) | **GET** /workspaces/{workspace_gid} | Get a workspace +*Asana.WorkspacesApi* | [**getWorkspaces**](docs/WorkspacesApi.md#getWorkspaces) | **GET** /workspaces | Get multiple workspaces +*Asana.WorkspacesApi* | [**removeUserForWorkspace**](docs/WorkspacesApi.md#removeUserForWorkspace) | **POST** /workspaces/{workspace_gid}/removeUser | Remove a user from a workspace or organization +*Asana.WorkspacesApi* | [**updateWorkspace**](docs/WorkspacesApi.md#updateWorkspace) | **PUT** /workspaces/{workspace_gid} | Update a workspace + +## Optional fields + +Our `opt_fields` feature allows you to request for properties of a resource that you want to be returned in the response (more information [here](https://developers.asana.com/docs/inputoutput-options)). + +**NOTE**: by default, endpoints that return an array of results (EX: [Get multiple tasks](https://developers.asana.com/reference/gettasks), [Get multiple projects](https://developers.asana.com/reference/getprojects)), will return a compact version of those results (EX: [Get multiple tasks](https://developers.asana.com/reference/gettasks) returns an array of [TaskCompact](https://developers.asana.com/reference/tasks#taskcompact) objects). + +### EX: [Get multiple tasks](https://developers.asana.com/reference/gettasks) / [**getTasks**](docs/TasksApi.md#getTasks) without `opt_fields` + +#### Example Request +```javascript +const Asana = require('asana'); -If you obtained a refresh token (from a previous authorization), you can use it together with your client -credentials to authenticate: +let client = Asana.ApiClient.instance; +let token = client.authentications['token']; +token.accessToken = ''; -```js -const credentials = { - // access_token: 'my_access_token', - refresh_token: 'my_refresh_token' +let tasksApiInstance = new Asana.TasksApi(); +let opts = { + "limit": 2, + "project": "" }; -client.useOauth({ - credentials: credentials + +// GET - get multiple tasks +tasksApiInstance.getTasks(opts).then((result) => { + console.log(JSON.stringify(result.data, null, 2)); +}, (error) => { + console.error(error.response.body); }); ``` -See `examples/oauth/webserver` for a working example of this. +#### Example Response +```javascript +[ + { + "gid": "123", + "name": "Task 1", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "456", + "name": "Task 2", + "resource_type": "task", + "resource_subtype": "default_task" + } +] +``` + +### EX: [Get multiple tasks](https://developers.asana.com/reference/gettasks) / [**getTasks**](docs/TasksApi.md#getTasks) with `opt_fields` + +#### Example Request +```javascript +const Asana = require('asana'); -#### Client OAuth +let client = Asana.ApiClient.instance; +let token = client.authentications['token']; +token.accessToken = ''; -Currently, Asana has removed support for implicit grant and client-side authorization code grant. To correctly implement -oauth in a browser, use your own server as the token exchange endpoint: +let tasksApiInstance = new Asana.TasksApi(); +let opts = { + "limit": 1, + "project": "", + "opt_fields": "actual_time_minutes,approval_status,assignee,assignee.name,assignee_section,assignee_section.name,assignee_status,completed,completed_at,completed_by,completed_by.name,created_at,created_by,custom_fields,custom_fields.asana_created_field,custom_fields.created_by,custom_fields.created_by.name,custom_fields.currency_code,custom_fields.custom_label,custom_fields.custom_label_position,custom_fields.date_value,custom_fields.date_value.date,custom_fields.date_value.date_time,custom_fields.description,custom_fields.display_value,custom_fields.enabled,custom_fields.enum_options,custom_fields.enum_options.color,custom_fields.enum_options.enabled,custom_fields.enum_options.name,custom_fields.enum_value,custom_fields.enum_value.color,custom_fields.enum_value.enabled,custom_fields.enum_value.name,custom_fields.format,custom_fields.has_notifications_enabled,custom_fields.is_formula_field,custom_fields.is_global_to_workspace,custom_fields.is_value_read_only,custom_fields.multi_enum_values,custom_fields.multi_enum_values.color,custom_fields.multi_enum_values.enabled,custom_fields.multi_enum_values.name,custom_fields.name,custom_fields.number_value,custom_fields.people_value,custom_fields.people_value.name,custom_fields.precision,custom_fields.resource_subtype,custom_fields.text_value,custom_fields.type,dependencies,dependents,due_at,due_on,external,external.data,followers,followers.name,hearted,hearts,hearts.user,hearts.user.name,html_notes,is_rendered_as_separator,liked,likes,likes.user,likes.user.name,memberships,memberships.project,memberships.project.name,memberships.section,memberships.section.name,modified_at,name,notes,num_hearts,num_likes,num_subtasks,offset,parent,parent.created_by,parent.name,parent.resource_subtype,path,permalink_url,projects,projects.name,resource_subtype,start_at,start_on,tags,tags.name,uri,workspace,workspace.name" +}; -```js -Asana.Client.create({ - clientId: clientId, - redirectUri: 'http://localhost:' + port + '/oauth_callback', - tokenExchangeEndpoint: 'https://my-app-server.io/oauth_token' - }); +// GET - get multiple tasks +tasksApiInstance.getTasks(opts).then((result) => { + console.log(JSON.stringify(result.data, null, 2)); +}, (error) => { + console.error(error.response.body); +}); ``` -When a request comes to your server, verify it's a valid request (either using your own login cookie, cors, etc.). Then -take the body, add your `client_secret` to it, and send a POST request with the body to -`https://app.asana.com/-/oauth_token`. This will give your server the access and refresh tokens. Either return the -access_token to the browser, or keep it on your server if your server handles requests to Asana. +#### Example Response +```javascript +[ + { + "gid": "129839839", + "actual_time_minutes": null, + "assignee": { + "gid": "120938293", + "name": "user@example.com" + }, + "assignee_status": "upcoming", + "assignee_section": { + "gid": "1094838938", + "name": "Recently assigned" + }, + "completed": false, + "completed_at": null, + "completed_by": null, + "created_at": "2023-01-01T20:31:21.717Z", + "created_by": { + "gid": "1201784467042440", + "resource_type": "user" + }, + "custom_fields": [ + { + "gid": "191859815", + "enabled": true, + "name": "Estimated time", + "description": "Asana-created. Estimate time to complete a task.", + "number_value": null, + "precision": 0, + "format": "duration", + "currency_code": null, + "custom_label": null, + "created_by": null, + "custom_label_position": null, + "display_value": null, + "resource_subtype": "number", + "is_formula_field": false, + "is_value_read_only": false, + "type": "number" + } + ], + "dependencies": [], + "dependents": [], + "due_at": "2025-01-20T02:06:58.000Z", + "due_on": "2025-01-19", + "followers": [ + { + "gid": "120938293", + "name": "user@example.com" + } + ], + "hearted": true, + "hearts": [ + { + "gid": "594849843", + "user": { + "gid": "120938293", + "name": "user@example.com" + } + } + ], + "html_notes": "Example task notes", + "is_rendered_as_separator": false, + "liked": true, + "likes": [ + { + "gid": "58303939", + "user": { + "gid": "120938293", + "name": "user@example.com" + } + } + ], + "memberships": [ + { + "project": { + "gid": "4567", + "name": "Example Project" + }, + "section": { + "gid": "8900", + "name": "Untitled section" + } + } + ], + "modified_at": "2023-01-25T21:24:06.996Z", + "name": "Task 1", + "notes": "Example task notes", + "num_hearts": 1, + "num_likes": 1, + "num_subtasks": 0, + "parent": null, + "permalink_url": "https://app.asana.com/0/58303939/129839839", + "projects": [ + { + "gid": "4567", + "name": "Example Project" + } + ], + "start_at": null, + "start_on": null, + "tags": [], + "resource_subtype": "default_task", + "workspace": { + "gid": "111111", + "name": "Example Workspace" + } + } +] +``` -Here is an [express example](https://github.com/Asana/devrel-examples/blob/master/javascript/pkce_oauth/server/index.js) -for AWS Lambda that works as an app server. +## Pagination -Your client side code will look similar to the [webserver](https://github.com/Asana/node-asana/blob/master/examples/oauth/webserver/oauth_webserver.js) -example, but with client side routing instead of express. +By default, endpoints that return an array of results (EX: [Get multiple tasks](https://developers.asana.com/reference/gettasks), [Get multiple projects](https://developers.asana.com/reference/getprojects)), will return a [Collection](src/utils/collection.js) object. +This collection object contains a `nextPage` method that can be used to fetch for the next page of results. **NOTE**: in order to use `nextPage` you must have provided a `limit` query parameter argument in the initial request. -### Collections +### Use case -Whenever you ask for a collection of resources, you will receive a `Collection` -object which gives you access to a page of results at a time. You can provide -a number of results per page to fetch, between `1` and `100`. +You may run into the following error when making a request to an endpoint that has >1000 results: -It defaults to `50` if you don't provide any. +> "The result is too large. You should use pagination (may require specifying a workspace)!" -```js -client.tasks.findByTag(tagId, { limit: 5 }).then(function(collection) { - console.log(collection.data); - // [ .. array of up to 5 task objects .. ] -}); -``` +In this scenario you will want to use pagaintion to gather your results. To do this, you will need to provide a `limit` query parameter argument in your request. This `limit` query parameter represents the number of results per page. NOTE: the `limit` can only be between 1 and 100. -Additionally, `Collection` has a few useful methods that can make them -more convenient to deal with. +EX: Pagination gather all resources +```javascript +const Asana = require('asana'); -#### Individual page iteration +let client = Asana.ApiClient.instance; +let token = client.authentications['token']; +token.accessToken = ''; -To get the next page of a collection, you do not have to manually construct -the next request. The `nextPage()` method takes care of this for you: +let tasksApiInstance = new Asana.TasksApi(); +let opts = { + "project": "", + "limit": 100, +}; -```js -client.tasks.findByTag(tagId).then(firstPage => { - console.log(firstPage.data); - firstPage.nextPage().then(secondPage => { - console.log(secondPage.data); - }); -}); -``` +async function getAllTasks(opts) { + let tasks = await tasksApiInstance.getTasks(opts).then(async (response) => { + let result = []; + let page = response; + while(true) { + // Add items on page to list of results + result = result.concat(page.data); + // Fetch the next page + page = await page.nextPage(); + // If the there is no data in the next page break from the loop + if (!page.data) { + break; + } + } + return result; + }, (error) => { + console.error(error.response.body); + }); + // Do something with the tasks. EX: print out results + console.log('Tasks: ' + JSON.stringify(tasks, null, 2)); +} -#### Automatic page iteration +getAllTasks(opts); -To automatically fetch a bunch of results and have the client transparently -request pages under the hood, use the `fetch()` method: +``` -```js -client.tasks.findByTag(tagId).then(collection => { - // Fetch up to 200 tasks, using multiple pages if necessary - collection.fetch(200).then(tasks => { - console.log(tasks); - }); -}); +Sample output: +```bash +Tasks: [ + { + "gid": "123", + "name": "task 1", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "456", + "name": "task 2", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "789", + "name": "task 3", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "101112", + "name": "task 4", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "131415", + "name": "task 5", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "161718", + "name": "task 6", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "192021", + "name": "task 7", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "222324", + "name": "task 8", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "252627", + "name": "task 9", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "282930", + "name": "task 10", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "313233", + "name": "task 11", + "resource_type": "task", + "resource_subtype": "default_task" + }, +] ``` -#### Streaming +EX: Pagination do something per page +```javascript +const Asana = require('asana'); -You can also construct a `stream` from a collection. This will transparently -(and lazily) fetch the items in the collection in pages as you iterate -through them. +let client = Asana.ApiClient.instance; +let token = client.authentications['token']; +token.accessToken = ''; -```js -client.tasks.findByTag(tagId).then(collection => { - collection.stream().on('data', task => { - console.log(task); - }); +let tasksApiInstance = new Asana.TasksApi(); +let opts = { + 'project': "", + "limit": 5, +}; + +let pageIndex = 1; + +tasksApiInstance.getTasks(opts).then(async (response) => { + let page = response; + while(true) { + // Do something with the page results + // EX: print the name of the tasks on that page + console.log(`Page ${pageIndex}: `); + page.data.forEach(task => { + console.log(` ${task.name}`); + }); + pageIndex += 1; + + page = await page.nextPage(); + // If the there is no data in the next page break from the loop + if (!page.data) { + break; + } + } +}, (error) => { + console.error(error.response.body); }); -``` -### Debugging +``` -To quickly debug raw requests. Set debug to true on the Asana dispatcher. -```js -client.dispatcher.debug(true); +Sample output: + +```bash +Page 1: + task 1 + task 2 + task 3 + task 4 + task 5 +Page 2: + task 6 + task 7 + task 8 + task 9 + task 10 +Page 3: + task 11 + task 12 + task 13 + task 14 + task 15 ``` -We use the [request](https://github.com/request/request) library under the hood, and this is equivalent to setting `request.debug = true;` -### Error handling +### Turning off Pagination -In any request against the Asana API, there a number of errors that could -arise. Those are well documented in the [Asana API Documentation][api-reference], and -are represented as exceptions under the namespace `Asana.errors`. +If you do not want a [Collection](src/utils/collection.js) object returned and want to implement your own pagination, you can disable pagination by setting `RETURN_COLLECTION` to `false`: -## Options +EX: Turning off pagination +```javascript +const Asana = require('asana'); + +let client = Asana.ApiClient.instance; +let token = client.authentications['token']; +token.accessToken = ''; + +// Turn off pagination +client.RETURN_COLLECTION = false; -To add global headers (like for our [deprecation framework](https://asana.com/developers/documentation/getting-started/deprecations)), you add them to the client. +let tasksApiInstance = new Asana.TasksApi(); +let opts = { + 'project': "", + 'limit': 1 +}; +tasksApiInstance.getTasks(opts).then((result) => { + console.log('API called successfully. Returned data: ' + JSON.stringify(result, null, 2)); +}) +``` -```js - asana.Client.create({"defaultHeaders": {"asana-enable": "string_ids,new_sections"}}); +Sample response: +``` +API called successfully. Returned data: { + "data": [ + { + "gid": "", + "name": "Task 1", + "resource_type": "task", + "resource_subtype": "default_task" + }, + ], + "next_page": { + "offset": "gjJl2xAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJib3JkZXJfcmHilbI6IltcIlZ5IixcIjlaWlhVMkkzUUdOoXcEIsMTIwNDYxNTc0NTypNDI3MF0iLCJpYXQiOjE2OTc4MjgsSkjjQsImV4cCI6MTY5NzgyOTM2NH0.5VuMfKvqexoEsKfoPFtayWBNWiKvfR7_hN6MJaaIkx8", + "path": "/tasks?project=123456&limit=1&offset=gjJl2xAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJib3JkZXJfcmHilbI6IltcIlZ5IixcIjlaWlhVMkkzUUdOoXcEIsMTIwNDYxNTc0NTypNDI3MF0iLCJpYXQiOjE2OTc4MjgsSkjjQsImV4cCI6MTY5NzgyOTM2NH0.5VuMfKvqexoEsKfoPFtayWBNWiKvfR7_hN6MJaaIkx8", + "uri": "https://app.asana.com/api/1.0/tasks?project=123456&limit=1&offset=gjJl2xAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJib3JkZXJfcmHilbI6IltcIlZ5IixcIjlaWlhVMkkzUUdOoXcEIsMTIwNDYxNTc0NTypNDI3MF0iLCJpYXQiOjE2OTc4MjgsSkjjQsImV4cCI6MTY5NzgyOTM2NH0.5VuMfKvqexoEsKfoPFtayWBNWiKvfR7_hN6MJaaIkx8" + } +} ``` -### Asana Change Warnings +## Getting events -You will receive warning logs if performing requests that may be affected by a deprecation. The warning contains a link that explains the deprecation. +In order to get events you will need a sync token. This sync token can be acquired in the error message from the initial +request to [getEvents](docs/EventsApi.md#getEvents). -If you receive one of these warnings, you should: -* Read about the deprecation. -* Resolve sections of your code that would be affected by the deprecation. -* Add the deprecation flag to your `"asana-enable"` header. +```javascript +const Asana = require('asana'); -If you would rather suppress these warnings, you can do the following: +let client = Asana.ApiClient.instance; +let token = client.authentications['token']; +token.accessToken = ''; -```js - asana.Client.create({"logAsanaChangeWarnings": false}); +let eventsApiInstance = new Asana.EventsApi(); +let resource = ""; // String | A resource ID to subscribe to. The resource can be a task or project. +let opts = { + "sync": "" +}; +const timeouts = 5000 + +// Used to fetch for initial sync token +const setSyncToken = async () => { + await eventsApiInstance.getEvents(resource, opts).then((result) => { + console.log(JSON.stringify(result.data, null, 2)); + }, (error) => { + let syncToken = error.response.body.sync; + opts['sync'] = syncToken; + }); +} + +const getEvents = async () => { + console.log("Setting sync token"); + await setSyncToken(); + // Fetch for new events every 5 seconds + console.log(`Fetching events every ${timeouts/1000} second(s)`); + while(true) { + await eventsApiInstance.getEvents(resource, opts).then((result) => { + // Print response + console.log(`Fetching events since sync: ${opts['sync']}`); + console.log(JSON.stringify(result.data, null, 2)); + + // Update the sync token with the new sync token provided in the response + opts['sync'] = result._response.sync; + }, (error) => { + if (error.status === 412) { + let syncToken = error.response.body.sync; + opts['sync'] = syncToken; + console.log(`412 error new sync token: ${syncToken}`); + } else{ + console.error(error.response.text); + } + }); + await new Promise(resolve => setTimeout(resolve, timeouts)); + } +} + +getEvents(); ``` -## Examples - -Various examples are in the repository under `examples/`, but some basic -concepts are illustrated here. +## Accessing repsonse data + +```javascript +. +. +. +tasksApiInstance.getTask(task_gid, opts).then((task) => { + let taskName = task.data.name; + let taskNotes = task.data.notes; + console.log(`taskName: ${taskName}`); + console.log(`taskNotes: ${taskNotes}`); +}, (error) => { + console.error(error.response.body); +}); +``` -### Find some incomplete tasks assigned to me that are new or marked for today in my default workspace +## Accessing response status code and headers +Use the `WithHttpInfo` (EX: `getTaskWithHttpInfo`) method to make a request that returns a response with headers. -```js +```javascript const Asana = require('asana'); -const util = require('util'); - -// Using a PAT for basic authentication. This is reasonable to get -// started with, but Oauth is more secure and provides more features. - -var client = Asana.Client.create().useAccessToken(process.env.ASANA_PAT); - -client.users.me() - .then(user => { - const userId = user.gid; - // The user's "default" workspace is the first one in the list, though - // any user can have multiple workspaces so you can't always assume this - // is the one you want to work with. - const workspaceId = user.workspaces[0].gid; - return client.tasks.findAll({ - assignee: userId, - workspace: workspaceId, - completed_since: 'now', - opt_fields: 'id,name,assignee_status,completed' - }); - }) - .then(response => { - // There may be more pages of data, we could stream or return a promise - // to request those here - for now, let's just return the first page - // of items. - return response.data; - }) - .filter(task => { - return task.assignee_status === 'today' || - task.assignee_status === 'new'; - }) - .then(list => { - console.log(util.inspect(list, { - colors: true, - depth: null - })); - }) - .catch(e => { - console.log(e); - }); + +let client = Asana.ApiClient.instance; +let token = client.authentications['token']; +token.accessToken = ''; + +let tasksApiInstance = new Asana.TasksApi(); +let task_gid = ""; +let opts = {}; + +tasksApiInstance.getTaskWithHttpInfo(task_gid, opts).then((response_and_data) => { + let data = response_and_data.data; + let response = response_and_data.response; + let task = data.data; + let headers = response.headers; + console.log(task); + console.log(headers); +}, (error) => { + console.error(error.response.body); +}); ``` -## Documentation +## Adding deprecation flag: "asana-enable" or "asana-disable" header -The code is thoroughly documented with JSDoc tags. The -[Official Asana Documentation][asana-doc] is a great resource, since this is -just a thin wrapper for the API. +EX: Asana-Enable header +```javascript +const Asana = require('asana'); -## Contributing +let client = Asana.ApiClient.instance; +let token = client.authentications['token']; +token.accessToken = ''; -Feel free to fork and submit pull requests for the code! Please follow the -existing code as an example of style, and make sure that all your code passes -lint and tests. +// Add asana-enable header for the client +client.defaultHeaders['asana-enable'] = 'new_goal_memberships'; +``` -For a sanity check: +EX: Asana-Disable header +```javascript +const Asana = require('asana'); -```sh -git clone git@github.com:Asana/node-asana.git -cd node-asana -npm install -npm test +let client = Asana.ApiClient.instance; +let token = client.authentications['token']; +token.accessToken = ''; + +// Add asana-disable header for the client +client.defaultHeaders['asana-disable'] = 'new_goal_memberships'; ``` -### Code generation +## Using the `callApi` method -The specific Asana resource classes within the gen folder (`Tag`, `Workspace`, `Task`, etc.) are -generated code, hence they shouldn't be modified by hand. +Use the `callApi` method to make http calls when the endpoint does not exist in the current library version or has bugs -See our [openapi spec][https://github.com/Asana/developer-docs/blob/master/defs/asana_oas.yaml] and [swagger](https://github.com/swagger-api/swagger-codegen) for details. +### Example: GET, POST, PUT, DELETE on tasks -### Deployment +#### GET - get a task +```javascript +const Asana = require('asana'); -**Repo Owners Only.** Take the following steps to issue a new release of the library. +let client = Asana.ApiClient.instance; +let token = client.authentications['token']; +token.accessToken = ''; + +// GET - get a task +client.callApi( + path='/tasks/{task_gid}', + httpMethod='GET', + pathParams={"task_gid": ""}, + queryParams={}, + headerParams={}, + formParams={}, + bodyParam=null, + authNames=['token'], + contentTypes=[], + accepts=['application/json; charset=UTF-8'], + returnType='Blob' +).then((response_and_data) => { + let result = response_and_data.data; + let task = result.data; + console.log(task.name); +}, (error) => { + console.error(error.response.body); +}); +``` - 1. Merge in the desired changes into the `master` branch and commit them. - 2. Clone the repo; work on `master`. - 3. Bump the package version to indicate the [semantic version](http://semver.org) change, using one of: `gulp bump-patch`, `gulp bump-feature`, or `gulp bump-release` - 4. Push changes to origin, including tags: - `git push origin master --tags` +#### GET - get multiple tasks -> with opt_fields +```javascript +const Asana = require('asana'); -Travis CI will automatically build and deploy the tagged release. +let client = Asana.ApiClient.instance; +let token = client.authentications['token']; +token.accessToken = ''; + +// GET - get multiple tasks -> with opt_fields +client.callApi( + path='/tasks', + httpMethod='GET', + pathParams={}, + queryParams={ + "limit": 50, + "modified_since": '2012-02-22T02:06:58.158Z', // OR new Date("2012-02-22T02:06:58.158Z") + "project": '', + "opt_fields": 'name,notes' + }, + headerParams={}, + formParams={}, + bodyParam=null, + authNames=['token'], + contentTypes=[], + accepts=['application/json; charset=UTF-8'], + returnType='Blob' +).then((response_and_data) => { + let result = response_and_data.data; + let tasks = result.data; + if (tasks.length > 0) { + console.log(`Task 1 Name: ${tasks[0].name}`); + console.log(`Task 1 Notes: ${tasks[0].notes}`); + } +}, (error) => { + console.error(error.response.body); +}); +``` -[release-image]: https://img.shields.io/github/release/asana/node-asana.svg +#### POST - create a task +```javascript +const Asana = require('asana'); -[travis-url]: http://travis-ci.org/Asana/node-asana -[travis-image]: http://img.shields.io/travis/Asana/node-asana.svg?style=flat-square&branch=master +let client = Asana.ApiClient.instance; +let token = client.authentications['token']; +token.accessToken = ''; + +// POST - create a task +client.callApi( + path='/tasks', + httpMethod='POST', + pathParams={}, + queryParams={}, + headerParams={}, + formParams={}, + bodyParam={ + data: { + "name": "New Task", + "approval_status": "pending", + "assignee_status": "upcoming", + "completed": false, + "html_notes": "Mittens really likes the stuff from Humboldt.", + "is_rendered_as_separator": false, + "liked": true, + "assignee": "me", + "projects": [""], + } + }, + authNames=['token'], + contentTypes=[], + accepts=['application/json; charset=UTF-8'], + returnType='Blob' +).then((response_and_data) => { + let result = response_and_data.data; + let task = result.data; + console.log(task.name); +}, (error) => { + console.error(error.response.body); +}); +``` -[npm-url]: https://www.npmjs.org/package/asana -[npm-image]: http://img.shields.io/npm/v/asana.svg?style=flat-square +#### PUT - update a task +```javascript +const Asana = require('asana'); + +let client = Asana.ApiClient.instance; +let token = client.authentications['token']; +token.accessToken = ''; + +// PUT - update a task +client.callApi( + path='/tasks/{task_gid}', + httpMethod='PUT', + pathParams={task_gid: ""}, + queryParams={}, + headerParams={}, + formParams={}, + bodyParam={ + "data": { + "name": "Updated Task", + "html_notes": "Updated task notes", + "due_at": "2025-01-20T02:06:58.147Z" + } + }, + authNames=['token'], + contentTypes=[], + accepts=['application/json; charset=UTF-8'], + returnType='Blob' +).then((response_and_data) => { + let result = response_and_data.data; + let task = result.data; + console.log(task.name); +}, (error) => { + console.error(error.response.body); +}); +``` -[bluebird]: https://github.com/petkaantonov/bluebird -[co]: https://github.com/visionmedia/co -[highland]: http://highlandjs.org/ +#### DELETE - delete a task +```javascript +const Asana = require('asana'); -[asana-docs]: https://developers.asana.com/docs +let client = Asana.ApiClient.instance; +let token = client.authentications['token']; +token.accessToken = ''; + +// DELETE - delete a task +client.callApi( + path='/tasks/{task_gid}', + httpMethod='DELETE', + pathParams={"task_gid": ""}, + queryParams={}, + headerParams={}, + formParams={}, + bodyParam=null, + authNames=['token'], + contentTypes=[], + accepts=['application/json; charset=UTF-8'], + returnType='Blob' +).then((response_and_data) => { + let result = response_and_data.data; + let result = result.data; + console.log(result); +}, (error) => { + console.error(error.response.body); +}); +``` + +[release-image]: https://img.shields.io/github/release/asana/node-asana.svg +[release-url]: https://github.com/Asana/node-asana/releases/tag/v3.0.3 +[npm-image]: http://img.shields.io/npm/v/asana.svg?style=flat-square +[npm-url]: https://www.npmjs.org/package/asana diff --git a/node_modules/asana/VERSION b/node_modules/asana/VERSION deleted file mode 100644 index fe5a2ce31..000000000 --- a/node_modules/asana/VERSION +++ /dev/null @@ -1 +0,0 @@ -0.18.5 \ No newline at end of file diff --git a/node_modules/asana/bower.json b/node_modules/asana/bower.json deleted file mode 100644 index a8e13ec87..000000000 --- a/node_modules/asana/bower.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "asana", - "main": "dist/asana.js", - "version": "0.15.1", - "homepage": "https://github.com/Asana/node-asana", - "authors": [ - "Greg Slovacek ", - "Phips Peter " - ], - "description": "A JavaScript client for the 1.0 version of the Asana API", - "moduleType": [ - "amd", - "globals", - "node" - ], - "keywords": [ - "asana", - "api", - "oauth" - ], - "license": "MIT", - "ignore": [ - "**/.*", - "node_modules", - "bower_components", - "test", - "tests" - ] -} diff --git a/node_modules/asana/build-tests/README.md b/node_modules/asana/build-tests/README.md new file mode 100644 index 000000000..cefabfd23 --- /dev/null +++ b/node_modules/asana/build-tests/README.md @@ -0,0 +1,19 @@ +# Test Build + +This directory contains tests that are meant to be ran locally + +1. Install dependencies: `npm i` + +2. Setup Environment Variables. Create a `.env` file within the root of the project directory with the following information + +``` +PERSONAL_ACCESS_TOKEN= +TEAM_GID= +TEXT_CUSTOM_FIELD_GID= -> NOTE: make sure that there is at least one task that has this custom field and the value of the custom field on that task is `custom_value` +USER_GID= +WORKSPACE_GID= +``` + +3. Run tests: `npm run testbuild` + +TIP: to debug, add `debugger;` to the location of the test code you want to debug and re-run `npm run testbuild` diff --git a/node_modules/asana/build-tests/api/ProjectsApi.js b/node_modules/asana/build-tests/api/ProjectsApi.js new file mode 100644 index 000000000..f1f56fb0c --- /dev/null +++ b/node_modules/asana/build-tests/api/ProjectsApi.js @@ -0,0 +1,178 @@ +(function (root, factory) { + if (typeof define === "function" && define.amd) { + // AMD. + define(["expect.js", "../../src/index"], factory); + } else if (typeof module === "object" && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require("expect.js"), require("../../src/index")); + } else { + // Browser globals (root is window) + factory(root.expect, root.Asana); + } +})(this, function (expect, Asana) { + "use strict"; + + var TEAM_GID; + var WORKSPACE_GID; + + var projectsApiInstance; + var project; + var projects; + + before(async function () { + require('dotenv').config() + TEAM_GID = process.env.TEAM_GID; + WORKSPACE_GID = process.env.WORKSPACE_GID; + + let client = Asana.ApiClient.instance; + let token = client.authentications["token"]; + token.accessToken = process.env.PERSONAL_ACCESS_TOKEN; + + projectsApiInstance = new Asana.ProjectsApi(); + }); + + describe("ProjectsApi", function () { + describe("createProject", function () { + it("should have created project", async function () { + let body = { + data: { + name: "Project 1", + notes: "Some description", + team: TEAM_GID, + }, + }; + + try { + project = await projectsApiInstance.createProject(body, {}); + } catch (error) { + throw error.response.body; + } + expect(project).to.be.ok(); + }); + it("should have a `name`", function () { + expect(project.data.name).to.be("Project 1"); + }); + it("should have a description/`notes`", function () { + expect(project.data.notes).to.be("Some description"); + }); + }); + describe("updateProject", function () { + it("should have updated project", async function () { + let body = { + data: { + name: "Project 1 - Updated", + notes: "Updated description", + }, + }; + + try { + project = await projectsApiInstance.updateProject( + body, + project.data.gid, + {} + ); + } catch (error) { + throw error.response.body; + } + expect(project).to.be.ok(); + }); + it("should have updated project `name`", function () { + expect(project.data.name).to.be("Project 1 - Updated"); + }); + it("should have updated project description/`notes`", function () { + expect(project.data.notes).to.be("Updated description"); + }); + }); + describe("getProject", function () { + it("should return project", async function () { + let response; + try { + response = await projectsApiInstance.getProject( + project.data.gid, + {} + ); + } catch (error) { + throw error.response.body; + } + expect(response).to.ok(); + }); + }); + describe("getProject with `opt_fields`", function () { + describe("ask for `html_notes` and `due_on` properties in `opt_fields`", function () { + it("should return project", async function () { + let opts = { + opt_fields: "html_notes,due_on", + }; + + try { + project = await projectsApiInstance.getProject( + project.data.gid, + opts + ); + } catch (error) { + throw error.response.body; + } + expect(project).to.ok(); + }); + it("should have `html_notes`", async function () { + expect(project.data.html_notes).not.to.equal(null); + }); + it("should have `due_on` with `null` value", async function () { + expect(project.data.due_on).to.be(null); + }); + }); + }); + describe("getProjects", function () { + it("should return an array of projects", async function () { + let opts = { + limit: 100, + workspace: WORKSPACE_GID, + }; + try { + projects = await projectsApiInstance.getProjects(opts); + } catch (error) { + throw error.response.body; + } + expect(projects).to.be.ok(); + expect(projects.data).to.be.an("array"); + }); + }); + describe("getProjects with `opt_fields`", function () { + describe("ask for `color` and `completed` properties in `opt_fields`", function () { + it("should return an array of projects", async function () { + let opts = { + workspace: WORKSPACE_GID, + opt_fields: "color,completed", + }; + + try { + projects = await projectsApiInstance.getProjects(opts); + } catch (error) { + throw error.response.body; + } + expect(projects).to.be.ok(); + expect(projects.data).to.be.an("array"); + }); + it("should have `workspace`", function () { + expect("color" in projects.data[0]).to.be(true); + }); + it("should have `completed`", function () { + expect("completed" in projects.data[0]).to.be(true); + }); + }); + }); + describe("deleteProject", function () { + it("should be deleted", async function () { + let response; + try { + response = await projectsApiInstance.deleteProject( + project.data.gid + ); + } catch (error) { + throw error.response.body; + } + expect(response.data).to.be.empty(); + }); + }); + }); +}); diff --git a/node_modules/asana/build-tests/api/TasksApi.js b/node_modules/asana/build-tests/api/TasksApi.js new file mode 100644 index 000000000..5e41b9e68 --- /dev/null +++ b/node_modules/asana/build-tests/api/TasksApi.js @@ -0,0 +1,260 @@ +// NOTE: Because these tests are making live API calls, we decided to write these tests in a particular order to optimize speed and reduce API calls. +// The down side to this approach is that these tests are tightly coupled. +(function (root, factory) { + if (typeof define === "function" && define.amd) { + // AMD. + define(["expect.js", "../../src/index"], factory); + } else if (typeof module === "object" && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require("expect.js"), require("../../src/index")); + } else { + // Browser globals (root is window) + factory(root.expect, root.Asana); + } +})(this, function (expect, Asana) { + "use strict"; + + var TEXT_CUSTOM_FIELD_GID; + var USER_GID; + var WORKSPACE_GID; + + var tasksApiInstance; + var task; + var tasks; + + before(async function () { + require('dotenv').config() + TEXT_CUSTOM_FIELD_GID = process.env.TEXT_CUSTOM_FIELD_GID; + USER_GID = process.env.USER_GID; + WORKSPACE_GID = process.env.WORKSPACE_GID; + + let client = Asana.ApiClient.instance; + let token = client.authentications["token"]; + token.accessToken = process.env.PERSONAL_ACCESS_TOKEN; + tasksApiInstance = new Asana.TasksApi(); + }); + + describe("TasksApi", function () { + describe("createTask", function () { + it("should have created task", async function () { + let body = { + data: { + assignee: USER_GID, + name: "Task 1", + notes: "Some description", + workspace: WORKSPACE_GID, + }, + }; + try { + task = await tasksApiInstance.createTask(body, {}); + } catch (error) { + throw error.response.body; + } + expect(task).to.be.ok(); + }); + it("should have a `name`", function () { + expect(task.data.name).to.be("Task 1"); + }); + it("should have a description/`notes`", function () { + expect(task.data.notes).to.be("Some description"); + }); + }); + describe("updateTask", function () { + it("should have updated task", async function () { + let body = { + data: { + name: "Task 1 - Updated", + notes: "Updated description", + }, + }; + try { + task = await tasksApiInstance.updateTask( + body, + task.data.gid, + {} + ); + } catch (error) { + throw error.response.body; + } + expect(task).to.be.ok(); + }); + it("should have updated task `name`", function () { + expect(task.data.name).to.be("Task 1 - Updated"); + }); + it("should have updated task description/`notes`", function () { + expect(task.data.notes).to.be("Updated description"); + }); + }); + describe("getTask", function () { + it("should return task", async function () { + let response; + try { + response = await tasksApiInstance.getTask( + task.data.gid, + {} + ); + } catch (error) { + throw error.response.body; + } + expect(response).to.ok(); + }); + }); + describe("getTask with `opt_fields`", function () { + describe("task for `html_notes` and `due_on` properties in `opt_fields`", function () { + it("should return task", async function () { + let opts = { + opt_fields: "html_notes,due_on", + }; + try { + task = await tasksApiInstance.getTask( + task.data.gid, + opts + ); + } catch (error) { + throw error.response.body; + } + expect(task).to.be.ok(); + }); + it("should have `html_notes`", function () { + expect(task.data.html_notes).not.to.equal(null); + }); + it("should have `due_on` with `null` value", function () { + expect(task.data.due_on).to.be(null); + }); + }); + }); + describe("getTasks", function () { + it("should return an array of tasks", async function () { + let tasksApiInstance = new Asana.TasksApi(); + let opts = { + limit: 100, + assignee: USER_GID, + workspace: WORKSPACE_GID, + }; + try { + tasks = await tasksApiInstance.getTasks(opts); + } catch (error) { + throw error.response.body; + } + expect(tasks).to.be.ok(); + expect(tasks.data).to.be.an("array"); + }); + }); + describe("getTasks with `opt_fields`", function () { + describe("ask for `workspace` and `due_on` properties in `opt_fields`", function () { + it("should return an array of tasks", async function () { + let tasksApiInstance = new Asana.TasksApi(); + let opts = { + assignee: USER_GID, + workspace: WORKSPACE_GID, + opt_fields: "workspace,due_on", + }; + + try { + tasks = await tasksApiInstance.getTasks(opts); + } catch (error) { + throw error.response.body; + } + expect(tasks).to.be.ok(); + expect(tasks.data).to.be.an("array"); + }); + it("should have `workspace`", function () { + expect(tasks.data[0].workspace).not.to.equal(null); + }); + it("should have `due_on`", function () { + expect("due_on" in tasks.data[0]).to.be(true); + }); + }); + }); + describe("getTasks limit 1", function () { + it("should return an array with 1 task", async function () { + let tasksApiInstance = new Asana.TasksApi(); + let opts = { + limit: 1, + assignee: USER_GID, + workspace: WORKSPACE_GID, + }; + + try { + tasks = await tasksApiInstance.getTasks(opts); + } catch (error) { + throw error.response.body; + } + expect(tasks.data.length).to.be(1); + expect(tasks.data).to.be.an("array"); + }); + }); + describe("searchTasksForWorkspace", function () { + it("should return an array of tasks", async function () { + let opts = { + text: "Task", + completed: false, + }; + + try { + tasks = await tasksApiInstance.searchTasksForWorkspace( + WORKSPACE_GID, + opts + ); + } catch (error) { + throw error.response.body; + } + expect(tasks).to.be.ok(); + expect(tasks.data).to.be.an("array"); + }); + }); + describe("searchTasksForWorkspace with custom field parameter - MATCH", function () { + it("should return an array with one task that has matching custom field value from search query", async function () { + let opts = { + limit: 1, + [`custom_fields.${TEXT_CUSTOM_FIELD_GID}.value`]: + "custom_value", + }; + + try { + tasks = await tasksApiInstance.searchTasksForWorkspace( + WORKSPACE_GID, + opts + ); + } catch (error) { + throw error.response.body; + } + expect(tasks).to.be.ok(); + expect(tasks.data.length).to.be(1); + }); + }); + describe("searchTasksForWorkspace with custom field parameter - NO MATCH", function () { + it("should return an empty array", async function () { + let opts = { + [`custom_fields.${TEXT_CUSTOM_FIELD_GID}.value`]: + "inimw8I23M4FRTPfApu1", + }; + + try { + tasks = await tasksApiInstance.searchTasksForWorkspace( + WORKSPACE_GID, + opts + ); + } catch (error) { + throw error.response.body; + } + expect(tasks.data).to.be.empty(); + }); + }); + describe("deleteTask", function () { + it("should be deleted", async function () { + let response; + try { + // NOTE: In the above tasks we are setting the global task variable in different tests. Make sure + // that future tests don't overwrite the original task created with another task otherwise + // that original task won't be deleted + response = await tasksApiInstance.deleteTask(task.data.gid); + } catch (error) { + throw error.response.body; + } + expect(response).to.be.ok(); + expect(response.data).to.be.empty(); + }); + }); + }); +}); diff --git a/node_modules/asana/codegen/swagger/README.md b/node_modules/asana/codegen/swagger/README.md new file mode 100644 index 000000000..ca6b3110d --- /dev/null +++ b/node_modules/asana/codegen/swagger/README.md @@ -0,0 +1,74 @@ +# Swagger Codegen for the AsanaPythonClientCodegen library + +## Overview +This is a boiler-plate project to generate your own client library with Swagger. Its goal is +to get you started with the basic plumbing so you can put in your own logic. It won't work without +your changes applied. + +## What's Swagger? +The goal of Swagger™ is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, Swagger removes the guesswork in calling the service. + + +Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the Swagger project, including additional libraries with support for other languages and more. + +## How do I use this? +At this point, you've likely generated a client setup. It will include something along these lines: + +``` +. +|- README.md // this file +|- pom.xml // build script +|-- src +|--- main +|---- java +|----- com.asana.codegen.AsanaPythonClientCodegenGenerator.java // generator file +|---- resources +|----- AsanaPythonClientCodegen // template files +|----- META-INF +|------ services +|------- io.swagger.codegen.CodegenConfig +``` + +You _will_ need to make changes in at least the following: + +`AsanaPythonClientCodegenGenerator.java` + +Templates in this folder: + +`src/main/resources/AsanaPythonClientCodegen` + +Once modified, you can run this: + +``` +mvn package +``` + +In your generator project. A single jar file will be produced in `target`. You can now use that with codegen: + +``` +java -cp /path/to/swagger-codegen-cli.jar:/path/to/your.jar io.swagger.codegen.v3.cli.SwaggerCodegen -l AsanaPythonClientCodegen -i /path/to/swagger.yaml -o ./test +``` + +Now your templates are available to the client generator and you can write output values + +## But how do I modify this? +The `ReadMe.java` has comments in it--lots of comments. There is no good substitute +for reading the code more, though. See how the `ReadMe` implements `CodegenConfig`. +That class has the signature of all values that can be overridden. + +For the templates themselves, you have a number of values available to you for generation. +You can execute the `java` command from above while passing different debug flags to show +the object you have available during client generation: + +``` +# The following additional debug options are available for all codegen targets: +# -DdebugSwagger prints the OpenAPI Specification as interpreted by the codegen +# -DdebugModels prints models passed to the template engine +# -DdebugOperations prints operations passed to the template engine +# -DdebugSupportingFiles prints additional data passed to the template engine + +java -DdebugOperations -cp /path/to/swagger-codegen-cli.jar:/path/to/your.jar io.swagger.codegen.Codegen -l AsanaPythonClientCodegen -i /path/to/swagger.yaml -o ./test +``` + +Will, for example, output the debug info for operations. You can use this info +in the `api.mustache` file. diff --git a/node_modules/asana/codegen/swagger/pom.xml b/node_modules/asana/codegen/swagger/pom.xml new file mode 100644 index 000000000..edd081583 --- /dev/null +++ b/node_modules/asana/codegen/swagger/pom.xml @@ -0,0 +1,129 @@ + + 4.0.0 + io.swagger + AsanaClientCodegen-swagger-codegen + jar + AsanaClientCodegen-swagger-codegen + 1.0.0 + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0-M1 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + ${build-helper-maven-plugin} + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.1 + + 1.8 + 1.8 + + + + + + + io.swagger.codegen.v3 + swagger-codegen + ${swagger-codegen-version} + provided + + + io.swagger.codegen.v3 + swagger-codegen-generators + ${swagger-codegen-generators-version} + provided + + + + UTF-8 + 3.0.44 + 1.0.41 + 1.0.0 + 4.13.1 + 3.0.0 + + diff --git a/node_modules/asana/codegen/swagger/src/main/java/com/asana/codegen/ExampleUtility.java b/node_modules/asana/codegen/swagger/src/main/java/com/asana/codegen/ExampleUtility.java new file mode 100644 index 000000000..634e95c0a --- /dev/null +++ b/node_modules/asana/codegen/swagger/src/main/java/com/asana/codegen/ExampleUtility.java @@ -0,0 +1,27 @@ +package com.asana.codegen; + +import org.json.*; +import io.swagger.codegen.v3.*; + +class ExampleUtility { + public static void tryToSetExample(CodegenParameter p) { + JSONObject obj = new JSONObject(p.jsonSchema); + + if (obj.has("example")) { + p.example = obj.get("example").toString(); + return; + } + + if (!obj.has("schema")) { + return; + } + + JSONObject schema = obj.getJSONObject("schema"); + + if (!schema.has("example")) { + return; + } + + p.example = schema.get("example").toString(); + } +} diff --git a/node_modules/asana/codegen/swagger/src/main/java/com/asana/codegen/JavascriptClientCodegenGenerator.java b/node_modules/asana/codegen/swagger/src/main/java/com/asana/codegen/JavascriptClientCodegenGenerator.java new file mode 100644 index 000000000..cfd47e5bc --- /dev/null +++ b/node_modules/asana/codegen/swagger/src/main/java/com/asana/codegen/JavascriptClientCodegenGenerator.java @@ -0,0 +1,181 @@ +package com.asana.codegen; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.json.*; +import io.swagger.codegen.v3.*; +import io.swagger.codegen.v3.generators.javascript.*; +import io.swagger.codegen.v3.SupportingFile; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.Schema; + +public class JavascriptClientCodegenGenerator extends JavaScriptClientCodegen { + public JavascriptClientCodegenGenerator() { + super(); + apiDocTemplateFiles.put("code_samples.mustache", ".yaml"); + modelTemplateFiles.remove("model.mustache"); + modelTestTemplateFiles.remove("model_test.mustache"); + modelDocTemplateFiles.remove("model_doc.mustache"); + // Create a definition for collection to be used in pagination + supportingFiles.add(new SupportingFile("collection.mustache", "src/utils", "collection.js")); + } + + @Override + public void processOpts() { + // custom generators do not set the CodegenConstants + // Super must be called BEFORE our modification, otherwise the package name + // somehow ends up wrong + super.processOpts(); + setProjectName("asana"); + } + + @Override + public String getModelPropertyNaming() { + // Javascript tries to use camelCase by default: + // https://github.com/swagger-api/swagger-codegen-generators/blob/66dcca9d545892e18f982b2cde60621ec6f72bfe/src/main/java/io/swagger/codegen/v3/generators/javascript/JavaScriptClientCodegen.java#L112 + // + // but we want it to use the OAS schema + return CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.original.toString(); + } + + @Override + public String toVarName(String name) { + // Return the name as defined in the OAS rather than formatting it. EX: instead of returning modified_on_after -> modified_on.after + return name; + } + + @Override + public void setParameterExampleValue(CodegenParameter p) { + // Our example correction code must execute before super, to ensure that + // super does its special magic of determining the example type: + // https://github.com/swagger-api/swagger-codegen-generators/blob/master/src/main/java/io/swagger/codegen/v3/generators/javascript/JavaScriptClientCodegen.java#L714 + ExampleUtility.tryToSetExample(p); + + String example; + if (p.defaultValue == null) { + example = p.example; + } else { + example = p.defaultValue; + } + + String type = p.baseType; + if (type == null) { + type = p.dataType; + } + + if ("String".equals(type)) { + if (example == null) { + example = p.paramName + "_example"; + } + // Change opt_fields example from ["param1", "param2"] -> "param1,param2" + String cleanedInput = example.replace("[", "").replace("]", "").replace("\"", ""); + String[] fields = cleanedInput.split(","); + String exampleOptFieldString = String.join(",", fields); + p.example = "\"" + exampleOptFieldString + "\""; + return; + } else if ("Date".equals(type)) { + if (example == null) { + example = "2013-10-20T19:20:30+01:00"; + } + // Change from new Date("2012-02-22T02:06:58.158Z") -> "2012-02-22T02:06:58.158Z" + p.example = "\"" + escapeText(example) + "\""; + return; + } + + super.setParameterExampleValue(p); + + // Wrap file request body param example in fs.createReadStream + if (p.paramName.equalsIgnoreCase("file")) { + p.example = "fs.createReadStream(" + p.example + ")"; + } + + // Update example for requests that require body + if (!languageSpecificPrimitives.contains(type)) { + // type is a model class, e.g. User + p.example = "{\"data\": {\"\": \"\", \"\": \"\",}}"; + p.dataType = "Object"; + } + } + + @Override + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map schemas, OpenAPI openAPI) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, schemas, openAPI); + // Set vendor-extension to be used in template: + // x-codegen-isCreateAttachmentForObject + if(op.operationId.equalsIgnoreCase("createAttachmentForObject")) { + op.vendorExtensions.put("x-codegen-isCreateAttachmentForObject", true); + } + if(op.operationId.equalsIgnoreCase("searchTasksForWorkspace")) { + op.vendorExtensions.put("x-codegen-isSearchTasksForWorkspace", true); + } + // Add a lower case operation ID to link to developer docs + op.vendorExtensions.put("x-codegen-operationIdLowerCase", op.operationId.toLowerCase()); + // Check if the returnType has "Array" in the name EX: TaskResponseArray is so set isArrayResponse to true + // This will be used to check if an endpoint should return a collection object or not + op.vendorExtensions.put("x-codegen-isArrayResponse", op.returnType.contains("Array")); + + // Generate resource instance variable name from the tag. EX: CustomFieldSettings -> customFieldSettingsApiInstance + String resourceInstanceName = generateResourceInstanceName(operation.getTags().get(0)); + op.vendorExtensions.put("x-codegen-resourceInstanceName", resourceInstanceName); + + // Fix PUT endpoints not adding comma in method request for sample docs. EX: .updateTask(bodytask_gid, opts) -> .updateTask(body, task_gid, opts) + // Make a copy of parameters to be used in the template (templateParams). This is a hacky work around. We noticed that the below code "p.vendorExtensions.put" + // does not update the parameter's vendorExtensions for POST and PUT endpoints so to work around this we created a new list that does have those + // vendorExtensions added + List templateParams = new ArrayList(); + CodegenParameter lastRequired = null; + CodegenParameter lastOptional = null; + for (CodegenParameter p : op.allParams) { + if (p.required) { + lastRequired = p; + } else { + lastOptional = p; + } + } + + // Set vendor-extension to be used in template: + // x-codegen-hasMoreRequired + // x-codegen-hasMoreOptional + // x-codegen-hasRequiredParams + for (CodegenParameter p : op.allParams) { + if (p == lastRequired) { + p.vendorExtensions.put("x-codegen-hasMoreRequired", false); + } else if (p == lastOptional) { + p.vendorExtensions.put("x-codegen-hasMoreOptional", false); + } else { + p.vendorExtensions.put("x-codegen-hasMoreRequired", true); + p.vendorExtensions.put("x-codegen-hasMoreOptional", true); + } + templateParams.add(p.copy()); + } + op.vendorExtensions.put("x-codegen-hasRequiredParams", lastRequired != null); + op.vendorExtensions.put("x-codegen-templateParams",templateParams); + + return op; + } + + static String generateResourceInstanceName(String inputString) { + StringBuilder camelCaseString = new StringBuilder(); + + // Split input string into words using space as delimiter + String[] words = inputString.split("\\s+"); + + // Capitalize the first letter of each word except the first one + for (int i = 0; i < words.length; i++) { + String word = words[i]; + if (i == 0) { + camelCaseString.append(word.toLowerCase()); + } else { + camelCaseString.append(word.substring(0, 1).toUpperCase()) + .append(word.substring(1).toLowerCase()); + } + } + + // Add "ApiInstance" to the end of the string + return camelCaseString.toString() + "ApiInstance"; + } +} diff --git a/node_modules/asana/codegen/swagger/src/main/java/com/asana/codegen/ReadMe.java b/node_modules/asana/codegen/swagger/src/main/java/com/asana/codegen/ReadMe.java new file mode 100644 index 000000000..749193ac2 --- /dev/null +++ b/node_modules/asana/codegen/swagger/src/main/java/com/asana/codegen/ReadMe.java @@ -0,0 +1,164 @@ +package com.asana.codegen; + +import io.swagger.codegen.v3.*; +import io.swagger.codegen.v3.generators.DefaultCodegenConfig; + +import java.util.*; +import java.io.File; + +public class ReadMe extends DefaultCodegenConfig { + + // source folder where to write the files + protected String sourceFolder = "src"; + protected String apiVersion = "1.0.0"; + + /** + * Configures the type of generator. + * + * @return the CodegenType for this generator + * @see io.swagger.codegen.CodegenType + */ + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + /** + * Configures a friendly name for the generator. This will be used by the generator + * to select the library with the -l flag. + * + * @return the friendly name for the generator + */ + public String getName() { + return "AsanaPythonClientCodegen"; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with help + * tips, parameters here + * + * @return A string value for the help message + */ + public String getHelp() { + return "Generates a AsanaPythonClientCodegen client library."; + } + + public ReadMe() { + super(); + + // set the output folder here + outputFolder = "generated-code/AsanaPythonClientCodegen"; + + /** + * Models. You can write model files using the modelTemplateFiles map. + * if you want to create one template for file, you can do so here. + * for multiple files for model, just put another entry in the `modelTemplateFiles` with + * a different extension + */ + modelTemplateFiles.put( + "model.mustache", // the template to use + ".sample"); // the extension for each file to write + + /** + * Api classes. You can write classes for each Api file with the apiTemplateFiles map. + * as with models, add multiple entries with different extensions for multiple files per + * class + */ + apiTemplateFiles.put( + "api.mustache", // the template to use + ".sample"); // the extension for each file to write + + /** + * Template Location. This is the location which templates will be read from. The generator + * will use the resource stream to attempt to read the templates. + */ + templateDir = "AsanaPythonClientCodegen"; + + /** + * Api Package. Optional, if needed, this can be used in templates + */ + apiPackage = "io.swagger.client.api"; + + /** + * Model Package. Optional, if needed, this can be used in templates + */ + modelPackage = "io.swagger.client.model"; + + /** + * Reserved words. Override this with reserved words specific to your language + */ + reservedWords = new HashSet ( + Arrays.asList( + "sample1", // replace with static values + "sample2") + ); + + /** + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files + */ + additionalProperties.put("apiVersion", apiVersion); + + /** + * Supporting Files. You can write single files for the generator with the + * entire object tree available. If the input file has a suffix of `.mustache + * it will be processed by the template engine. Otherwise, it will be copied + */ + supportingFiles.add(new SupportingFile("myFile.mustache", // the input template or file + "", // the destination folder, relative `outputFolder` + "myFile.sample") // the output file + ); + + /** + * Language Specific Primitives. These types will not trigger imports by + * the client generator + */ + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "Type1", // replace these with your types + "Type2") + ); + } + + /** + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping + * those terms here. This logic is only called if a variable matches the reserved words + * + * @return the escaped term + */ + @Override + public String escapeReservedWord(String name) { + return "_" + name; // add an underscore to the name + } + + /** + * Location to write model files. You can use the modelPackage() as defined when the class is + * instantiated + */ + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + /** + * Location to write api files. You can use the apiPackage() as defined when the class is + * instantiated + */ + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String getArgumentsLocation() { + return null; + } + + @Override + protected String getTemplateDir() { + return templateDir; + } + + @Override + public String getDefaultTemplateDir() { + return templateDir; + } +} diff --git a/node_modules/asana/codegen/swagger/src/main/resources/META-INF/services/io.swagger.codegen.v3.CodegenConfig b/node_modules/asana/codegen/swagger/src/main/resources/META-INF/services/io.swagger.codegen.v3.CodegenConfig new file mode 100644 index 000000000..1edb652a2 --- /dev/null +++ b/node_modules/asana/codegen/swagger/src/main/resources/META-INF/services/io.swagger.codegen.v3.CodegenConfig @@ -0,0 +1 @@ +com.asana.codegen.JavascriptClientCodegenGenerator diff --git a/node_modules/asana/codegen/templates/ApiClient.mustache b/node_modules/asana/codegen/templates/ApiClient.mustache new file mode 100644 index 000000000..fe29f8094 --- /dev/null +++ b/node_modules/asana/codegen/templates/ApiClient.mustache @@ -0,0 +1,641 @@ +{{>licenseInfo}} +import superagent from "superagent"; + +{{#emitJSDoc}}/** +* @module {{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}ApiClient +* @version {{projectVersion}} +*/ + +/** +* Manages low level client-server communications, parameter marshalling, etc. There should not be any need for an +* application to use this class directly - the *Api and model classes provide the public API for the service. The +* contents of this file should be regarded as internal but are documented for completeness. +* @alias module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}ApiClient +* @class +*/{{/emitJSDoc}} +export class ApiClient { + constructor() { + {{#emitJSDoc}}/** + * The base URL against which to resolve every API call's (relative) path. + * @type {String} + * @default {{{basePath}}} + */{{/emitJSDoc}} + this.basePath = '{{{basePath}}}'.replace(/\/+$/, ''); + + this.RETURN_COLLECTION = true; + + {{#emitJSDoc}}/** + * The authentication methods to be included for all API calls. + * @type {Array.} + */{{/emitJSDoc}} + this.authentications = { +{{#authMethods}} +{{#isBasic}} + '{{name}}': {{braces "left"}}type: 'basic'{{braces "right"}}{{^@last}},{{/@last}} +{{/isBasic}} +{{#isApiKey}} + '{{name}}': {{braces "left"}}type: 'apiKey', 'in': {{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{^isKeyInHeader}}'query'{{/isKeyInHeader}}, name: '{{keyParamName}}'{{braces "right"}}{{^@last}},{{/@last}} +{{/isApiKey}} +{{#isOAuth}} + '{{name}}': {{braces "left"}}type: 'oauth2'{{braces "right"}}{{^@last}},{{/@last}}, +{{/isOAuth}} +{{#isBearer}} + // Add an option to support bearer OAS security definition + 'token': {{braces "left"}}type: 'personalAccessToken'{{braces "right"}}{{^@last}},{{/@last}}, +{{/isBearer}} +{{/authMethods}} + } + + {{#emitJSDoc}}/** + * The default HTTP headers to be included for all API calls. + * @type {Array.} + * @default {} + */{{/emitJSDoc}} + this.defaultHeaders = {}; + + /** + * The default HTTP timeout for all API calls. + * @type {Number} + * @default 60000 + */ + this.timeout = 60000; + + /** + * If set to false an additional timestamp parameter is added to all API GET calls to + * prevent browser caching + * @type {Boolean} + * @default true + */ + this.cache = true; + + {{#emitJSDoc}}/** + * If set to true, the client will save the cookies from each server + * response, and return them in the next request. + * @default false + */{{/emitJSDoc}} + this.enableCookies = false; + + /* + * Used to save and return cookies in a node.js (non-browser) setting, + * if this.enableCookies is set to true. + */ + if (typeof window === 'undefined') { + this.agent = new superagent.agent(); + } + + /* + * Allow user to override superagent agent + */ + this.requestAgent = null; + + } + + {{#emitJSDoc}}/** + * Returns a string representation for an actual parameter. + * @param param The actual parameter. + * @returns {String} The string representation of param. + */{{/emitJSDoc}} + paramToString(param) { + if (param == undefined || param == null) { + return ''; + } + if (param instanceof Date) { + return param.toJSON(); + } + + return param.toString(); + } + + {{#emitJSDoc}}/** + * Builds full URL by appending the given path to the base URL and replacing path parameter place-holders with parameter values. + * NOTE: query parameters are not handled here. + * @param {String} path The path to append to the base URL. + * @param {Object} pathParams The parameter values to append. + * @returns {String} The encoded path with parameter values substituted. + */{{/emitJSDoc}} + buildUrl(path, pathParams) { + if (!path.match(/^\//)) { + path = '/' + path; + } + + var url = this.basePath + path; + url = url.replace(/\{([\w-]+)\}/g, (fullMatch, key) => { + var value; + if (pathParams.hasOwnProperty(key)) { + value = this.paramToString(pathParams[key]); + } else { + value = fullMatch; + } + + return encodeURIComponent(value); + }); + + return url; + } + + {{#emitJSDoc}}/** + * Checks whether the given content type represents JSON.
+ * JSON content type examples:
+ *
    + *
  • application/json
  • + *
  • application/json; charset=UTF8
  • + *
  • APPLICATION/JSON
  • + *
+ * @param {String} contentType The MIME content type to check. + * @returns {Boolean} true if contentType represents JSON, otherwise false. + */{{/emitJSDoc}} + isJsonMime(contentType) { + return Boolean(contentType != null && contentType.match(/^application\/json(;.*)?$/i)); + } + + {{#emitJSDoc}}/** + * Chooses a content type from the given array, with JSON preferred; i.e. return JSON if included, otherwise return the first. + * @param {Array.} contentTypes + * @returns {String} The chosen content type, preferring JSON. + */{{/emitJSDoc}} + jsonPreferredMime(contentTypes) { + for (var i = 0; i < contentTypes.length; i++) { + if (this.isJsonMime(contentTypes[i])) { + return contentTypes[i]; + } + } + + return contentTypes[0]; + } + + {{#emitJSDoc}}/** + * Checks whether the given parameter value represents file-like content. + * @param param The parameter to check. + * @returns {Boolean} true if param represents a file. + */ + {{/emitJSDoc}} + isFileParam(param) { + // fs.ReadStream in Node.js and Electron (but not in runtime like browserify) + if (typeof require === 'function') { + let fs; + try { + fs = require('fs'); + } catch (err) {} + if (fs && fs.ReadStream && param instanceof fs.ReadStream) { + return true; + } + } + + // Buffer in Node.js + if (typeof Buffer === 'function' && param instanceof Buffer) { + return true; + } + + // Blob in browser + if (typeof Blob === 'function' && param instanceof Blob) { + return true; + } + + // File in browser (it seems File object is also instance of Blob, but keep this for safe) + if (typeof File === 'function' && param instanceof File) { + return true; + } + + return false; + } + + {{#emitJSDoc}}/** + * Normalizes parameter values: + *
    + *
  • remove nils
  • + *
  • keep files and arrays
  • + *
  • format to string with `paramToString` for other cases
  • + *
+ * @param {Object.} params The parameters as object properties. + * @returns {Object.} normalized parameters. + */{{/emitJSDoc}} + normalizeParams(params) { + var newParams = {}; + for (var key in params) { + if (params.hasOwnProperty(key) && params[key] != undefined && params[key] != null) { + var value = params[key]; + if (this.isFileParam(value) || Array.isArray(value)) { + newParams[key] = value; + } else { + newParams[key] = this.paramToString(value); + } + } + } + + return newParams; + } + + {{#emitJSDoc}}/** + * Enumeration of collection format separator strategies. + * @enum {String} + * @readonly + */{{/emitJSDoc}} + static CollectionFormatEnum = { + {{#emitJSDoc}}/** + * Comma-separated values. Value: csv + * @const + */{{/emitJSDoc}} + CSV: ',', + + {{#emitJSDoc}}/** + * Space-separated values. Value: ssv + * @const + */{{/emitJSDoc}} + SSV: ' ', + + {{#emitJSDoc}}/** + * Tab-separated values. Value: tsv + * @const + */{{/emitJSDoc}} + TSV: '\t', + + {{#emitJSDoc}}/** + * Pipe(|)-separated values. Value: pipes + * @const + */{{/emitJSDoc}} + PIPES: '|', + + {{#emitJSDoc}}/** + * Native array. Value: multi + * @const + */{{/emitJSDoc}} + MULTI: 'multi' + }; + + {{#emitJSDoc}}/** + * Builds a string representation of an array-type actual parameter, according to the given collection format. + * @param {Array} param An array parameter. + * @param {module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}ApiClient.CollectionFormatEnum} collectionFormat The array element separator strategy. + * @returns {String|Array} A string representation of the supplied collection, using the specified delimiter. Returns + * param as is if collectionFormat is multi. + */{{/emitJSDoc}} + buildCollectionParam(param, collectionFormat) { + if (param == null) { + return null; + } + switch (collectionFormat) { + case 'csv': + return param.map(this.paramToString).join(','); + case 'ssv': + return param.map(this.paramToString).join(' '); + case 'tsv': + return param.map(this.paramToString).join('\t'); + case 'pipes': + return param.map(this.paramToString).join('|'); + case 'multi': + //return the array directly as SuperAgent will handle it as expected + return param.map(this.paramToString); + default: + throw new Error('Unknown collection format: ' + collectionFormat); + } + } + + {{#emitJSDoc}}/** + * Applies authentication headers to the request. + * @param {Object} request The request object created by a superagent() call. + * @param {Array.} authNames An array of authentication method names. + */{{/emitJSDoc}} + applyAuthToRequest(request, authNames) { + authNames.forEach((authName) => { + // We named the bearer auth in our OAS as "personalAccessToken". + // This logic is here because we want to change client.authentications['personalAccessToken'] -> client.authentications['token'] + // This makes it so that we don't have to change the name "personalAccessToken" -> "token" in the OAS or + // makes us need to modify the api.mustache template to pass in "token" in authNames + var auth = {}; + if (authName === "personalAccessToken") { + auth = this.authentications["token"]; + } else { + auth = this.authentications[authName]; + } + switch (auth.type) { + case 'basic': + if (auth.username || auth.password) { + request.auth(auth.username || '', auth.password || ''); + } + + break; + case 'apiKey': + if (auth.apiKey) { + var data = {}; + if (auth.apiKeyPrefix) { + data[auth.name] = auth.apiKeyPrefix + ' ' + auth.apiKey; + } else { + data[auth.name] = auth.apiKey; + } + + if (auth['in'] === 'header') { + request.set(data); + } else { + request.query(data); + } + } + + break; + case 'oauth2': + if (auth.accessToken) { + request.set({'Authorization': 'Bearer ' + auth.accessToken}); + } + + break; + case 'personalAccessToken': + if (auth.accessToken) { + request.set({'Authorization': 'Bearer ' + auth.accessToken}); + } + + break; + default: + throw new Error('Unknown authentication type: ' + auth.type); + } + }); + } + + {{#emitJSDoc}}/** + * Deserializes an HTTP response body into a value of the specified type. + * @param {Object} response A SuperAgent response object. + * @param {(String|Array.|Object.|Function)} returnType The type to return. Pass a string for simple types + * or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To + * return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type: + * all properties on data will be converted to this type. + * @returns A value of the specified type. + */ + {{/emitJSDoc}} + deserialize(response, returnType) { + if (response == null || returnType == null || response.status == 204) { + return null; + } + + // Rely on SuperAgent for parsing response body. + // See http://visionmedia.github.io/superagent/#parsing-response-bodies + var data = response.body; + if (data == null || (typeof data === 'object' && typeof data.length === 'undefined' && !Object.keys(data).length)) { + // SuperAgent does not always produce a body; use the unparsed response as a fallback + data = response.text; + } + + return ApiClient.convertToType(data, returnType); + } + + {{#emitJSDoc}}{{^usePromises}}/** + * Callback function to receive the result of the operation. + * @callback module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}ApiClient~callApiCallback + * @param {String} error Error message, if any. + * @param data The data returned by the service call. + * @param {String} response The complete HTTP response. + */{{/usePromises}}{{/emitJSDoc}} + + {{#emitJSDoc}}/** + * Invokes the REST service using the supplied settings and parameters. + * @param {String} path The base URL to invoke. + * @param {String} httpMethod The HTTP method to use. + * @param {Object.} pathParams A map of path parameters and their values. + * @param {Object.} queryParams A map of query parameters and their values. + * @param {Object.} headerParams A map of header parameters and their values. + * @param {Object.} formParams A map of form parameters and their values. + * @param {Object} bodyParam The value to pass as the request body. + * @param {Array.} authNames An array of authentication type names. + * @param {Array.} contentTypes An array of request MIME types. + * @param {Array.} accepts An array of acceptable response MIME types. + * @param {(String|Array|ObjectFunction)} returnType The required type to return; can be a string for simple types or the + * constructor for a complex type.{{^usePromises}} + * @param {module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}ApiClient~callApiCallback} callback The callback function.{{/usePromises}} + * @returns {{#usePromises}}{Promise} A {@link https://www.promisejs.org/|Promise} object{{/usePromises}}{{^usePromises}}{Object} The SuperAgent request object{{/usePromises}}. + */ + {{/emitJSDoc}} + callApi(path, httpMethod, pathParams, + queryParams, headerParams, formParams, bodyParam, authNames, contentTypes, accepts, + returnType{{^usePromises}}, callback{{/usePromises}}) { + + var url = this.buildUrl(path, pathParams); + var request = superagent(httpMethod, url); + + // apply authentications + this.applyAuthToRequest(request, authNames); + + // set query parameters + if (httpMethod.toUpperCase() === 'GET' && this.cache === false) { + queryParams['_'] = new Date().getTime(); + } + + request.query(this.normalizeParams(queryParams)); + + // set header parameters + if (typeof(navigator) === 'undefined' || typeof(window) === 'undefined') { + headerParams['X-Asana-Client-Lib'] = new URLSearchParams( + { + 'version': "{{projectVersion}}", + 'language': 'NodeJS', + 'language_version': process.version, + 'os': process.platform + } + ).toString(); + } else { + headerParams['X-Asana-Client-Lib'] = new URLSearchParams( + { + 'version': "{{projectVersion}}", + 'language': 'BrowserJS' + } + ).toString(); + } + request.set(this.defaultHeaders).set(this.normalizeParams(headerParams)); + + // set requestAgent if it is set by user + if (this.requestAgent) { + request.agent(this.requestAgent); + } + + // set request timeout + request.timeout(this.timeout); + + var contentType = this.jsonPreferredMime(contentTypes); + if (contentType) { + // Issue with superagent and multipart/form-data (https://github.com/visionmedia/superagent/issues/746) + if(contentType != 'multipart/form-data') { + request.type(contentType); + } + } else if (!request.header['Content-Type']) { + request.type('application/json'); + } + + if (contentType === 'application/x-www-form-urlencoded') { + request.send(new URLSearchParams(this.normalizeParams(formParams)).toString()); + } else if (contentType == 'multipart/form-data') { + var _formParams = this.normalizeParams(formParams); + for (var key in _formParams) { + if (_formParams.hasOwnProperty(key)) { + if (this.isFileParam(_formParams[key])) { + // file field + request.attach(key, _formParams[key]); + } else { + request.field(key, _formParams[key]); + } + } + } + } else if (bodyParam) { + // Some Asana resources (EX: Projects, ProjectTemplates) contain a "public" property which is a JavaScript reserved word. + // Because of this, the generator adds a "_" prefix to properties that is in the reserved words list: https://github.com/swagger-api/swagger-codegen-generators/blob/v1.0.42/src/main/java/io/swagger/codegen/v3/generators/javascript/JavaScriptClientCodegen.java#L134-L153 + // We need to remove this "_prefix" before sending the request to the Asana API because it will not throw an error for "_public" property in the request body. + if (bodyParam.data.hasOwnProperty("_public")) { + bodyParam.data['public'] = bodyParam.data['_public']; + delete bodyParam.data['_public']; + } + request.send(bodyParam); + } + + var accept = this.jsonPreferredMime(accepts); + if (accept) { + request.accept(accept); + } + + // Attach previously saved cookies, if enabled + if (this.enableCookies){ + if (typeof window === 'undefined') { + this.agent.attachCookies(request); + } + else { + request.withCredentials(); + } + } + + {{#usePromises}}return new Promise((resolve, reject) => { + request.end((error, response) => { + if (error) { + reject(error); + } else { + try { + var data = this.deserialize(response, returnType); + if (this.enableCookies && typeof window === 'undefined'){ + this.agent.saveCookies(response); + } + + resolve({data, response}); + } catch (err) { + reject(err); + } + } + }); + });{{/usePromises}} + + {{^usePromises}}request.end((error, response) => { + if (callback) { + var data = null; + if (!error) { + try { + data = this.deserialize(response, returnType); + if (this.enableCookies && typeof window === 'undefined'){ + this.agent.saveCookies(response); + } + } catch (err) { + error = err; + } + } + + callback(error, data, response); + } + }); + + return request;{{/usePromises}} + } + + {{#emitJSDoc}}/** + * Parses an ISO-8601 string representation of a date value. + * @param {String} str The date value as a string. + * @returns {Date} The parsed date object. + */{{/emitJSDoc}} + static parseDate(str) { + return new Date(str); + } + + {{#emitJSDoc}}/** + * Converts a value to the specified type. + * @param {(String|Object)} data The data to convert, as a string or object. + * @param {(String|Array.|Object.|Function)} type The type to return. Pass a string for simple types + * or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To + * return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type: + * all properties on data will be converted to this type. + * @returns An instance of the specified type or null or undefined if data is null or undefined. + */ + {{/emitJSDoc}} + static convertToType(data, type) { + if (data === null || data === undefined) + return data + + switch (type) { + case 'Boolean': + return Boolean(data); + case 'Integer': + return parseInt(data, 10); + case 'Number': + return parseFloat(data); + case 'String': + return String(data); + case 'Date': + return ApiClient.parseDate(String(data)); + case 'Blob': + return data; + default: + if (type === Object) { + // generic object, return directly + return data; + } else if (typeof type === 'function') { + // for model type like: User + return type.constructFromObject(data); + } else if (Array.isArray(type)) { + // for array type like: ['String'] + var itemType = type[0]; + + return data.map((item) => { + return ApiClient.convertToType(item, itemType); + }); + } else if (typeof type === 'object') { + // for plain object type like: {'String': 'Integer'} + var keyType, valueType; + for (var k in type) { + if (type.hasOwnProperty(k)) { + keyType = k; + valueType = type[k]; + break; + } + } + + var result = {}; + for (var k in data) { + if (data.hasOwnProperty(k)) { + var key = ApiClient.convertToType(k, keyType); + var value = ApiClient.convertToType(data[k], valueType); + result[key] = value; + } + } + + return result; + } else { + // for unknown type, return the data directly + return data; + } + } + } + + {{#emitJSDoc}}/** + * Constructs a new map or array model from REST data. + * @param data {Object|Array} The REST data. + * @param obj {Object|Array} The target object or array. + */{{/emitJSDoc}} + static constructFromObject(data, obj, itemType) { + if (Array.isArray(data)) { + for (var i = 0; i < data.length; i++) { + if (data.hasOwnProperty(i)) + obj[i] = ApiClient.convertToType(data[i], itemType); + } + } else { + for (var k in data) { + if (data.hasOwnProperty(k)) + obj[k] = ApiClient.convertToType(data[k], itemType); + } + } + }; +} + +{{#emitJSDoc}}/** +* The default API client implementation. +* @type {module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}ApiClient} +*/{{/emitJSDoc}} +ApiClient.instance = new ApiClient(); diff --git a/node_modules/asana/codegen/templates/README.mustache b/node_modules/asana/codegen/templates/README.mustache new file mode 100644 index 000000000..12c1d61af --- /dev/null +++ b/node_modules/asana/codegen/templates/README.mustache @@ -0,0 +1,871 @@ +# {{projectName}} [![GitHub release][release-image]][release-url] [![NPM Version][npm-image]][npm-url] + +- API version: {{appVersion}} +- Package version: {{projectVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} + +## Installation + +### For [Node.js](https://nodejs.org/) + +#### npm install from [npmjs](https://www.npmjs.com/package/asana) + +```shell +npm install {{{projectName}}} --save +``` + +### For browser + +Include the latest release directly from GitHub: + +```html + +``` + +Example usage (**NOTE**: be careful not to expose your access token): + +```html + +``` + +### Webpack Configuration + +Using Webpack you may encounter the following error: "Module not found: Error: +Cannot resolve module", most certainly you should disable AMD loader. Add/merge +the following section to your webpack config: + +```javascript +module: { + rules: [ + { + parser: { + amd: false + } + } + ] +} +``` + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following JS code: + +```javascript +{{>code_sample_client}} + +let usersApiInstance = new {{{moduleName}}}.UsersApi(); +let user_gid = "me"; // String | A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. +let opts = { + "opt_fields": "email,name,photo,photo.image_1024x1024,photo.image_128x128,photo.image_21x21,photo.image_27x27,photo.image_36x36,photo.image_60x60,workspaces,workspaces.name" // [String] | This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. +}; + +usersApiInstance.getUser(user_gid, opts).then((result) => { + console.log('API called successfully. Returned data: ' + JSON.stringify(result.data, null, 2)); +}, (error) => { + console.error(error.response.body); +}); +``` + +### Example: GET, POST, PUT, DELETE on tasks + +#### GET - get multiple tasks +```javascript +{{>code_sample_client}} + +let tasksApiInstance = new {{{moduleName}}}.TasksApi(); +let opts = { + "limit": 50, // Number | Results per page. The number of objects to return per page. The value must be between 1 and 100. + "project": "", // String | The project to filter tasks on. + "modified_since": "2012-02-22T02:06:58.158Z", // Date | Only return tasks that have been modified since the given time. *Note: A task is considered “modified” if any of its properties change, or associations between it and other objects are modified (e.g. a task being added to a project). A task is not considered modified just because another object it is associated with (e.g. a subtask) is modified. Actions that count as modifying the task include assigning, renaming, completing, and adding stories.* + "opt_fields": "actual_time_minutes,approval_status,assignee,assignee.name,assignee_section,assignee_section.name,assignee_status,completed,completed_at,completed_by,completed_by.name,created_at,created_by,custom_fields,custom_fields.asana_created_field,custom_fields.created_by,custom_fields.created_by.name,custom_fields.currency_code,custom_fields.custom_label,custom_fields.custom_label_position,custom_fields.date_value,custom_fields.date_value.date,custom_fields.date_value.date_time,custom_fields.description,custom_fields.display_value,custom_fields.enabled,custom_fields.enum_options,custom_fields.enum_options.color,custom_fields.enum_options.enabled,custom_fields.enum_options.name,custom_fields.enum_value,custom_fields.enum_value.color,custom_fields.enum_value.enabled,custom_fields.enum_value.name,custom_fields.format,custom_fields.has_notifications_enabled,custom_fields.is_formula_field,custom_fields.is_global_to_workspace,custom_fields.is_value_read_only,custom_fields.multi_enum_values,custom_fields.multi_enum_values.color,custom_fields.multi_enum_values.enabled,custom_fields.multi_enum_values.name,custom_fields.name,custom_fields.number_value,custom_fields.people_value,custom_fields.people_value.name,custom_fields.precision,custom_fields.resource_subtype,custom_fields.text_value,custom_fields.type,dependencies,dependents,due_at,due_on,external,external.data,followers,followers.name,hearted,hearts,hearts.user,hearts.user.name,html_notes,is_rendered_as_separator,liked,likes,likes.user,likes.user.name,memberships,memberships.project,memberships.project.name,memberships.section,memberships.section.name,modified_at,name,notes,num_hearts,num_likes,num_subtasks,offset,parent,parent.created_by,parent.name,parent.resource_subtype,path,permalink_url,projects,projects.name,resource_subtype,start_at,start_on,tags,tags.name,uri,workspace,workspace.name" // [String] | This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. +}; + +// GET - get multiple tasks +tasksApiInstance.getTasks(opts).then((result) => { + console.log('API called successfully. Returned data: ' + JSON.stringify(result.data, null, 2)); +}, (error) => { + console.error(error.response.body); +}); +``` + +#### POST - create a task +```javascript +{{>code_sample_client}} + +let tasksApiInstance = new {{{moduleName}}}.TasksApi(); +let body = { + "data": { + "name": "New Task", + "approval_status": "pending", + "assignee_status": "upcoming", + "completed": false, + "external": { + "gid": "1234", + "data": "A blob of information.", + }, + "html_notes": "Mittens really likes the stuff from Humboldt.", + "is_rendered_as_separator": false, + "liked": true, + "assignee": "me", + "projects": [""], + }, +}; +let opts = {}; + +// POST - Create a task +tasksApiInstance.createTask(body, opts).then((result) => { + console.log('API called successfully. Returned data: ' + JSON.stringify(result.data, null, 2)); +}, (error) => { + console.error(error.response.body); +}); +``` + +#### PUT - update a task +```javascript +{{>code_sample_client}} + +let tasksApiInstance = new {{{moduleName}}}.TasksApi(); +let task_gid = ""; +let body = { + "data": { + "name": "Updated Task", + }, +}; +let opts = {}; + +// PUT - Update a task +tasksApiInstance.updateTask(body, task_gid, opts).then((result) => { + console.log('API called successfully. Returned data: ' + JSON.stringify(result.data, null, 2)); +}, (error) => { + console.error(error.response.body); +}); +``` + +#### DELETE - delete a task +```javascript +{{>code_sample_client}} + +let tasksApiInstance = new {{{moduleName}}}.TasksApi(); +let task_gid = ""; + +// DELETE - Delete a task +tasksApiInstance.deleteTask(task_gid).then((result) => { + console.log('API called successfully. Returned data: ' + JSON.stringify(result.data, null, 2)); +}, (error) => { + console.error(error.response.body); +}); +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{basePath}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{moduleName}}.{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Optional fields + +Our `opt_fields` feature allows you to request for properties of a resource that you want to be returned in the response (more information [here](https://developers.asana.com/docs/inputoutput-options)). + +**NOTE**: by default, endpoints that return an array of results (EX: [Get multiple tasks](https://developers.asana.com/reference/gettasks), [Get multiple projects](https://developers.asana.com/reference/getprojects)), will return a compact version of those results (EX: [Get multiple tasks](https://developers.asana.com/reference/gettasks) returns an array of [TaskCompact](https://developers.asana.com/reference/tasks#taskcompact) objects). + +### EX: [Get multiple tasks](https://developers.asana.com/reference/gettasks) / [**getTasks**](docs/TasksApi.md#getTasks) without `opt_fields` + +#### Example Request +```javascript +{{>code_sample_client}} + +let tasksApiInstance = new {{{moduleName}}}.TasksApi(); +let opts = { + "limit": 2, + "project": "" +}; + +// GET - get multiple tasks +tasksApiInstance.getTasks(opts).then((result) => { + console.log(JSON.stringify(result.data, null, 2)); +}, (error) => { + console.error(error.response.body); +}); +``` + +#### Example Response +```javascript +[ + { + "gid": "123", + "name": "Task 1", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "456", + "name": "Task 2", + "resource_type": "task", + "resource_subtype": "default_task" + } +] +``` + +### EX: [Get multiple tasks](https://developers.asana.com/reference/gettasks) / [**getTasks**](docs/TasksApi.md#getTasks) with `opt_fields` + +#### Example Request +```javascript +{{>code_sample_client}} + +let tasksApiInstance = new {{{moduleName}}}.TasksApi(); +let opts = { + "limit": 1, + "project": "", + "opt_fields": "actual_time_minutes,approval_status,assignee,assignee.name,assignee_section,assignee_section.name,assignee_status,completed,completed_at,completed_by,completed_by.name,created_at,created_by,custom_fields,custom_fields.asana_created_field,custom_fields.created_by,custom_fields.created_by.name,custom_fields.currency_code,custom_fields.custom_label,custom_fields.custom_label_position,custom_fields.date_value,custom_fields.date_value.date,custom_fields.date_value.date_time,custom_fields.description,custom_fields.display_value,custom_fields.enabled,custom_fields.enum_options,custom_fields.enum_options.color,custom_fields.enum_options.enabled,custom_fields.enum_options.name,custom_fields.enum_value,custom_fields.enum_value.color,custom_fields.enum_value.enabled,custom_fields.enum_value.name,custom_fields.format,custom_fields.has_notifications_enabled,custom_fields.is_formula_field,custom_fields.is_global_to_workspace,custom_fields.is_value_read_only,custom_fields.multi_enum_values,custom_fields.multi_enum_values.color,custom_fields.multi_enum_values.enabled,custom_fields.multi_enum_values.name,custom_fields.name,custom_fields.number_value,custom_fields.people_value,custom_fields.people_value.name,custom_fields.precision,custom_fields.resource_subtype,custom_fields.text_value,custom_fields.type,dependencies,dependents,due_at,due_on,external,external.data,followers,followers.name,hearted,hearts,hearts.user,hearts.user.name,html_notes,is_rendered_as_separator,liked,likes,likes.user,likes.user.name,memberships,memberships.project,memberships.project.name,memberships.section,memberships.section.name,modified_at,name,notes,num_hearts,num_likes,num_subtasks,offset,parent,parent.created_by,parent.name,parent.resource_subtype,path,permalink_url,projects,projects.name,resource_subtype,start_at,start_on,tags,tags.name,uri,workspace,workspace.name" +}; + +// GET - get multiple tasks +tasksApiInstance.getTasks(opts).then((result) => { + console.log(JSON.stringify(result.data, null, 2)); +}, (error) => { + console.error(error.response.body); +}); +``` + +#### Example Response +```javascript +[ + { + "gid": "129839839", + "actual_time_minutes": null, + "assignee": { + "gid": "120938293", + "name": "user@example.com" + }, + "assignee_status": "upcoming", + "assignee_section": { + "gid": "1094838938", + "name": "Recently assigned" + }, + "completed": false, + "completed_at": null, + "completed_by": null, + "created_at": "2023-01-01T20:31:21.717Z", + "created_by": { + "gid": "1201784467042440", + "resource_type": "user" + }, + "custom_fields": [ + { + "gid": "191859815", + "enabled": true, + "name": "Estimated time", + "description": "Asana-created. Estimate time to complete a task.", + "number_value": null, + "precision": 0, + "format": "duration", + "currency_code": null, + "custom_label": null, + "created_by": null, + "custom_label_position": null, + "display_value": null, + "resource_subtype": "number", + "is_formula_field": false, + "is_value_read_only": false, + "type": "number" + } + ], + "dependencies": [], + "dependents": [], + "due_at": "2025-01-20T02:06:58.000Z", + "due_on": "2025-01-19", + "followers": [ + { + "gid": "120938293", + "name": "user@example.com" + } + ], + "hearted": true, + "hearts": [ + { + "gid": "594849843", + "user": { + "gid": "120938293", + "name": "user@example.com" + } + } + ], + "html_notes": "Example task notes", + "is_rendered_as_separator": false, + "liked": true, + "likes": [ + { + "gid": "58303939", + "user": { + "gid": "120938293", + "name": "user@example.com" + } + } + ], + "memberships": [ + { + "project": { + "gid": "4567", + "name": "Example Project" + }, + "section": { + "gid": "8900", + "name": "Untitled section" + } + } + ], + "modified_at": "2023-01-25T21:24:06.996Z", + "name": "Task 1", + "notes": "Example task notes", + "num_hearts": 1, + "num_likes": 1, + "num_subtasks": 0, + "parent": null, + "permalink_url": "https://app.asana.com/0/58303939/129839839", + "projects": [ + { + "gid": "4567", + "name": "Example Project" + } + ], + "start_at": null, + "start_on": null, + "tags": [], + "resource_subtype": "default_task", + "workspace": { + "gid": "111111", + "name": "Example Workspace" + } + } +] +``` + +## Pagination + +By default, endpoints that return an array of results (EX: [Get multiple tasks](https://developers.asana.com/reference/gettasks), [Get multiple projects](https://developers.asana.com/reference/getprojects)), will return a [Collection](src/utils/collection.js) object. +This collection object contains a `nextPage` method that can be used to fetch for the next page of results. **NOTE**: in order to use `nextPage` you must have provided a `limit` query parameter argument in the initial request. + +### Use case + +You may run into the following error when making a request to an endpoint that has >1000 results: + +> "The result is too large. You should use pagination (may require specifying a workspace)!" + +In this scenario you will want to use pagaintion to gather your results. To do this, you will need to provide a `limit` query parameter argument in your request. This `limit` query parameter represents the number of results per page. NOTE: the `limit` can only be between 1 and 100. + +EX: Pagination gather all resources +```javascript +{{>code_sample_client}} + +let tasksApiInstance = new {{{moduleName}}}.TasksApi(); +let opts = { + "project": "", + "limit": 100, +}; + +async function getAllTasks(opts) { + let tasks = await tasksApiInstance.getTasks(opts).then(async (response) => { + let result = []; + let page = response; + while(true) { + // Add items on page to list of results + result = result.concat(page.data); + // Fetch the next page + page = await page.nextPage(); + // If the there is no data in the next page break from the loop + if (!page.data) { + break; + } + } + return result; + }, (error) => { + console.error(error.response.body); + }); + // Do something with the tasks. EX: print out results + console.log('Tasks: ' + JSON.stringify(tasks, null, 2)); +} + +getAllTasks(opts); + +``` + +Sample output: +```bash +Tasks: [ + { + "gid": "123", + "name": "task 1", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "456", + "name": "task 2", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "789", + "name": "task 3", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "101112", + "name": "task 4", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "131415", + "name": "task 5", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "161718", + "name": "task 6", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "192021", + "name": "task 7", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "222324", + "name": "task 8", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "252627", + "name": "task 9", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "282930", + "name": "task 10", + "resource_type": "task", + "resource_subtype": "default_task" + }, + { + "gid": "313233", + "name": "task 11", + "resource_type": "task", + "resource_subtype": "default_task" + }, +] +``` + +EX: Pagination do something per page +```javascript +{{>code_sample_client}} + +let tasksApiInstance = new {{{moduleName}}}.TasksApi(); +let opts = { + 'project': "", + "limit": 5, +}; + +let pageIndex = 1; + +tasksApiInstance.getTasks(opts).then(async (response) => { + let page = response; + while(true) { + // Do something with the page results + // EX: print the name of the tasks on that page + console.log(`Page ${pageIndex}: `); + page.data.forEach(task => { + console.log(` ${task.name}`); + }); + pageIndex += 1; + + page = await page.nextPage(); + // If the there is no data in the next page break from the loop + if (!page.data) { + break; + } + } +}, (error) => { + console.error(error.response.body); +}); + +``` + +Sample output: + +```bash +Page 1: + task 1 + task 2 + task 3 + task 4 + task 5 +Page 2: + task 6 + task 7 + task 8 + task 9 + task 10 +Page 3: + task 11 + task 12 + task 13 + task 14 + task 15 +``` + +### Turning off Pagination + +If you do not want a [Collection](src/utils/collection.js) object returned and want to implement your own pagination, you can disable pagination by setting `RETURN_COLLECTION` to `false`: + +EX: Turning off pagination +```javascript +{{>code_sample_client}} + +// Turn off pagination +client.RETURN_COLLECTION = false; + +let tasksApiInstance = new {{{moduleName}}}.TasksApi(); +let opts = { + 'project': "", + 'limit': 1 +}; +tasksApiInstance.getTasks(opts).then((result) => { + console.log('API called successfully. Returned data: ' + JSON.stringify(result, null, 2)); +}) +``` + +Sample response: +``` +API called successfully. Returned data: { + "data": [ + { + "gid": "", + "name": "Task 1", + "resource_type": "task", + "resource_subtype": "default_task" + }, + ], + "next_page": { + "offset": "gjJl2xAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJib3JkZXJfcmHilbI6IltcIlZ5IixcIjlaWlhVMkkzUUdOoXcEIsMTIwNDYxNTc0NTypNDI3MF0iLCJpYXQiOjE2OTc4MjgsSkjjQsImV4cCI6MTY5NzgyOTM2NH0.5VuMfKvqexoEsKfoPFtayWBNWiKvfR7_hN6MJaaIkx8", + "path": "/tasks?project=123456&limit=1&offset=gjJl2xAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJib3JkZXJfcmHilbI6IltcIlZ5IixcIjlaWlhVMkkzUUdOoXcEIsMTIwNDYxNTc0NTypNDI3MF0iLCJpYXQiOjE2OTc4MjgsSkjjQsImV4cCI6MTY5NzgyOTM2NH0.5VuMfKvqexoEsKfoPFtayWBNWiKvfR7_hN6MJaaIkx8", + "uri": "https://app.asana.com/api/1.0/tasks?project=123456&limit=1&offset=gjJl2xAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJib3JkZXJfcmHilbI6IltcIlZ5IixcIjlaWlhVMkkzUUdOoXcEIsMTIwNDYxNTc0NTypNDI3MF0iLCJpYXQiOjE2OTc4MjgsSkjjQsImV4cCI6MTY5NzgyOTM2NH0.5VuMfKvqexoEsKfoPFtayWBNWiKvfR7_hN6MJaaIkx8" + } +} +``` + +## Getting events + +In order to get events you will need a sync token. This sync token can be acquired in the error message from the initial +request to [getEvents](docs/EventsApi.md#getEvents). + +```javascript +{{>code_sample_client}} + +let eventsApiInstance = new {{{moduleName}}}.EventsApi(); +let resource = ""; // String | A resource ID to subscribe to. The resource can be a task or project. +let opts = { + "sync": "" +}; +const timeouts = 5000 + +// Used to fetch for initial sync token +const setSyncToken = async () => { + await eventsApiInstance.getEvents(resource, opts).then((result) => { + console.log(JSON.stringify(result.data, null, 2)); + }, (error) => { + let syncToken = error.response.body.sync; + opts['sync'] = syncToken; + }); +} + +const getEvents = async () => { + console.log("Setting sync token"); + await setSyncToken(); + // Fetch for new events every 5 seconds + console.log(`Fetching events every ${timeouts/1000} second(s)`); + while(true) { + await eventsApiInstance.getEvents(resource, opts).then((result) => { + // Print response + console.log(`Fetching events since sync: ${opts['sync']}`); + console.log(JSON.stringify(result.data, null, 2)); + + // Update the sync token with the new sync token provided in the response + opts['sync'] = result._response.sync; + }, (error) => { + if (error.status === 412) { + let syncToken = error.response.body.sync; + opts['sync'] = syncToken; + console.log(`412 error new sync token: ${syncToken}`); + } else{ + console.error(error.response.text); + } + }); + await new Promise(resolve => setTimeout(resolve, timeouts)); + } +} + +getEvents(); +``` + +## Accessing repsonse data + +```javascript +. +. +. +tasksApiInstance.getTask(task_gid, opts).then((task) => { + let taskName = task.data.name; + let taskNotes = task.data.notes; + console.log(`taskName: ${taskName}`); + console.log(`taskNotes: ${taskNotes}`); +}, (error) => { + console.error(error.response.body); +}); +``` + +## Accessing response status code and headers +Use the `WithHttpInfo` (EX: `getTaskWithHttpInfo`) method to make a request that returns a response with headers. + +```javascript +{{>code_sample_client}} + +let tasksApiInstance = new {{{moduleName}}}.TasksApi(); +let task_gid = ""; +let opts = {}; + +tasksApiInstance.getTaskWithHttpInfo(task_gid, opts).then((response_and_data) => { + let data = response_and_data.data; + let response = response_and_data.response; + let task = data.data; + let headers = response.headers; + console.log(task); + console.log(headers); +}, (error) => { + console.error(error.response.body); +}); +``` + +## Adding deprecation flag: "asana-enable" or "asana-disable" header + +EX: Asana-Enable header +```javascript +{{>code_sample_client}} + +// Add asana-enable header for the client +client.defaultHeaders['asana-enable'] = 'new_goal_memberships'; +``` + +EX: Asana-Disable header +```javascript +{{>code_sample_client}} + +// Add asana-disable header for the client +client.defaultHeaders['asana-disable'] = 'new_goal_memberships'; +``` + +## Using the `callApi` method + +Use the `callApi` method to make http calls when the endpoint does not exist in the current library version or has bugs + +### Example: GET, POST, PUT, DELETE on tasks + +#### GET - get a task +```javascript +{{>code_sample_client}} + +// GET - get a task +client.callApi( + path='/tasks/{task_gid}', + httpMethod='GET', + pathParams={"task_gid": ""}, + queryParams={}, + headerParams={}, + formParams={}, + bodyParam=null, + authNames=['token'], + contentTypes=[], + accepts=['application/json; charset=UTF-8'], + returnType='Blob' +).then((response_and_data) => { + let result = response_and_data.data; + let task = result.data; + console.log(task.name); +}, (error) => { + console.error(error.response.body); +}); +``` + +#### GET - get multiple tasks -> with opt_fields +```javascript +{{>code_sample_client}} + +// GET - get multiple tasks -> with opt_fields +client.callApi( + path='/tasks', + httpMethod='GET', + pathParams={}, + queryParams={ + "limit": 50, + "modified_since": '2012-02-22T02:06:58.158Z', // OR new Date("2012-02-22T02:06:58.158Z") + "project": '', + "opt_fields": 'name,notes' + }, + headerParams={}, + formParams={}, + bodyParam=null, + authNames=['token'], + contentTypes=[], + accepts=['application/json; charset=UTF-8'], + returnType='Blob' +).then((response_and_data) => { + let result = response_and_data.data; + let tasks = result.data; + if (tasks.length > 0) { + console.log(`Task 1 Name: ${tasks[0].name}`); + console.log(`Task 1 Notes: ${tasks[0].notes}`); + } +}, (error) => { + console.error(error.response.body); +}); +``` + +#### POST - create a task +```javascript +{{>code_sample_client}} + +// POST - create a task +client.callApi( + path='/tasks', + httpMethod='POST', + pathParams={}, + queryParams={}, + headerParams={}, + formParams={}, + bodyParam={ + data: { + "name": "New Task", + "approval_status": "pending", + "assignee_status": "upcoming", + "completed": false, + "html_notes": "Mittens really likes the stuff from Humboldt.", + "is_rendered_as_separator": false, + "liked": true, + "assignee": "me", + "projects": [""], + } + }, + authNames=['token'], + contentTypes=[], + accepts=['application/json; charset=UTF-8'], + returnType='Blob' +).then((response_and_data) => { + let result = response_and_data.data; + let task = result.data; + console.log(task.name); +}, (error) => { + console.error(error.response.body); +}); +``` + +#### PUT - update a task +```javascript +{{>code_sample_client}} + +// PUT - update a task +client.callApi( + path='/tasks/{task_gid}', + httpMethod='PUT', + pathParams={task_gid: ""}, + queryParams={}, + headerParams={}, + formParams={}, + bodyParam={ + "data": { + "name": "Updated Task", + "html_notes": "Updated task notes", + "due_at": "2025-01-20T02:06:58.147Z" + } + }, + authNames=['token'], + contentTypes=[], + accepts=['application/json; charset=UTF-8'], + returnType='Blob' +).then((response_and_data) => { + let result = response_and_data.data; + let task = result.data; + console.log(task.name); +}, (error) => { + console.error(error.response.body); +}); +``` + +#### DELETE - delete a task +```javascript +{{>code_sample_client}} + +// DELETE - delete a task +client.callApi( + path='/tasks/{task_gid}', + httpMethod='DELETE', + pathParams={"task_gid": ""}, + queryParams={}, + headerParams={}, + formParams={}, + bodyParam=null, + authNames=['token'], + contentTypes=[], + accepts=['application/json; charset=UTF-8'], + returnType='Blob' +).then((response_and_data) => { + let result = response_and_data.data; + let result = result.data; + console.log(result); +}, (error) => { + console.error(error.response.body); +}); +``` + +[release-image]: https://img.shields.io/github/release/asana/node-asana.svg +[release-url]: https://github.com/Asana/node-asana/releases/tag/v{{projectVersion}} +[npm-image]: http://img.shields.io/npm/v/asana.svg?style=flat-square +[npm-url]: https://www.npmjs.org/package/asana diff --git a/node_modules/asana/codegen/templates/api.mustache b/node_modules/asana/codegen/templates/api.mustache new file mode 100644 index 000000000..0f6733964 --- /dev/null +++ b/node_modules/asana/codegen/templates/api.mustache @@ -0,0 +1,155 @@ +{{>licenseInfo}} +import {{braces "left"}}ApiClient{{braces "right"}} from "../ApiClient"; +var Collection = require('../utils/collection'); + +{{#emitJSDoc}}/** +* {{baseName}} service. +* @module {{#invokerPackage}}{{&invokerPackage}}/{{/invokerPackage}}{{#apiPackage}}{{&apiPackage}}/{{/apiPackage}}{{classname}} +* @version {{projectVersion}} +*/{{/emitJSDoc}} +export class {{classname}} { + + {{#emitJSDoc}}/** + * Constructs a new {{&classname}}. {{#description}} + * {{description}}{{/description}} + * @alias module:{{#invokerPackage}}{{&invokerPackage}}/{{/invokerPackage}}{{#apiPackage}}{{apiPackage}}/{{/apiPackage}}{{classname}} + * @class + * @param {{braces "left"}}module:{{#invokerPackage}}{{&invokerPackage}}/{{/invokerPackage}}ApiClient{{braces "right"}} [apiClient] Optional API client implementation to use, + * default to {{braces "left"}}@link module:{{#invokerPackage}}{{&invokerPackage}}/{{/invokerPackage}}ApiClient#instanc + e{{braces "right"}} if unspecified. + */{{/emitJSDoc}} + constructor(apiClient) { + this.apiClient = apiClient || ApiClient.instance; + } + +{{#operations}}{{#operation}}{{#emitJSDoc}}{{^usePromises}} + /** + * Callback function to receive the result of the {{operationId}} operation. + * @callback module{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}{{#apiPackage}}{{apiPackage}}/{{/apiPackage}}{{classname}}~{{operationId}}Callback + * @param {{braces "left"}}String{{braces "right"}} error Error message, if any. + * @param {{#vendorExtensions.x-jsdoc-type}}{{braces "left"}}{{&vendorExtensions.x-jsdoc-type}}{{braces "left"}} data The data returned by the service call.{{/vendorExtensions.x-jsdoc-type}}{{^vendorExtensions.x-jsdoc-type}}data This operation does not return a value.{{/vendorExtensions.x-jsdoc-type}} + * @param {{braces "left"}}String{{braces "right"}} response The complete HTTP response. + */{{/usePromises}} + + /**{{#summary}} + * {{summary}}{{/summary}}{{#notes}} + * {{notes}}{{/notes}}{{#allParams}}{{#required}} + * @param {{braces "left"}}{{&vendorExtensions.x-jsdoc-type}}{{braces "right"}} {{paramName}} {{description}}{{/required}}{{/allParams}}{{#hasOptionalParams}} + * @param {{braces "left"}}Object{{braces "right"}} opts Optional parameters{{#allParams}}{{^required}} + * @param {{braces "left"}}{{&vendorExtensions.x-jsdoc-type}}{{braces "right"}} opts.{{paramName}} {{description}}{{#defaultValue}} (default to <.>){{/defaultValue}}{{/required}}{{/allParams}}{{/hasOptionalParams}}{{^usePromises}} + * @param {{braces "left"}}module:{{#invokerPackage}}{{&invokerPackage}}/{{/invokerPackage}}{{#apiPackage}}{{&apiPackage}}/{{/apiPackage}}{{classname}}~{{operationId}}Callback{{braces "right"}} callback The callback function, accepting three arguments: error, data, response{{#returnType}} + * data is of type: {{braces "left"}}@link <&vendorExtensions.x-jsdoc-type>{{braces "right"}}{{/returnType}}{{/usePromises}}{{#usePromises}} + * @return {{braces "left"}}Promise{{braces "right"}} a {{braces "left"}}@link https://www.promisejs.org/|Promise{{braces "right"}}{{#returnType}}, with an object containing data and HTTP response{{/returnType}}{{^returnType}}, with an object containing HTTP response{{/returnType}}{{/usePromises}} + */ +{{/emitJSDoc}} {{operationId}}{{#usePromises}}WithHttpInfo{{/usePromises}}({{vendorExtensions.x-codegen-arg-list}}{{^usePromises}}{{#hasParams}}, {{/hasParams}}callback{{/usePromises}}) { + {{#hasOptionalParams}}opts = opts || {};{{/hasOptionalParams}} + let postBody = {{#bodyParam}}{{#required}}{{paramName}}{{/required}}{{^required}}opts['{{paramName}}']{{/required}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; +{{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} === undefined || {{paramName}} === null) { + throw new Error("Missing the required parameter '{{paramName}}' when calling {{operationId}}"); + } +{{/required}}{{/allParams}} + + let pathParams = { + {{#pathParams}}'{{baseName}}': {{#required}}{{paramName}}{{/required}}{{^required}}opts['{{paramName}}']{{/required}}{{#hasMore}},{{/hasMore}}{{/pathParams}} + }; + let queryParams = {}; + {{#hasOptionalParams}} + opts = opts || {}; + queryParams = opts; + {{/hasOptionalParams}} + {{#queryParams}}{{#required}} + queryParams['{{baseName}}'] = {{paramName}}; + {{/required}}{{/queryParams}} + + {{#vendorExtensions.x-codegen-isSearchTasksForWorkspace}} + // Checks if the user provided custom field query parameters and adds it to the request + for (const [key, value] of Object.entries(opts)) { + var matchDotCase = /custom_fields\.(.*?)\..*/; + var matchSnakeCase = /custom_fields_(.*?)_.*/; + // If the provided custom fields query param key is in the following format: custom_fields.. (EX: custom_fields.123.is_set) + if (matchDotCase.test(key)) { + queryParams[key] = value; + // If the provided custom fields query param key is in the following format: custom_fields__ (EX: custom_fields_123_is_set) + } else if (matchSnakeCase.test(key)) { + var custom_field_gid = matchSnakeCase.exec(key)[1]; + var custom_field_query_param_key = key.replace(`custom_fields_${custom_field_gid}_`, `custom_fields.${custom_field_gid}.`); + queryParams[custom_field_query_param_key] = value; + } + } + {{/vendorExtensions.x-codegen-isSearchTasksForWorkspace}} + let headerParams = { + {{#headerParams}}'{{baseName}}': {{#required}}{{paramName}}{{/required}}{{^required}}opts['{{paramName}}']{{/required}}{{#hasMore}},{{/hasMore}}{{/headerParams}} + }; + let formParams = { + {{#formParams}}'{{baseName}}': {{#collectionFormat}}this.apiClient.buildCollectionParam({{#required}}{{paramName}}{{/required}}{{^required}}opts['{{paramName}}']{{/required}}, '{{collectionFormat}}'){{/collectionFormat}}{{^collectionFormat}}{{#required}}{{paramName}}{{/required}}{{^required}}opts['{{paramName}}']{{/required}}{{/collectionFormat}}{{#hasMore}},{{/hasMore}}{{/formParams}} + }; + + let authNames = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; + let contentTypes = [{{#consumes}}'{{& mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]; + let accepts = [{{#produces}}'{{& mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]; + let returnType = 'Blob'; + {{#vendorExtensions.x-codegen-isArrayResponse}} + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient( + this.apiClient.callApi( + '{{&path}}', '{{httpMethod}}', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType{{^usePromises}}, callback{{/usePromises}} + ), + this.apiClient, + { + 'path': '{{&path}}', + 'httpMethod': '{{httpMethod}}', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + } + ) + } + {{/vendorExtensions.x-codegen-isArrayResponse}} + + return this.apiClient.callApi( + '{{&path}}', '{{httpMethod}}', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType{{^usePromises}}, callback{{/usePromises}} + ); + } +{{#usePromises}} + {{#emitJSDoc}} + + /**{{#summary}} + * {{summary}}{{/summary}}{{#notes}} + * {{notes}}{{/notes}}{{#allParams}}{{#required}} + * @param {{braces "left"}}<&vendorExtensions.x-jsdoc-type>{{braces "right"}} {{paramName}} {{description}}{{/required}}{{/allParams}}{{#hasOptionalParams}} + * @param {{braces "left"}}Object{{braces "right"}} opts Optional parameters{{#allParams}}{{^required}} + * @param {{braces "left"}}{{&vendorExtensions.x-jsdoc-type}}{{braces "right"}} opts.{{paramName}} {{description}}{{#defaultValue}} (default to <.>){{/defaultValue}}{{/required}}{{/allParams}}{{/hasOptionalParams}}{{^usePromises}} + * @param {{braces "left"}}module:{{#invokerPackage}}{{&invokerPackage}}/{{/invokerPackage}}{{#apiPackage}}{{&apiPackage}}/{{/apiPackage}}{{classname}}~{{operationId}}Callback{{braces "right"}} callback The callback function, accepting three arguments: error, data, response{{#returnType}} + * data is of type: {{braces "left"}}@link {{&vendorExtensions.x-jsdoc-type}}{{braces "right"}}{{/returnType}}{{/usePromises}}{{#usePromises}} + * @return {{braces "left"}}Promise{{braces "right"}} a {{braces "left"}}@link https://www.promisejs.org/|Promise{{braces "right"}}{{#returnType}}, with data of type {{braces "left"}}@link {{&vendorExtensions.x-jsdoc-type}}{{braces "right"}}{{/returnType}}{{/usePromises}} + */ +{{/emitJSDoc}} {{operationId}}({{vendorExtensions.x-codegen-arg-list}}) { + {{#vendorExtensions.x-codegen-isArrayResponse}} + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.{{operationId}}WithHttpInfo({{vendorExtensions.x-codegen-arg-list}}) + } + {{/vendorExtensions.x-codegen-isArrayResponse}} + + return this.{{operationId}}WithHttpInfo({{vendorExtensions.x-codegen-arg-list}}) + .then(function(response_and_data) { + return response_and_data.data; + }); + } +{{/usePromises}} +{{/operation}}{{/operations}} + +} diff --git a/node_modules/asana/codegen/templates/api_doc.mustache b/node_modules/asana/codegen/templates/api_doc.mustache new file mode 100644 index 000000000..d3c414ded --- /dev/null +++ b/node_modules/asana/codegen/templates/api_doc.mustache @@ -0,0 +1,48 @@ +# {{moduleName}}.{{classname}}{{#description}} +{{description}}{{/description}} + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} +{{#contents}} +{{#@first}} + +# **{{operationId}}** + +{{summary}}{{#notes}} + +{{{notes}}}{{/notes}} + +([more information](https://developers.asana.com/reference/{{{vendorExtensions.x-codegen-operationIdLowerCase}}})) + +### Example +```javascript +{{>code_sample}} +``` + +### Parameters +{{^parameters}}This endpoint does not need any parameter.{{/parameters}}{{#parameters}}{{#@last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/@last}}{{/parameters}} +{{#parameters}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}**Object**{{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{/parameters}} + +### Return type + +object + +### HTTP request headers + + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + +{{/@first}} +{{/contents}} +{{/operation}} +{{/operations}} diff --git a/node_modules/asana/codegen/templates/code_sample.mustache b/node_modules/asana/codegen/templates/code_sample.mustache new file mode 100644 index 000000000..0197a61bf --- /dev/null +++ b/node_modules/asana/codegen/templates/code_sample.mustache @@ -0,0 +1,35 @@ +{{>code_sample_client}} + +let {{{vendorExtensions.x-codegen-resourceInstanceName}}} = new {{{moduleName}}}.{{{classname}}}();{{#hasParams}} +{{#vendorExtensions.x-codegen-hasRequiredParams}}{{#parameters}}{{#required}} +let {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}} +{{/required}}{{/parameters}}{{/vendorExtensions.x-codegen-hasRequiredParams}}{{#hasOptionalParams}} +let opts = { {{#vendorExtensions.x-codegen-templateParams}}{{^required}} + '{{{paramName}}}': {{{example}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/vendorExtensions.x-codegen-templateParams}} +};{{/hasOptionalParams}}{{/hasParams}} +{{#vendorExtensions.x-codegen-isSearchTasksForWorkspace}} +// Custom fields query +opts['custom_fields.123.is_set'] = true; // Boolean | Replace "123" with . NOTE: searching for multiple exact matches of a custom field, searching for multi-enum custom field +opts['custom_fields.123.value'] = '456'; // String, Number, Enum option ID | Replace "123" with . NOTE: searching for multiple exact matches of a custom field, searching for multi-enum custom field +opts['custom_fields.123.starts_with'] = 'start'; // String | Replace "123" with . NOTE: searching for multiple exact matches of a custom field, searching for multi-enum custom field +opts['custom_fields.123.ends_with'] = 'end'; // String | Replace "123" with . NOTE: searching for multiple exact matches of a custom field, searching for multi-enum custom field +opts['custom_fields.123.contains'] = 'first'; // String | Replace "123" with . NOTE: searching for multiple exact matches of a custom field, searching for multi-enum custom field +opts['custom_fields.123.less_than'] = 10; // Number | Replace "123" with . NOTE: searching for multiple exact matches of a custom field, searching for multi-enum custom field +opts['custom_fields.123.greater_than'] = 100; // Number | Replace "123" with . NOTE: searching for multiple exact matches of a custom field, searching for multi-enum custom field +{{/vendorExtensions.x-codegen-isSearchTasksForWorkspace}} +{{#usePromises}} +{{{vendorExtensions.x-codegen-resourceInstanceName}}}.{{{operationId}}}({{#vendorExtensions.x-codegen-templateParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/vendorExtensions.x-codegen-templateParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}).then(({{#returnType}}result{{/returnType}}) => { + {{#returnType}}console.log('API called successfully. Returned data: ' + JSON.stringify(result.data, null, 2));{{/returnType}}{{^returnType}}console.log('API called successfully.');{{/returnType}} +}, (error) => { + console.error(error.response.body); +}); + +{{/usePromises}}{{^usePromises}} +{{{vendorExtensions.x-codegen-resourceInstanceName}}}.{{{operationId}}}({{#vendorExtensions.x-codegen-templateParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/vendorExtensions.x-codegen-templateParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}{{#hasParams}}, {{/hasParams}}(error, result, response) => { + if (error) { + console.error(error.response.body); + } else { + {{#returnType}}console.log('API called successfully. Returned data: ' + JSON.stringify(result.data, null, 2));{{/returnType}}{{^returnType}}console.log('API called successfully.');{{/returnType}} + } +}); +{{/usePromises}} diff --git a/node_modules/asana/codegen/templates/code_sample_client.mustache b/node_modules/asana/codegen/templates/code_sample_client.mustache new file mode 100644 index 000000000..d1caddd25 --- /dev/null +++ b/node_modules/asana/codegen/templates/code_sample_client.mustache @@ -0,0 +1,25 @@ +const {{{moduleName}}} = require('{{{projectName}}}'); +{{#hasParams}} +{{#vendorExtensions.x-codegen-isCreateAttachmentForObject}} +const fs = require("fs"); +{{/vendorExtensions.x-codegen-isCreateAttachmentForObject}} +{{/hasParams}} + +{{#hasAuthMethods}} +let client = {{{moduleName}}}.ApiClient.instance;{{#authMethods}}{{#isBasic}} +// Configure HTTP basic authorization: {{{name}}} +let {{{name}}} = client.authentications['{{{name}}}']; +{{{name}}}.username = 'YOUR USERNAME'; +{{{name}}}.password = 'YOUR PASSWORD';{{/isBasic}}{{#isApiKey}} +// Configure API key authorization: {{{name}}} +let {{{name}}} = client.authentications['{{{name}}}']; +{{{name}}}.apiKey = 'YOUR API KEY'; +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//{{{name}}}.apiKeyPrefix = 'Token';{{/isApiKey}}{{#isOAuth}} +// Configure OAuth2 access token for authorization: {{{name}}} +let {{{name}}} = client.authentications['{{{name}}}']; +{{{name}}}.accessToken = '';{{/isOAuth}}{{#isBearer}} +let token = client.authentications['token']; +token.accessToken = '';{{/isBearer}} +{{/authMethods}} +{{/hasAuthMethods}} \ No newline at end of file diff --git a/node_modules/asana/codegen/templates/code_samples.mustache b/node_modules/asana/codegen/templates/code_samples.mustache new file mode 100644 index 000000000..63275fda5 --- /dev/null +++ b/node_modules/asana/codegen/templates/code_samples.mustache @@ -0,0 +1,11 @@ +{{classname}}: +{{#operations}} +{{#operation}} +{{#contents}} +{{#@first}} + {{operationId}}: |- + {{>code_sample}} +{{/@first}} +{{/contents}} +{{/operation}} +{{/operations}} diff --git a/node_modules/asana/codegen/templates/collection.mustache b/node_modules/asana/codegen/templates/collection.mustache new file mode 100644 index 000000000..ef48dd3cc --- /dev/null +++ b/node_modules/asana/codegen/templates/collection.mustache @@ -0,0 +1,80 @@ +/** + * Create a Collection object from a response containing a list of resources. + * + * @param {Object} response_and_data + * @param {ApiClient} apiClient + * @param {Object} apiRequestData + * @returns {Object} Collection + */ +function Collection(response_and_data, apiClient, apiRequestData) { + if (!Collection.isCollectionResponse(response_and_data.data.data)) { + throw new Error( + 'Cannot create Collection from response that does not have resources'); + } + + this.data = response_and_data.data.data; // return the contents inside of the "data" key that Asana API returns + this._response = response_and_data.data; + this._apiClient = apiClient; + this._apiRequestData = apiRequestData; +} + +/** + * Transforms a Promise of a raw response into a Promise for a Collection. + * + * @param {Promise} promise + * @param {ApiClient} apiClient + * @param {Object} apiRequestData + * @returns {Promise} + */ +Collection.fromApiClient = function(promise, apiClient, apiRequestData) { + return promise.then(function(response_and_data) { + return new Collection(response_and_data, apiClient, apiRequestData); + }); +}; + +/** + * @param response {Object} Response that a request promise resolved to + * @returns {boolean} True iff the response is a collection (possibly empty) + */ +Collection.isCollectionResponse = function(responseData) { + return typeof(responseData) === 'object' && + typeof(responseData) === 'object' && + typeof(responseData.length) === 'number'; +}; + +module.exports = Collection; + +/** + * Get the next page of results in a collection. + * + * @returns {Promise} Resolves to either a collection representing + * the next page of results, or null if no more pages. + */ +Collection.prototype.nextPage = function() { + /* jshint camelcase:false */ + var me = this; + var next = me._response.next_page; + var apiRequestData = me._apiRequestData; + if (typeof(next) === 'object' && next !== null && me.data && me.data.length > 0) { + apiRequestData.queryParams['offset'] = next.offset; + return Collection.fromApiClient( + me._apiClient.callApi( + apiRequestData.path, + apiRequestData.httpMethod, + apiRequestData.pathParams, + apiRequestData.queryParams, + apiRequestData.headerParams, + apiRequestData.formParams, + apiRequestData.bodyParam, + apiRequestData.authNames, + apiRequestData.contentTypes, + apiRequestData.accepts, + apiRequestData.returnType + ), + me._apiClient, + me._apiRequestData); + } else { + // No more results. + return Promise.resolve({"data": null}); + } +}; diff --git a/node_modules/asana/codegen/templates/index.mustache b/node_modules/asana/codegen/templates/index.mustache new file mode 100644 index 000000000..95eb8c11d --- /dev/null +++ b/node_modules/asana/codegen/templates/index.mustache @@ -0,0 +1,51 @@ +{{>licenseInfo}} +import {ApiClient} from './ApiClient'; +{{#apiInfo}}{{#apis}}import {{braces "left"}}{{importPath}}{{braces "right"}} from './{{#apiPackage}}{{apiPackage}}/{{/apiPackage}}{{importPath}}'; +{{/apis}}{{/apiInfo}} + +{{#emitJSDoc}}/**{{#projectDescription}} +* {{projectDescription}}.
{{/projectDescription}} +* The index module provides access to constructors for all the classes which comprise the public API. +*

+* An AMD (recommended!) or CommonJS application will generally do something equivalent to the following: +*

+* var {{moduleName}} = require('{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}index'); // See note below*.
+* var xxxSvc = new {{moduleName}}.XxxApi(); // Allocate the API class we're going to use.
+* var yyyModel = new {{moduleName}}.Yyy(); // Construct a model instance.
+* yyyModel.someProperty = 'someValue';
+* ...
+* var zzz = xxxSvc.doSomething(yyyModel); // Invoke the service.
+* ...
+* 
+* *NOTE: For a top-level AMD script, use require(['{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}index'], function(){...}) +* and put the application logic within the callback function. +*

+*

+* A non-AMD browser application (discouraged) might do something like this: +*

+* var xxxSvc = new {{moduleName}}.XxxApi(); // Allocate the API class we're going to use.
+* var yyy = new {{moduleName}}.Yyy(); // Construct a model instance.
+* yyyModel.someProperty = 'someValue';
+* ...
+* var zzz = xxxSvc.doSomething(yyyModel); // Invoke the service.
+* ...
+* 
+*

+* @module {{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}index +* @version {{projectVersion}} +*/{{/emitJSDoc}} +export { + {{#emitJSDoc}}/** + * The ApiClient constructor. + * @property {{braces "left"}}module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}ApiClient{{braces "right"}} + */{{/emitJSDoc}} + ApiClient + + {{#apiInfo}}{{#apis}}, + + {{#emitJSDoc}}/** + * The {{importPath}} service constructor. + * @property {{braces "left"}}module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}{{#apiPackage}}{{apiPackage}}/{{/apiPackage}}{{importPath}}{{braces "right"}} + */{{/emitJSDoc}} + {{importPath}}{{/apis}}{{/apiInfo}} +}; diff --git a/node_modules/asana/codegen/templates/package.mustache b/node_modules/asana/codegen/templates/package.mustache new file mode 100644 index 000000000..b07ef0243 --- /dev/null +++ b/node_modules/asana/codegen/templates/package.mustache @@ -0,0 +1,47 @@ +{ + "name": "{{{projectName}}}", + "version": "{{{projectVersion}}}", + "description": "{{{projectDescription}}}", + "license": "{{licenseName}}", + "main": "{{sourceFolder}}{{#invokerPackage}}/{{invokerPackage}}{{/invokerPackage}}/index.js", + "repository": { + "url": "https://github.com/Asana/node-{{{projectName}}}", + "type": "git" + }, + "scripts": { + "test": "mocha --require @babel/register --recursive", + "testbuild": "mocha --timeout 20000 --require @babel/register --recursive 'build-tests/api/*.js'" + }, + "browser": { + "fs": false + }, + "dependencies": { + "@babel/cli": "^7.0.0", + "superagent": "^5.3.0" + }, + "devDependencies": { + "@babel/core": "^7.0.0", + "@babel/plugin-proposal-class-properties": "^7.0.0", + "@babel/plugin-proposal-decorators": "^7.0.0", + "@babel/plugin-proposal-do-expressions": "^7.0.0", + "@babel/plugin-proposal-export-default-from": "^7.0.0", + "@babel/plugin-proposal-export-namespace-from": "^7.0.0", + "@babel/plugin-proposal-function-bind": "^7.0.0", + "@babel/plugin-proposal-function-sent": "^7.0.0", + "@babel/plugin-proposal-json-strings": "^7.0.0", + "@babel/plugin-proposal-logical-assignment-operators": "^7.0.0", + "@babel/plugin-proposal-nullish-coalescing-operator": "^7.0.0", + "@babel/plugin-proposal-numeric-separator": "^7.0.0", + "@babel/plugin-proposal-optional-chaining": "^7.0.0", + "@babel/plugin-proposal-pipeline-operator": "^7.0.0", + "@babel/plugin-proposal-throw-expressions": "^7.0.0", + "@babel/plugin-syntax-dynamic-import": "^7.0.0", + "@babel/plugin-syntax-import-meta": "^7.0.0", + "@babel/preset-env": "^7.0.0", + "@babel/register": "^7.0.0", + "dotenv": "^16.4.1", + "expect.js": "^0.3.1", + "mocha": "^8.0.1", + "sinon": "^7.2.0" + } +} diff --git a/node_modules/asana/dist/ApiClient.js b/node_modules/asana/dist/ApiClient.js new file mode 100644 index 000000000..74d6f9485 --- /dev/null +++ b/node_modules/asana/dist/ApiClient.js @@ -0,0 +1,618 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ApiClient = void 0; +var _superagent = _interopRequireDefault(require("superagent")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +/** +* @module ApiClient +* @version 3.0.3 +*/ +/** +* Manages low level client-server communications, parameter marshalling, etc. There should not be any need for an +* application to use this class directly - the *Api and model classes provide the public API for the service. The +* contents of this file should be regarded as internal but are documented for completeness. +* @alias module:ApiClient +* @class +*/ +var ApiClient = exports.ApiClient = /*#__PURE__*/function () { + function ApiClient() { + _classCallCheck(this, ApiClient); + /** + * The base URL against which to resolve every API call's (relative) path. + * @type {String} + * @default https://app.asana.com/api/1.0 + */ + this.basePath = 'https://app.asana.com/api/1.0'.replace(/\/+$/, ''); + this.RETURN_COLLECTION = true; + + /** + * The authentication methods to be included for all API calls. + * @type {Array.} + */ + this.authentications = { + // Add an option to support bearer OAS security definition + 'token': { + type: 'personalAccessToken' + } + }; + + /** + * The default HTTP headers to be included for all API calls. + * @type {Array.} + * @default {} + */ + this.defaultHeaders = {}; + + /** + * The default HTTP timeout for all API calls. + * @type {Number} + * @default 60000 + */ + this.timeout = 60000; + + /** + * If set to false an additional timestamp parameter is added to all API GET calls to + * prevent browser caching + * @type {Boolean} + * @default true + */ + this.cache = true; + + /** + * If set to true, the client will save the cookies from each server + * response, and return them in the next request. + * @default false + */ + this.enableCookies = false; + + /* + * Used to save and return cookies in a node.js (non-browser) setting, + * if this.enableCookies is set to true. + */ + if (typeof window === 'undefined') { + this.agent = new _superagent["default"].agent(); + } + + /* + * Allow user to override superagent agent + */ + this.requestAgent = null; + } + + /** + * Returns a string representation for an actual parameter. + * @param param The actual parameter. + * @returns {String} The string representation of param. + */ + return _createClass(ApiClient, [{ + key: "paramToString", + value: function paramToString(param) { + if (param == undefined || param == null) { + return ''; + } + if (param instanceof Date) { + return param.toJSON(); + } + return param.toString(); + } + + /** + * Builds full URL by appending the given path to the base URL and replacing path parameter place-holders with parameter values. + * NOTE: query parameters are not handled here. + * @param {String} path The path to append to the base URL. + * @param {Object} pathParams The parameter values to append. + * @returns {String} The encoded path with parameter values substituted. + */ + }, { + key: "buildUrl", + value: function buildUrl(path, pathParams) { + var _this = this; + if (!path.match(/^\//)) { + path = '/' + path; + } + var url = this.basePath + path; + url = url.replace(/\{([\w-]+)\}/g, function (fullMatch, key) { + var value; + if (pathParams.hasOwnProperty(key)) { + value = _this.paramToString(pathParams[key]); + } else { + value = fullMatch; + } + return encodeURIComponent(value); + }); + return url; + } + + /** + * Checks whether the given content type represents JSON.
+ * JSON content type examples:
+ *
    + *
  • application/json
  • + *
  • application/json; charset=UTF8
  • + *
  • APPLICATION/JSON
  • + *
+ * @param {String} contentType The MIME content type to check. + * @returns {Boolean} true if contentType represents JSON, otherwise false. + */ + }, { + key: "isJsonMime", + value: function isJsonMime(contentType) { + return Boolean(contentType != null && contentType.match(/^application\/json(;.*)?$/i)); + } + + /** + * Chooses a content type from the given array, with JSON preferred; i.e. return JSON if included, otherwise return the first. + * @param {Array.} contentTypes + * @returns {String} The chosen content type, preferring JSON. + */ + }, { + key: "jsonPreferredMime", + value: function jsonPreferredMime(contentTypes) { + for (var i = 0; i < contentTypes.length; i++) { + if (this.isJsonMime(contentTypes[i])) { + return contentTypes[i]; + } + } + return contentTypes[0]; + } + + /** + * Checks whether the given parameter value represents file-like content. + * @param param The parameter to check. + * @returns {Boolean} true if param represents a file. + */ + }, { + key: "isFileParam", + value: function isFileParam(param) { + // fs.ReadStream in Node.js and Electron (but not in runtime like browserify) + if (typeof require === 'function') { + var fs; + try { + fs = require('fs'); + } catch (err) {} + if (fs && fs.ReadStream && param instanceof fs.ReadStream) { + return true; + } + } + + // Buffer in Node.js + if (typeof Buffer === 'function' && param instanceof Buffer) { + return true; + } + + // Blob in browser + if (typeof Blob === 'function' && param instanceof Blob) { + return true; + } + + // File in browser (it seems File object is also instance of Blob, but keep this for safe) + if (typeof File === 'function' && param instanceof File) { + return true; + } + return false; + } + + /** + * Normalizes parameter values: + *
    + *
  • remove nils
  • + *
  • keep files and arrays
  • + *
  • format to string with `paramToString` for other cases
  • + *
+ * @param {Object.} params The parameters as object properties. + * @returns {Object.} normalized parameters. + */ + }, { + key: "normalizeParams", + value: function normalizeParams(params) { + var newParams = {}; + for (var key in params) { + if (params.hasOwnProperty(key) && params[key] != undefined && params[key] != null) { + var value = params[key]; + if (this.isFileParam(value) || Array.isArray(value)) { + newParams[key] = value; + } else { + newParams[key] = this.paramToString(value); + } + } + } + return newParams; + } + + /** + * Enumeration of collection format separator strategies. + * @enum {String} + * @readonly + */ + }, { + key: "buildCollectionParam", + value: + /** + * Builds a string representation of an array-type actual parameter, according to the given collection format. + * @param {Array} param An array parameter. + * @param {module:ApiClient.CollectionFormatEnum} collectionFormat The array element separator strategy. + * @returns {String|Array} A string representation of the supplied collection, using the specified delimiter. Returns + * param as is if collectionFormat is multi. + */ + function buildCollectionParam(param, collectionFormat) { + if (param == null) { + return null; + } + switch (collectionFormat) { + case 'csv': + return param.map(this.paramToString).join(','); + case 'ssv': + return param.map(this.paramToString).join(' '); + case 'tsv': + return param.map(this.paramToString).join('\t'); + case 'pipes': + return param.map(this.paramToString).join('|'); + case 'multi': + //return the array directly as SuperAgent will handle it as expected + return param.map(this.paramToString); + default: + throw new Error('Unknown collection format: ' + collectionFormat); + } + } + + /** + * Applies authentication headers to the request. + * @param {Object} request The request object created by a superagent() call. + * @param {Array.} authNames An array of authentication method names. + */ + }, { + key: "applyAuthToRequest", + value: function applyAuthToRequest(request, authNames) { + var _this2 = this; + authNames.forEach(function (authName) { + // We named the bearer auth in our OAS as "personalAccessToken". + // This logic is here because we want to change client.authentications['personalAccessToken'] -> client.authentications['token'] + // This makes it so that we don't have to change the name "personalAccessToken" -> "token" in the OAS or + // makes us need to modify the api.mustache template to pass in "token" in authNames + var auth = {}; + if (authName === "personalAccessToken") { + auth = _this2.authentications["token"]; + } else { + auth = _this2.authentications[authName]; + } + switch (auth.type) { + case 'basic': + if (auth.username || auth.password) { + request.auth(auth.username || '', auth.password || ''); + } + break; + case 'apiKey': + if (auth.apiKey) { + var data = {}; + if (auth.apiKeyPrefix) { + data[auth.name] = auth.apiKeyPrefix + ' ' + auth.apiKey; + } else { + data[auth.name] = auth.apiKey; + } + if (auth['in'] === 'header') { + request.set(data); + } else { + request.query(data); + } + } + break; + case 'oauth2': + if (auth.accessToken) { + request.set({ + 'Authorization': 'Bearer ' + auth.accessToken + }); + } + break; + case 'personalAccessToken': + if (auth.accessToken) { + request.set({ + 'Authorization': 'Bearer ' + auth.accessToken + }); + } + break; + default: + throw new Error('Unknown authentication type: ' + auth.type); + } + }); + } + + /** + * Deserializes an HTTP response body into a value of the specified type. + * @param {Object} response A SuperAgent response object. + * @param {(String|Array.|Object.|Function)} returnType The type to return. Pass a string for simple types + * or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To + * return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type: + * all properties on data will be converted to this type. + * @returns A value of the specified type. + */ + }, { + key: "deserialize", + value: function deserialize(response, returnType) { + if (response == null || returnType == null || response.status == 204) { + return null; + } + + // Rely on SuperAgent for parsing response body. + // See http://visionmedia.github.io/superagent/#parsing-response-bodies + var data = response.body; + if (data == null || _typeof(data) === 'object' && typeof data.length === 'undefined' && !Object.keys(data).length) { + // SuperAgent does not always produce a body; use the unparsed response as a fallback + data = response.text; + } + return ApiClient.convertToType(data, returnType); + } + + /** + * Invokes the REST service using the supplied settings and parameters. + * @param {String} path The base URL to invoke. + * @param {String} httpMethod The HTTP method to use. + * @param {Object.} pathParams A map of path parameters and their values. + * @param {Object.} queryParams A map of query parameters and their values. + * @param {Object.} headerParams A map of header parameters and their values. + * @param {Object.} formParams A map of form parameters and their values. + * @param {Object} bodyParam The value to pass as the request body. + * @param {Array.} authNames An array of authentication type names. + * @param {Array.} contentTypes An array of request MIME types. + * @param {Array.} accepts An array of acceptable response MIME types. + * @param {(String|Array|ObjectFunction)} returnType The required type to return; can be a string for simple types or the + * constructor for a complex type. + * @returns {Promise} A {@link https://www.promisejs.org/|Promise} object. + */ + }, { + key: "callApi", + value: function callApi(path, httpMethod, pathParams, queryParams, headerParams, formParams, bodyParam, authNames, contentTypes, accepts, returnType) { + var _this3 = this; + var url = this.buildUrl(path, pathParams); + var request = (0, _superagent["default"])(httpMethod, url); + + // apply authentications + this.applyAuthToRequest(request, authNames); + + // set query parameters + if (httpMethod.toUpperCase() === 'GET' && this.cache === false) { + queryParams['_'] = new Date().getTime(); + } + request.query(this.normalizeParams(queryParams)); + + // set header parameters + if (typeof navigator === 'undefined' || typeof window === 'undefined') { + headerParams['X-Asana-Client-Lib'] = new URLSearchParams({ + 'version': "3.0.3", + 'language': 'NodeJS', + 'language_version': process.version, + 'os': process.platform + }).toString(); + } else { + headerParams['X-Asana-Client-Lib'] = new URLSearchParams({ + 'version': "3.0.3", + 'language': 'BrowserJS' + }).toString(); + } + request.set(this.defaultHeaders).set(this.normalizeParams(headerParams)); + + // set requestAgent if it is set by user + if (this.requestAgent) { + request.agent(this.requestAgent); + } + + // set request timeout + request.timeout(this.timeout); + var contentType = this.jsonPreferredMime(contentTypes); + if (contentType) { + // Issue with superagent and multipart/form-data (https://github.com/visionmedia/superagent/issues/746) + if (contentType != 'multipart/form-data') { + request.type(contentType); + } + } else if (!request.header['Content-Type']) { + request.type('application/json'); + } + if (contentType === 'application/x-www-form-urlencoded') { + request.send(new URLSearchParams(this.normalizeParams(formParams)).toString()); + } else if (contentType == 'multipart/form-data') { + var _formParams = this.normalizeParams(formParams); + for (var key in _formParams) { + if (_formParams.hasOwnProperty(key)) { + if (this.isFileParam(_formParams[key])) { + // file field + request.attach(key, _formParams[key]); + } else { + request.field(key, _formParams[key]); + } + } + } + } else if (bodyParam) { + // Some Asana resources (EX: Projects, ProjectTemplates) contain a "public" property which is a JavaScript reserved word. + // Because of this, the generator adds a "_" prefix to properties that is in the reserved words list: https://github.com/swagger-api/swagger-codegen-generators/blob/v1.0.42/src/main/java/io/swagger/codegen/v3/generators/javascript/JavaScriptClientCodegen.java#L134-L153 + // We need to remove this "_prefix" before sending the request to the Asana API because it will not throw an error for "_public" property in the request body. + if (bodyParam.data.hasOwnProperty("_public")) { + bodyParam.data['public'] = bodyParam.data['_public']; + delete bodyParam.data['_public']; + } + request.send(bodyParam); + } + var accept = this.jsonPreferredMime(accepts); + if (accept) { + request.accept(accept); + } + + // Attach previously saved cookies, if enabled + if (this.enableCookies) { + if (typeof window === 'undefined') { + this.agent.attachCookies(request); + } else { + request.withCredentials(); + } + } + return new Promise(function (resolve, reject) { + request.end(function (error, response) { + if (error) { + reject(error); + } else { + try { + var data = _this3.deserialize(response, returnType); + if (_this3.enableCookies && typeof window === 'undefined') { + _this3.agent.saveCookies(response); + } + resolve({ + data: data, + response: response + }); + } catch (err) { + reject(err); + } + } + }); + }); + } + + /** + * Parses an ISO-8601 string representation of a date value. + * @param {String} str The date value as a string. + * @returns {Date} The parsed date object. + */ + }], [{ + key: "parseDate", + value: function parseDate(str) { + return new Date(str); + } + + /** + * Converts a value to the specified type. + * @param {(String|Object)} data The data to convert, as a string or object. + * @param {(String|Array.|Object.|Function)} type The type to return. Pass a string for simple types + * or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To + * return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type: + * all properties on data will be converted to this type. + * @returns An instance of the specified type or null or undefined if data is null or undefined. + */ + }, { + key: "convertToType", + value: function convertToType(data, type) { + if (data === null || data === undefined) return data; + switch (type) { + case 'Boolean': + return Boolean(data); + case 'Integer': + return parseInt(data, 10); + case 'Number': + return parseFloat(data); + case 'String': + return String(data); + case 'Date': + return ApiClient.parseDate(String(data)); + case 'Blob': + return data; + default: + if (type === Object) { + // generic object, return directly + return data; + } else if (typeof type === 'function') { + // for model type like: User + return type.constructFromObject(data); + } else if (Array.isArray(type)) { + // for array type like: ['String'] + var itemType = type[0]; + return data.map(function (item) { + return ApiClient.convertToType(item, itemType); + }); + } else if (_typeof(type) === 'object') { + // for plain object type like: {'String': 'Integer'} + var keyType, valueType; + for (var k in type) { + if (type.hasOwnProperty(k)) { + keyType = k; + valueType = type[k]; + break; + } + } + var result = {}; + for (var k in data) { + if (data.hasOwnProperty(k)) { + var key = ApiClient.convertToType(k, keyType); + var value = ApiClient.convertToType(data[k], valueType); + result[key] = value; + } + } + return result; + } else { + // for unknown type, return the data directly + return data; + } + } + } + + /** + * Constructs a new map or array model from REST data. + * @param data {Object|Array} The REST data. + * @param obj {Object|Array} The target object or array. + */ + }, { + key: "constructFromObject", + value: function constructFromObject(data, obj, itemType) { + if (Array.isArray(data)) { + for (var i = 0; i < data.length; i++) { + if (data.hasOwnProperty(i)) obj[i] = ApiClient.convertToType(data[i], itemType); + } + } else { + for (var k in data) { + if (data.hasOwnProperty(k)) obj[k] = ApiClient.convertToType(data[k], itemType); + } + } + } + }]); +}(); +/** +* The default API client implementation. +* @type {module:ApiClient} +*/ +_defineProperty(ApiClient, "CollectionFormatEnum", { + /** + * Comma-separated values. Value: csv + * @const + */ + CSV: ',', + /** + * Space-separated values. Value: ssv + * @const + */ + SSV: ' ', + /** + * Tab-separated values. Value: tsv + * @const + */ + TSV: '\t', + /** + * Pipe(|)-separated values. Value: pipes + * @const + */ + PIPES: '|', + /** + * Native array. Value: multi + * @const + */ + MULTI: 'multi' +}); +ApiClient.instance = new ApiClient(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/AttachmentsApi.js b/node_modules/asana/dist/api/AttachmentsApi.js new file mode 100644 index 000000000..3ca378785 --- /dev/null +++ b/node_modules/asana/dist/api/AttachmentsApi.js @@ -0,0 +1,267 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AttachmentsApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* Attachments service. +* @module api/AttachmentsApi +* @version 3.0.3 +*/ +var AttachmentsApi = exports.AttachmentsApi = /*#__PURE__*/function () { + /** + * Constructs a new AttachmentsApi. + * @alias module:api/AttachmentsApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function AttachmentsApi(apiClient) { + _classCallCheck(this, AttachmentsApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Upload an attachment + * Upload an attachment. This method uploads an attachment on an object and returns the compact record for the created attachment object. This is possible by either: - Providing the URL of the external resource being attached, or - Downloading the file content first and then uploading it as any other attachment. Note that it is not possible to attach files from third party services such as Dropbox, Box, Vimeo & Google Drive via the API The 100MB size limit on attachments in Asana is enforced on this endpoint. This endpoint expects a multipart/form-data encoded request containing the full contents of the file to be uploaded. Requests made should follow the HTTP/1.1 specification that line terminators are of the form `CRLF` or `\\r\\n` outlined [here](http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01#Basic-Rules) in order for the server to reliably and properly handle the request. + * @param {Object} opts Optional parameters + * @param {module:model/String} opts.resource_subtype + * @param {Blob} opts.file + * @param {String} opts.parent + * @param {String} opts.url + * @param {String} opts.name + * @param {Boolean} opts.connect_to_app + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(AttachmentsApi, [{ + key: "createAttachmentForObjectWithHttpInfo", + value: function createAttachmentForObjectWithHttpInfo(opts) { + opts = opts || {}; + var postBody = null; + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = { + 'resource_subtype': opts['resource_subtype'], + 'file': opts['file'], + 'parent': opts['parent'], + 'url': opts['url'], + 'name': opts['name'], + 'connect_to_app': opts['connect_to_app'] + }; + var authNames = ['personalAccessToken']; + var contentTypes = ['multipart/form-data']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/attachments', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Upload an attachment + * Upload an attachment. This method uploads an attachment on an object and returns the compact record for the created attachment object. This is possible by either: - Providing the URL of the external resource being attached, or - Downloading the file content first and then uploading it as any other attachment. Note that it is not possible to attach files from third party services such as Dropbox, Box, Vimeo & Google Drive via the API The 100MB size limit on attachments in Asana is enforced on this endpoint. This endpoint expects a multipart/form-data encoded request containing the full contents of the file to be uploaded. Requests made should follow the HTTP/1.1 specification that line terminators are of the form `CRLF` or `\\r\\n` outlined [here](http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01#Basic-Rules) in order for the server to reliably and properly handle the request. + * @param {Object} opts Optional parameters + * @param {module:model/String} opts.resource_subtype + * @param {Blob} opts.file + * @param {String} opts.parent + * @param {String} opts.url + * @param {String} opts.name + * @param {Boolean} opts.connect_to_app + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/AttachmentResponseData} + */ + }, { + key: "createAttachmentForObject", + value: function createAttachmentForObject(opts) { + return this.createAttachmentForObjectWithHttpInfo(opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Delete an attachment + * Deletes a specific, existing attachment. Returns an empty data record. + * @param {String} attachment_gid Globally unique identifier for the attachment. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "deleteAttachmentWithHttpInfo", + value: function deleteAttachmentWithHttpInfo(attachment_gid) { + var postBody = null; + // verify the required parameter 'attachment_gid' is set + if (attachment_gid === undefined || attachment_gid === null) { + throw new Error("Missing the required parameter 'attachment_gid' when calling deleteAttachment"); + } + var pathParams = { + 'attachment_gid': attachment_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/attachments/{attachment_gid}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Delete an attachment + * Deletes a specific, existing attachment. Returns an empty data record. + * @param {<&vendorExtensions.x-jsdoc-type>} attachment_gid Globally unique identifier for the attachment. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "deleteAttachment", + value: function deleteAttachment(attachment_gid) { + return this.deleteAttachmentWithHttpInfo(attachment_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get an attachment + * Get the full record for a single attachment. + * @param {String} attachment_gid Globally unique identifier for the attachment. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getAttachmentWithHttpInfo", + value: function getAttachmentWithHttpInfo(attachment_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'attachment_gid' is set + if (attachment_gid === undefined || attachment_gid === null) { + throw new Error("Missing the required parameter 'attachment_gid' when calling getAttachment"); + } + var pathParams = { + 'attachment_gid': attachment_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/attachments/{attachment_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get an attachment + * Get the full record for a single attachment. + * @param {<&vendorExtensions.x-jsdoc-type>} attachment_gid Globally unique identifier for the attachment. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/AttachmentResponseData} + */ + }, { + key: "getAttachment", + value: function getAttachment(attachment_gid, opts) { + return this.getAttachmentWithHttpInfo(attachment_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get attachments from an object + * Returns the compact records for all attachments on the object. There are three possible `parent` values for this request: `project`, `project_brief`, and `task`. For a project, an attachment refers to a file uploaded to the \"Key resources\" section in the project Overview. For a project brief, an attachment refers to inline files in the project brief itself. For a task, an attachment refers to a file directly associated to that task. Note that within the Asana app, inline images in the task description do not appear in the index of image thumbnails nor as stories in the task. However, requests made to `GET /attachments` for a task will return all of the images in the task, including inline images. + * @param {String} parent Globally unique identifier for object to fetch statuses from. Must be a GID for a `project`, `project_brief`, or `task`. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getAttachmentsForObjectWithHttpInfo", + value: function getAttachmentsForObjectWithHttpInfo(parent, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'parent' is set + if (parent === undefined || parent === null) { + throw new Error("Missing the required parameter 'parent' when calling getAttachmentsForObject"); + } + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + queryParams['parent'] = parent; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/attachments', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/attachments', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/attachments', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get attachments from an object + * Returns the compact records for all attachments on the object. There are three possible `parent` values for this request: `project`, `project_brief`, and `task`. For a project, an attachment refers to a file uploaded to the \"Key resources\" section in the project Overview. For a project brief, an attachment refers to inline files in the project brief itself. For a task, an attachment refers to a file directly associated to that task. Note that within the Asana app, inline images in the task description do not appear in the index of image thumbnails nor as stories in the task. However, requests made to `GET /attachments` for a task will return all of the images in the task, including inline images. + * @param {<&vendorExtensions.x-jsdoc-type>} parent Globally unique identifier for object to fetch statuses from. Must be a GID for a `project`, `project_brief`, or `task`. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/AttachmentResponseArray} + */ + }, { + key: "getAttachmentsForObject", + value: function getAttachmentsForObject(parent, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getAttachmentsForObjectWithHttpInfo(parent, opts); + } + return this.getAttachmentsForObjectWithHttpInfo(parent, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/AuditLogAPIApi.js b/node_modules/asana/dist/api/AuditLogAPIApi.js new file mode 100644 index 000000000..400ec8957 --- /dev/null +++ b/node_modules/asana/dist/api/AuditLogAPIApi.js @@ -0,0 +1,130 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AuditLogAPIApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* AuditLogAPI service. +* @module api/AuditLogAPIApi +* @version 3.0.3 +*/ +var AuditLogAPIApi = exports.AuditLogAPIApi = /*#__PURE__*/function () { + /** + * Constructs a new AuditLogAPIApi. + * @alias module:api/AuditLogAPIApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function AuditLogAPIApi(apiClient) { + _classCallCheck(this, AuditLogAPIApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Get audit log events + * Retrieve the audit log events that have been captured in your domain. This endpoint will return a list of [AuditLogEvent](/reference/audit-log-api) objects, sorted by creation time in ascending order. Note that the Audit Log API captures events from October 8th, 2021 and later. Queries for events before this date will not return results. There are a number of query parameters (below) that can be used to filter the set of [AuditLogEvent](/reference/audit-log-api) objects that are returned in the response. Any combination of query parameters is valid. When no filters are provided, all of the events that have been captured in your domain will match. The list of events will always be [paginated](/docs/pagination). The default limit is 1000 events. The next set of events can be retrieved using the `offset` from the previous response. If there are no events that match the provided filters in your domain, the endpoint will return `null` for the `next_page` field. Querying again with the same filters may return new events if they were captured after the last request. Once a response includes a `next_page` with an `offset`, subsequent requests can be made with the latest `offset` to poll for new events that match the provided filters. *Note: If the filters you provided match events in your domain and `next_page` is present in the response, we will continue to send `next_page` on subsequent requests even when there are no more events that match the filters. This was put in place so that you can implement an audit log stream that will return future events that match these filters. If you are not interested in future events that match the filters you have defined, you can rely on checking empty `data` response for the end of current events that match your filters.* When no `offset` is provided, the response will begin with the oldest events that match the provided filters. It is important to note that [AuditLogEvent](/reference/audit-log-api) objects will be permanently deleted from our systems after 90 days. If you wish to keep a permanent record of these events, we recommend using a SIEM tool to ingest and store these logs. + * @param {String} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {Date} opts.start_at Filter to events created after this time (inclusive). + * @param {Date} opts.end_at Filter to events created before this time (exclusive). + * @param {String} opts.event_type Filter to events of this type. Refer to the [supported audit log events](/docs/audit-log-events#supported-audit-log-events) for a full list of values. + * @param {module:model/String} opts.actor_type Filter to events with an actor of this type. This only needs to be included if querying for actor types without an ID. If `actor_gid` is included, this should be excluded. + * @param {String} opts.actor_gid Filter to events triggered by the actor with this ID. + * @param {String} opts.resource_gid Filter to events with this resource ID. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(AuditLogAPIApi, [{ + key: "getAuditLogEventsWithHttpInfo", + value: function getAuditLogEventsWithHttpInfo(workspace_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'workspace_gid' is set + if (workspace_gid === undefined || workspace_gid === null) { + throw new Error("Missing the required parameter 'workspace_gid' when calling getAuditLogEvents"); + } + var pathParams = { + 'workspace_gid': workspace_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/workspaces/{workspace_gid}/audit_log_events', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/workspaces/{workspace_gid}/audit_log_events', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/workspaces/{workspace_gid}/audit_log_events', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get audit log events + * Retrieve the audit log events that have been captured in your domain. This endpoint will return a list of [AuditLogEvent](/reference/audit-log-api) objects, sorted by creation time in ascending order. Note that the Audit Log API captures events from October 8th, 2021 and later. Queries for events before this date will not return results. There are a number of query parameters (below) that can be used to filter the set of [AuditLogEvent](/reference/audit-log-api) objects that are returned in the response. Any combination of query parameters is valid. When no filters are provided, all of the events that have been captured in your domain will match. The list of events will always be [paginated](/docs/pagination). The default limit is 1000 events. The next set of events can be retrieved using the `offset` from the previous response. If there are no events that match the provided filters in your domain, the endpoint will return `null` for the `next_page` field. Querying again with the same filters may return new events if they were captured after the last request. Once a response includes a `next_page` with an `offset`, subsequent requests can be made with the latest `offset` to poll for new events that match the provided filters. *Note: If the filters you provided match events in your domain and `next_page` is present in the response, we will continue to send `next_page` on subsequent requests even when there are no more events that match the filters. This was put in place so that you can implement an audit log stream that will return future events that match these filters. If you are not interested in future events that match the filters you have defined, you can rely on checking empty `data` response for the end of current events that match your filters.* When no `offset` is provided, the response will begin with the oldest events that match the provided filters. It is important to note that [AuditLogEvent](/reference/audit-log-api) objects will be permanently deleted from our systems after 90 days. If you wish to keep a permanent record of these events, we recommend using a SIEM tool to ingest and store these logs. + * @param {<&vendorExtensions.x-jsdoc-type>} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {Date} opts.start_at Filter to events created after this time (inclusive). + * @param {Date} opts.end_at Filter to events created before this time (exclusive). + * @param {String} opts.event_type Filter to events of this type. Refer to the [supported audit log events](/docs/audit-log-events#supported-audit-log-events) for a full list of values. + * @param {module:model/String} opts.actor_type Filter to events with an actor of this type. This only needs to be included if querying for actor types without an ID. If `actor_gid` is included, this should be excluded. + * @param {String} opts.actor_gid Filter to events triggered by the actor with this ID. + * @param {String} opts.resource_gid Filter to events with this resource ID. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/AuditLogEventArray} + */ + }, { + key: "getAuditLogEvents", + value: function getAuditLogEvents(workspace_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getAuditLogEventsWithHttpInfo(workspace_gid, opts); + } + return this.getAuditLogEventsWithHttpInfo(workspace_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/BatchAPIApi.js b/node_modules/asana/dist/api/BatchAPIApi.js new file mode 100644 index 000000000..b79b95607 --- /dev/null +++ b/node_modules/asana/dist/api/BatchAPIApi.js @@ -0,0 +1,114 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.BatchAPIApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* BatchAPI service. +* @module api/BatchAPIApi +* @version 3.0.3 +*/ +var BatchAPIApi = exports.BatchAPIApi = /*#__PURE__*/function () { + /** + * Constructs a new BatchAPIApi. + * @alias module:api/BatchAPIApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function BatchAPIApi(apiClient) { + _classCallCheck(this, BatchAPIApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Submit parallel requests + * Make multiple requests in parallel to Asana's API. + * @param {module:model/Object} body The requests to batch together via the Batch API. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(BatchAPIApi, [{ + key: "createBatchRequestWithHttpInfo", + value: function createBatchRequestWithHttpInfo(body, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling createBatchRequest"); + } + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/batch', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/batch', + 'httpMethod': 'POST', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/batch', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Submit parallel requests + * Make multiple requests in parallel to Asana's API. + * @param {<&vendorExtensions.x-jsdoc-type>} body The requests to batch together via the Batch API. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/BatchResponseArray} + */ + }, { + key: "createBatchRequest", + value: function createBatchRequest(body, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.createBatchRequestWithHttpInfo(body, opts); + } + return this.createBatchRequestWithHttpInfo(body, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/CustomFieldSettingsApi.js b/node_modules/asana/dist/api/CustomFieldSettingsApi.js new file mode 100644 index 000000000..73b7571de --- /dev/null +++ b/node_modules/asana/dist/api/CustomFieldSettingsApi.js @@ -0,0 +1,192 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.CustomFieldSettingsApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* CustomFieldSettings service. +* @module api/CustomFieldSettingsApi +* @version 3.0.3 +*/ +var CustomFieldSettingsApi = exports.CustomFieldSettingsApi = /*#__PURE__*/function () { + /** + * Constructs a new CustomFieldSettingsApi. + * @alias module:api/CustomFieldSettingsApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function CustomFieldSettingsApi(apiClient) { + _classCallCheck(this, CustomFieldSettingsApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Get a portfolio's custom fields + * Returns a list of all of the custom fields settings on a portfolio, in compact form. + * @param {String} portfolio_gid Globally unique identifier for the portfolio. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(CustomFieldSettingsApi, [{ + key: "getCustomFieldSettingsForPortfolioWithHttpInfo", + value: function getCustomFieldSettingsForPortfolioWithHttpInfo(portfolio_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'portfolio_gid' is set + if (portfolio_gid === undefined || portfolio_gid === null) { + throw new Error("Missing the required parameter 'portfolio_gid' when calling getCustomFieldSettingsForPortfolio"); + } + var pathParams = { + 'portfolio_gid': portfolio_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/portfolios/{portfolio_gid}/custom_field_settings', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/portfolios/{portfolio_gid}/custom_field_settings', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/portfolios/{portfolio_gid}/custom_field_settings', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a portfolio's custom fields + * Returns a list of all of the custom fields settings on a portfolio, in compact form. + * @param {<&vendorExtensions.x-jsdoc-type>} portfolio_gid Globally unique identifier for the portfolio. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/CustomFieldSettingResponseArray} + */ + }, { + key: "getCustomFieldSettingsForPortfolio", + value: function getCustomFieldSettingsForPortfolio(portfolio_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getCustomFieldSettingsForPortfolioWithHttpInfo(portfolio_gid, opts); + } + return this.getCustomFieldSettingsForPortfolioWithHttpInfo(portfolio_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a project's custom fields + * Returns a list of all of the custom fields settings on a project, in compact form. Note that, as in all queries to collections which return compact representation, `opt_fields` can be used to include more data than is returned in the compact representation. See the [documentation for input/output options](https://developers.asana.com/docs/inputoutput-options) for more information. + * @param {String} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getCustomFieldSettingsForProjectWithHttpInfo", + value: function getCustomFieldSettingsForProjectWithHttpInfo(project_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'project_gid' is set + if (project_gid === undefined || project_gid === null) { + throw new Error("Missing the required parameter 'project_gid' when calling getCustomFieldSettingsForProject"); + } + var pathParams = { + 'project_gid': project_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/projects/{project_gid}/custom_field_settings', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/projects/{project_gid}/custom_field_settings', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/projects/{project_gid}/custom_field_settings', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a project's custom fields + * Returns a list of all of the custom fields settings on a project, in compact form. Note that, as in all queries to collections which return compact representation, `opt_fields` can be used to include more data than is returned in the compact representation. See the [documentation for input/output options](https://developers.asana.com/docs/inputoutput-options) for more information. + * @param {<&vendorExtensions.x-jsdoc-type>} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/CustomFieldSettingResponseArray} + */ + }, { + key: "getCustomFieldSettingsForProject", + value: function getCustomFieldSettingsForProject(project_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getCustomFieldSettingsForProjectWithHttpInfo(project_gid, opts); + } + return this.getCustomFieldSettingsForProjectWithHttpInfo(project_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/CustomFieldsApi.js b/node_modules/asana/dist/api/CustomFieldsApi.js new file mode 100644 index 000000000..ac1c96c8e --- /dev/null +++ b/node_modules/asana/dist/api/CustomFieldsApi.js @@ -0,0 +1,455 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.CustomFieldsApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* CustomFields service. +* @module api/CustomFieldsApi +* @version 3.0.3 +*/ +var CustomFieldsApi = exports.CustomFieldsApi = /*#__PURE__*/function () { + /** + * Constructs a new CustomFieldsApi. + * @alias module:api/CustomFieldsApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function CustomFieldsApi(apiClient) { + _classCallCheck(this, CustomFieldsApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Create a custom field + * Creates a new custom field in a workspace. Every custom field is required to be created in a specific workspace, and this workspace cannot be changed once set. A custom field’s name must be unique within a workspace and not conflict with names of existing task properties such as `Due Date` or `Assignee`. A custom field’s type must be one of `text`, `enum`, `multi_enum`, `number`, `date`, or `people`. Returns the full record of the newly created custom field. + * @param {module:model/Object} body The custom field object to create. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(CustomFieldsApi, [{ + key: "createCustomFieldWithHttpInfo", + value: function createCustomFieldWithHttpInfo(body, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling createCustomField"); + } + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/custom_fields', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create a custom field + * Creates a new custom field in a workspace. Every custom field is required to be created in a specific workspace, and this workspace cannot be changed once set. A custom field’s name must be unique within a workspace and not conflict with names of existing task properties such as `Due Date` or `Assignee`. A custom field’s type must be one of `text`, `enum`, `multi_enum`, `number`, `date`, or `people`. Returns the full record of the newly created custom field. + * @param {<&vendorExtensions.x-jsdoc-type>} body The custom field object to create. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/CustomFieldResponseData} + */ + }, { + key: "createCustomField", + value: function createCustomField(body, opts) { + return this.createCustomFieldWithHttpInfo(body, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Create an enum option + * Creates an enum option and adds it to this custom field’s list of enum options. A custom field can have at most 500 enum options (including disabled options). By default new enum options are inserted at the end of a custom field’s list. Locked custom fields can only have enum options added by the user who locked the field. Returns the full record of the newly created enum option. + * @param {String} custom_field_gid Globally unique identifier for the custom field. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body The enum option object to create. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "createEnumOptionForCustomFieldWithHttpInfo", + value: function createEnumOptionForCustomFieldWithHttpInfo(custom_field_gid, opts) { + opts = opts || {}; + var postBody = opts['body']; + // verify the required parameter 'custom_field_gid' is set + if (custom_field_gid === undefined || custom_field_gid === null) { + throw new Error("Missing the required parameter 'custom_field_gid' when calling createEnumOptionForCustomField"); + } + var pathParams = { + 'custom_field_gid': custom_field_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/custom_fields/{custom_field_gid}/enum_options', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create an enum option + * Creates an enum option and adds it to this custom field’s list of enum options. A custom field can have at most 500 enum options (including disabled options). By default new enum options are inserted at the end of a custom field’s list. Locked custom fields can only have enum options added by the user who locked the field. Returns the full record of the newly created enum option. + * @param {<&vendorExtensions.x-jsdoc-type>} custom_field_gid Globally unique identifier for the custom field. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body The enum option object to create. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EnumOptionData} + */ + }, { + key: "createEnumOptionForCustomField", + value: function createEnumOptionForCustomField(custom_field_gid, opts) { + return this.createEnumOptionForCustomFieldWithHttpInfo(custom_field_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Delete a custom field + * A specific, existing custom field can be deleted by making a DELETE request on the URL for that custom field. Locked custom fields can only be deleted by the user who locked the field. Returns an empty data record. + * @param {String} custom_field_gid Globally unique identifier for the custom field. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "deleteCustomFieldWithHttpInfo", + value: function deleteCustomFieldWithHttpInfo(custom_field_gid) { + var postBody = null; + // verify the required parameter 'custom_field_gid' is set + if (custom_field_gid === undefined || custom_field_gid === null) { + throw new Error("Missing the required parameter 'custom_field_gid' when calling deleteCustomField"); + } + var pathParams = { + 'custom_field_gid': custom_field_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/custom_fields/{custom_field_gid}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Delete a custom field + * A specific, existing custom field can be deleted by making a DELETE request on the URL for that custom field. Locked custom fields can only be deleted by the user who locked the field. Returns an empty data record. + * @param {<&vendorExtensions.x-jsdoc-type>} custom_field_gid Globally unique identifier for the custom field. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "deleteCustomField", + value: function deleteCustomField(custom_field_gid) { + return this.deleteCustomFieldWithHttpInfo(custom_field_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a custom field + * Get the complete definition of a custom field’s metadata. Since custom fields can be defined for one of a number of types, and these types have different data and behaviors, there are fields that are relevant to a particular type. For instance, as noted above, enum_options is only relevant for the enum type and defines the set of choices that the enum could represent. The examples below show some of these type-specific custom field definitions. + * @param {String} custom_field_gid Globally unique identifier for the custom field. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getCustomFieldWithHttpInfo", + value: function getCustomFieldWithHttpInfo(custom_field_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'custom_field_gid' is set + if (custom_field_gid === undefined || custom_field_gid === null) { + throw new Error("Missing the required parameter 'custom_field_gid' when calling getCustomField"); + } + var pathParams = { + 'custom_field_gid': custom_field_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/custom_fields/{custom_field_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a custom field + * Get the complete definition of a custom field’s metadata. Since custom fields can be defined for one of a number of types, and these types have different data and behaviors, there are fields that are relevant to a particular type. For instance, as noted above, enum_options is only relevant for the enum type and defines the set of choices that the enum could represent. The examples below show some of these type-specific custom field definitions. + * @param {<&vendorExtensions.x-jsdoc-type>} custom_field_gid Globally unique identifier for the custom field. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/CustomFieldResponseData} + */ + }, { + key: "getCustomField", + value: function getCustomField(custom_field_gid, opts) { + return this.getCustomFieldWithHttpInfo(custom_field_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a workspace's custom fields + * Returns a list of the compact representation of all of the custom fields in a workspace. + * @param {String} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getCustomFieldsForWorkspaceWithHttpInfo", + value: function getCustomFieldsForWorkspaceWithHttpInfo(workspace_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'workspace_gid' is set + if (workspace_gid === undefined || workspace_gid === null) { + throw new Error("Missing the required parameter 'workspace_gid' when calling getCustomFieldsForWorkspace"); + } + var pathParams = { + 'workspace_gid': workspace_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/workspaces/{workspace_gid}/custom_fields', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/workspaces/{workspace_gid}/custom_fields', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/workspaces/{workspace_gid}/custom_fields', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a workspace's custom fields + * Returns a list of the compact representation of all of the custom fields in a workspace. + * @param {<&vendorExtensions.x-jsdoc-type>} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/CustomFieldResponseArray} + */ + }, { + key: "getCustomFieldsForWorkspace", + value: function getCustomFieldsForWorkspace(workspace_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getCustomFieldsForWorkspaceWithHttpInfo(workspace_gid, opts); + } + return this.getCustomFieldsForWorkspaceWithHttpInfo(workspace_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Reorder a custom field's enum + * Moves a particular enum option to be either before or after another specified enum option in the custom field. Locked custom fields can only be reordered by the user who locked the field. + * @param {String} custom_field_gid Globally unique identifier for the custom field. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body The enum option object to create. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "insertEnumOptionForCustomFieldWithHttpInfo", + value: function insertEnumOptionForCustomFieldWithHttpInfo(custom_field_gid, opts) { + opts = opts || {}; + var postBody = opts['body']; + // verify the required parameter 'custom_field_gid' is set + if (custom_field_gid === undefined || custom_field_gid === null) { + throw new Error("Missing the required parameter 'custom_field_gid' when calling insertEnumOptionForCustomField"); + } + var pathParams = { + 'custom_field_gid': custom_field_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/custom_fields/{custom_field_gid}/enum_options/insert', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Reorder a custom field's enum + * Moves a particular enum option to be either before or after another specified enum option in the custom field. Locked custom fields can only be reordered by the user who locked the field. + * @param {<&vendorExtensions.x-jsdoc-type>} custom_field_gid Globally unique identifier for the custom field. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body The enum option object to create. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EnumOptionData} + */ + }, { + key: "insertEnumOptionForCustomField", + value: function insertEnumOptionForCustomField(custom_field_gid, opts) { + return this.insertEnumOptionForCustomFieldWithHttpInfo(custom_field_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Update a custom field + * A specific, existing custom field can be updated by making a PUT request on the URL for that custom field. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the custom field. A custom field’s `type` cannot be updated. An enum custom field’s `enum_options` cannot be updated with this endpoint. Instead see “Work With Enum Options” for information on how to update `enum_options`. Locked custom fields can only be updated by the user who locked the field. Returns the complete updated custom field record. + * @param {String} custom_field_gid Globally unique identifier for the custom field. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body The custom field object with all updated properties. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "updateCustomFieldWithHttpInfo", + value: function updateCustomFieldWithHttpInfo(custom_field_gid, opts) { + opts = opts || {}; + var postBody = opts['body']; + // verify the required parameter 'custom_field_gid' is set + if (custom_field_gid === undefined || custom_field_gid === null) { + throw new Error("Missing the required parameter 'custom_field_gid' when calling updateCustomField"); + } + var pathParams = { + 'custom_field_gid': custom_field_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/custom_fields/{custom_field_gid}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Update a custom field + * A specific, existing custom field can be updated by making a PUT request on the URL for that custom field. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the custom field. A custom field’s `type` cannot be updated. An enum custom field’s `enum_options` cannot be updated with this endpoint. Instead see “Work With Enum Options” for information on how to update `enum_options`. Locked custom fields can only be updated by the user who locked the field. Returns the complete updated custom field record. + * @param {<&vendorExtensions.x-jsdoc-type>} custom_field_gid Globally unique identifier for the custom field. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body The custom field object with all updated properties. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/CustomFieldResponseData} + */ + }, { + key: "updateCustomField", + value: function updateCustomField(custom_field_gid, opts) { + return this.updateCustomFieldWithHttpInfo(custom_field_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Update an enum option + * Updates an existing enum option. Enum custom fields require at least one enabled enum option. Locked custom fields can only be updated by the user who locked the field. Returns the full record of the updated enum option. + * @param {String} enum_option_gid Globally unique identifier for the enum option. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body The enum option object to update + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "updateEnumOptionWithHttpInfo", + value: function updateEnumOptionWithHttpInfo(enum_option_gid, opts) { + opts = opts || {}; + var postBody = opts['body']; + // verify the required parameter 'enum_option_gid' is set + if (enum_option_gid === undefined || enum_option_gid === null) { + throw new Error("Missing the required parameter 'enum_option_gid' when calling updateEnumOption"); + } + var pathParams = { + 'enum_option_gid': enum_option_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/enum_options/{enum_option_gid}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Update an enum option + * Updates an existing enum option. Enum custom fields require at least one enabled enum option. Locked custom fields can only be updated by the user who locked the field. Returns the full record of the updated enum option. + * @param {<&vendorExtensions.x-jsdoc-type>} enum_option_gid Globally unique identifier for the enum option. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body The enum option object to update + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EnumOptionData} + */ + }, { + key: "updateEnumOption", + value: function updateEnumOption(enum_option_gid, opts) { + return this.updateEnumOptionWithHttpInfo(enum_option_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/EventsApi.js b/node_modules/asana/dist/api/EventsApi.js new file mode 100644 index 000000000..d262f7fec --- /dev/null +++ b/node_modules/asana/dist/api/EventsApi.js @@ -0,0 +1,117 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.EventsApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* Events service. +* @module api/EventsApi +* @version 3.0.3 +*/ +var EventsApi = exports.EventsApi = /*#__PURE__*/function () { + /** + * Constructs a new EventsApi. + * @alias module:api/EventsApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function EventsApi(apiClient) { + _classCallCheck(this, EventsApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Get events on a resource + * Returns the full record for all events that have occurred since the sync token was created. A `GET` request to the endpoint `/[path_to_resource]/events` can be made in lieu of including the resource ID in the data for the request. Asana limits a single sync token to 100 events. If more than 100 events exist for a given resource, `has_more: true` will be returned in the response, indicating that there are more events to pull. *Note: The resource returned will be the resource that triggered the event. This may be different from the one that the events were requested for. For example, a subscription to a project will contain events for tasks contained within the project.* + * @param {String} resource A resource ID to subscribe to. The resource can be a task, project, or goal. + * @param {Object} opts Optional parameters + * @param {String} opts.sync A sync token received from the last request, or none on first sync. Events will be returned from the point in time that the sync token was generated. *Note: On your first request, omit the sync token. The response will be the same as for an expired sync token, and will include a new valid sync token.If the sync token is too old (which may happen from time to time) the API will return a `412 Precondition Failed` error, and include a fresh sync token in the response.* + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(EventsApi, [{ + key: "getEventsWithHttpInfo", + value: function getEventsWithHttpInfo(resource, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'resource' is set + if (resource === undefined || resource === null) { + throw new Error("Missing the required parameter 'resource' when calling getEvents"); + } + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + queryParams['resource'] = resource; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/events', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/events', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/events', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get events on a resource + * Returns the full record for all events that have occurred since the sync token was created. A `GET` request to the endpoint `/[path_to_resource]/events` can be made in lieu of including the resource ID in the data for the request. Asana limits a single sync token to 100 events. If more than 100 events exist for a given resource, `has_more: true` will be returned in the response, indicating that there are more events to pull. *Note: The resource returned will be the resource that triggered the event. This may be different from the one that the events were requested for. For example, a subscription to a project will contain events for tasks contained within the project.* + * @param {<&vendorExtensions.x-jsdoc-type>} resource A resource ID to subscribe to. The resource can be a task, project, or goal. + * @param {Object} opts Optional parameters + * @param {String} opts.sync A sync token received from the last request, or none on first sync. Events will be returned from the point in time that the sync token was generated. *Note: On your first request, omit the sync token. The response will be the same as for an expired sync token, and will include a new valid sync token.If the sync token is too old (which may happen from time to time) the API will return a `412 Precondition Failed` error, and include a fresh sync token in the response.* + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EventResponseArray} + */ + }, { + key: "getEvents", + value: function getEvents(resource, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getEventsWithHttpInfo(resource, opts); + } + return this.getEventsWithHttpInfo(resource, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/GoalRelationshipsApi.js b/node_modules/asana/dist/api/GoalRelationshipsApi.js new file mode 100644 index 000000000..0cdafbe31 --- /dev/null +++ b/node_modules/asana/dist/api/GoalRelationshipsApi.js @@ -0,0 +1,324 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.GoalRelationshipsApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* GoalRelationships service. +* @module api/GoalRelationshipsApi +* @version 3.0.3 +*/ +var GoalRelationshipsApi = exports.GoalRelationshipsApi = /*#__PURE__*/function () { + /** + * Constructs a new GoalRelationshipsApi. + * @alias module:api/GoalRelationshipsApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function GoalRelationshipsApi(apiClient) { + _classCallCheck(this, GoalRelationshipsApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Add a supporting goal relationship + * Creates a goal relationship by adding a supporting resource to a given goal. Returns the newly created goal relationship record. + * @param {module:model/Object} body The supporting resource to be added to the goal + * @param {String} goal_gid Globally unique identifier for the goal. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(GoalRelationshipsApi, [{ + key: "addSupportingRelationshipWithHttpInfo", + value: function addSupportingRelationshipWithHttpInfo(body, goal_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling addSupportingRelationship"); + } + // verify the required parameter 'goal_gid' is set + if (goal_gid === undefined || goal_gid === null) { + throw new Error("Missing the required parameter 'goal_gid' when calling addSupportingRelationship"); + } + var pathParams = { + 'goal_gid': goal_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/goals/{goal_gid}/addSupportingRelationship', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Add a supporting goal relationship + * Creates a goal relationship by adding a supporting resource to a given goal. Returns the newly created goal relationship record. + * @param {<&vendorExtensions.x-jsdoc-type>} body The supporting resource to be added to the goal + * @param {<&vendorExtensions.x-jsdoc-type>} goal_gid Globally unique identifier for the goal. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/GoalRelationshipResponseData} + */ + }, { + key: "addSupportingRelationship", + value: function addSupportingRelationship(body, goal_gid, opts) { + return this.addSupportingRelationshipWithHttpInfo(body, goal_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a goal relationship + * Returns the complete updated goal relationship record for a single goal relationship. + * @param {String} goal_relationship_gid Globally unique identifier for the goal relationship. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getGoalRelationshipWithHttpInfo", + value: function getGoalRelationshipWithHttpInfo(goal_relationship_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'goal_relationship_gid' is set + if (goal_relationship_gid === undefined || goal_relationship_gid === null) { + throw new Error("Missing the required parameter 'goal_relationship_gid' when calling getGoalRelationship"); + } + var pathParams = { + 'goal_relationship_gid': goal_relationship_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/goal_relationships/{goal_relationship_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a goal relationship + * Returns the complete updated goal relationship record for a single goal relationship. + * @param {<&vendorExtensions.x-jsdoc-type>} goal_relationship_gid Globally unique identifier for the goal relationship. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/GoalRelationshipResponseData} + */ + }, { + key: "getGoalRelationship", + value: function getGoalRelationship(goal_relationship_gid, opts) { + return this.getGoalRelationshipWithHttpInfo(goal_relationship_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get goal relationships + * Returns compact goal relationship records. + * @param {String} supported_goal Globally unique identifier for the supported goal in the goal relationship. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {String} opts.resource_subtype If provided, filter to goal relationships with a given resource_subtype. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getGoalRelationshipsWithHttpInfo", + value: function getGoalRelationshipsWithHttpInfo(supported_goal, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'supported_goal' is set + if (supported_goal === undefined || supported_goal === null) { + throw new Error("Missing the required parameter 'supported_goal' when calling getGoalRelationships"); + } + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + queryParams['supported_goal'] = supported_goal; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/goal_relationships', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/goal_relationships', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/goal_relationships', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get goal relationships + * Returns compact goal relationship records. + * @param {<&vendorExtensions.x-jsdoc-type>} supported_goal Globally unique identifier for the supported goal in the goal relationship. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {String} opts.resource_subtype If provided, filter to goal relationships with a given resource_subtype. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/GoalRelationshipResponseArray} + */ + }, { + key: "getGoalRelationships", + value: function getGoalRelationships(supported_goal, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getGoalRelationshipsWithHttpInfo(supported_goal, opts); + } + return this.getGoalRelationshipsWithHttpInfo(supported_goal, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Removes a supporting goal relationship + * Removes a goal relationship for a given parent goal. + * @param {module:model/Object} body The supporting resource to be removed from the goal + * @param {String} goal_gid Globally unique identifier for the goal. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "removeSupportingRelationshipWithHttpInfo", + value: function removeSupportingRelationshipWithHttpInfo(body, goal_gid) { + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling removeSupportingRelationship"); + } + // verify the required parameter 'goal_gid' is set + if (goal_gid === undefined || goal_gid === null) { + throw new Error("Missing the required parameter 'goal_gid' when calling removeSupportingRelationship"); + } + var pathParams = { + 'goal_gid': goal_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/goals/{goal_gid}/removeSupportingRelationship', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Removes a supporting goal relationship + * Removes a goal relationship for a given parent goal. + * @param {<&vendorExtensions.x-jsdoc-type>} body The supporting resource to be removed from the goal + * @param {<&vendorExtensions.x-jsdoc-type>} goal_gid Globally unique identifier for the goal. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "removeSupportingRelationship", + value: function removeSupportingRelationship(body, goal_gid) { + return this.removeSupportingRelationshipWithHttpInfo(body, goal_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Update a goal relationship + * An existing goal relationship can be updated by making a PUT request on the URL for that goal relationship. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated goal relationship record. + * @param {module:model/Object} body The updated fields for the goal relationship. + * @param {String} goal_relationship_gid Globally unique identifier for the goal relationship. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "updateGoalRelationshipWithHttpInfo", + value: function updateGoalRelationshipWithHttpInfo(body, goal_relationship_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling updateGoalRelationship"); + } + // verify the required parameter 'goal_relationship_gid' is set + if (goal_relationship_gid === undefined || goal_relationship_gid === null) { + throw new Error("Missing the required parameter 'goal_relationship_gid' when calling updateGoalRelationship"); + } + var pathParams = { + 'goal_relationship_gid': goal_relationship_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/goal_relationships/{goal_relationship_gid}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Update a goal relationship + * An existing goal relationship can be updated by making a PUT request on the URL for that goal relationship. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated goal relationship record. + * @param {<&vendorExtensions.x-jsdoc-type>} body The updated fields for the goal relationship. + * @param {<&vendorExtensions.x-jsdoc-type>} goal_relationship_gid Globally unique identifier for the goal relationship. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/GoalRelationshipResponseData} + */ + }, { + key: "updateGoalRelationship", + value: function updateGoalRelationship(body, goal_relationship_gid, opts) { + return this.updateGoalRelationshipWithHttpInfo(body, goal_relationship_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/GoalsApi.js b/node_modules/asana/dist/api/GoalsApi.js new file mode 100644 index 000000000..598e7a74f --- /dev/null +++ b/node_modules/asana/dist/api/GoalsApi.js @@ -0,0 +1,599 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.GoalsApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* Goals service. +* @module api/GoalsApi +* @version 3.0.3 +*/ +var GoalsApi = exports.GoalsApi = /*#__PURE__*/function () { + /** + * Constructs a new GoalsApi. + * @alias module:api/GoalsApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function GoalsApi(apiClient) { + _classCallCheck(this, GoalsApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Add a collaborator to a goal + * Adds followers to a goal. Returns the goal the followers were added to. Each goal can be associated with zero or more followers in the system. Requests to add/remove followers, if successful, will return the complete updated goal record, described above. + * @param {module:model/Object} body The followers to be added as collaborators + * @param {String} goal_gid Globally unique identifier for the goal. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(GoalsApi, [{ + key: "addFollowersWithHttpInfo", + value: function addFollowersWithHttpInfo(body, goal_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling addFollowers"); + } + // verify the required parameter 'goal_gid' is set + if (goal_gid === undefined || goal_gid === null) { + throw new Error("Missing the required parameter 'goal_gid' when calling addFollowers"); + } + var pathParams = { + 'goal_gid': goal_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/goals/{goal_gid}/addFollowers', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Add a collaborator to a goal + * Adds followers to a goal. Returns the goal the followers were added to. Each goal can be associated with zero or more followers in the system. Requests to add/remove followers, if successful, will return the complete updated goal record, described above. + * @param {<&vendorExtensions.x-jsdoc-type>} body The followers to be added as collaborators + * @param {<&vendorExtensions.x-jsdoc-type>} goal_gid Globally unique identifier for the goal. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/GoalResponseData} + */ + }, { + key: "addFollowers", + value: function addFollowers(body, goal_gid, opts) { + return this.addFollowersWithHttpInfo(body, goal_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Create a goal + * Creates a new goal in a workspace or team. Returns the full record of the newly created goal. + * @param {module:model/Object} body The goal to create. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "createGoalWithHttpInfo", + value: function createGoalWithHttpInfo(body, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling createGoal"); + } + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/goals', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create a goal + * Creates a new goal in a workspace or team. Returns the full record of the newly created goal. + * @param {<&vendorExtensions.x-jsdoc-type>} body The goal to create. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/GoalResponseData} + */ + }, { + key: "createGoal", + value: function createGoal(body, opts) { + return this.createGoalWithHttpInfo(body, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Create a goal metric + * Creates and adds a goal metric to a specified goal. Note that this replaces an existing goal metric if one already exists. + * @param {module:model/Object} body The goal metric to create. + * @param {String} goal_gid Globally unique identifier for the goal. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "createGoalMetricWithHttpInfo", + value: function createGoalMetricWithHttpInfo(body, goal_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling createGoalMetric"); + } + // verify the required parameter 'goal_gid' is set + if (goal_gid === undefined || goal_gid === null) { + throw new Error("Missing the required parameter 'goal_gid' when calling createGoalMetric"); + } + var pathParams = { + 'goal_gid': goal_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/goals/{goal_gid}/setMetric', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create a goal metric + * Creates and adds a goal metric to a specified goal. Note that this replaces an existing goal metric if one already exists. + * @param {<&vendorExtensions.x-jsdoc-type>} body The goal metric to create. + * @param {<&vendorExtensions.x-jsdoc-type>} goal_gid Globally unique identifier for the goal. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/GoalResponseData} + */ + }, { + key: "createGoalMetric", + value: function createGoalMetric(body, goal_gid, opts) { + return this.createGoalMetricWithHttpInfo(body, goal_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Delete a goal + * A specific, existing goal can be deleted by making a DELETE request on the URL for that goal. Returns an empty data record. + * @param {String} goal_gid Globally unique identifier for the goal. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "deleteGoalWithHttpInfo", + value: function deleteGoalWithHttpInfo(goal_gid) { + var postBody = null; + // verify the required parameter 'goal_gid' is set + if (goal_gid === undefined || goal_gid === null) { + throw new Error("Missing the required parameter 'goal_gid' when calling deleteGoal"); + } + var pathParams = { + 'goal_gid': goal_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/goals/{goal_gid}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Delete a goal + * A specific, existing goal can be deleted by making a DELETE request on the URL for that goal. Returns an empty data record. + * @param {<&vendorExtensions.x-jsdoc-type>} goal_gid Globally unique identifier for the goal. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "deleteGoal", + value: function deleteGoal(goal_gid) { + return this.deleteGoalWithHttpInfo(goal_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a goal + * Returns the complete goal record for a single goal. + * @param {String} goal_gid Globally unique identifier for the goal. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getGoalWithHttpInfo", + value: function getGoalWithHttpInfo(goal_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'goal_gid' is set + if (goal_gid === undefined || goal_gid === null) { + throw new Error("Missing the required parameter 'goal_gid' when calling getGoal"); + } + var pathParams = { + 'goal_gid': goal_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/goals/{goal_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a goal + * Returns the complete goal record for a single goal. + * @param {<&vendorExtensions.x-jsdoc-type>} goal_gid Globally unique identifier for the goal. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/GoalResponseData} + */ + }, { + key: "getGoal", + value: function getGoal(goal_gid, opts) { + return this.getGoalWithHttpInfo(goal_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get goals + * Returns compact goal records. + * @param {Object} opts Optional parameters + * @param {String} opts.portfolio Globally unique identifier for supporting portfolio. + * @param {String} opts.project Globally unique identifier for supporting project. + * @param {String} opts.task Globally unique identifier for supporting task. + * @param {Boolean} opts.is_workspace_level Filter to goals with is_workspace_level set to query value. Must be used with the workspace parameter. + * @param {String} opts.team Globally unique identifier for the team. + * @param {String} opts.workspace Globally unique identifier for the workspace. + * @param {Array.} opts.time_periods Globally unique identifiers for the time periods. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getGoalsWithHttpInfo", + value: function getGoalsWithHttpInfo(opts) { + opts = opts || {}; + var postBody = null; + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/goals', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/goals', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/goals', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get goals + * Returns compact goal records. + * @param {Object} opts Optional parameters + * @param {String} opts.portfolio Globally unique identifier for supporting portfolio. + * @param {String} opts.project Globally unique identifier for supporting project. + * @param {String} opts.task Globally unique identifier for supporting task. + * @param {Boolean} opts.is_workspace_level Filter to goals with is_workspace_level set to query value. Must be used with the workspace parameter. + * @param {String} opts.team Globally unique identifier for the team. + * @param {String} opts.workspace Globally unique identifier for the workspace. + * @param {Array.} opts.time_periods Globally unique identifiers for the time periods. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/GoalResponseArray} + */ + }, { + key: "getGoals", + value: function getGoals(opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getGoalsWithHttpInfo(opts); + } + return this.getGoalsWithHttpInfo(opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get parent goals from a goal + * Returns a compact representation of all of the parent goals of a goal. + * @param {String} goal_gid Globally unique identifier for the goal. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getParentGoalsForGoalWithHttpInfo", + value: function getParentGoalsForGoalWithHttpInfo(goal_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'goal_gid' is set + if (goal_gid === undefined || goal_gid === null) { + throw new Error("Missing the required parameter 'goal_gid' when calling getParentGoalsForGoal"); + } + var pathParams = { + 'goal_gid': goal_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/goals/{goal_gid}/parentGoals', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/goals/{goal_gid}/parentGoals', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/goals/{goal_gid}/parentGoals', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get parent goals from a goal + * Returns a compact representation of all of the parent goals of a goal. + * @param {<&vendorExtensions.x-jsdoc-type>} goal_gid Globally unique identifier for the goal. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/GoalResponseArray} + */ + }, { + key: "getParentGoalsForGoal", + value: function getParentGoalsForGoal(goal_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getParentGoalsForGoalWithHttpInfo(goal_gid, opts); + } + return this.getParentGoalsForGoalWithHttpInfo(goal_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Remove a collaborator from a goal + * Removes followers from a goal. Returns the goal the followers were removed from. Each goal can be associated with zero or more followers in the system. Requests to add/remove followers, if successful, will return the complete updated goal record, described above. + * @param {module:model/Object} body The followers to be removed as collaborators + * @param {String} goal_gid Globally unique identifier for the goal. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "removeFollowersWithHttpInfo", + value: function removeFollowersWithHttpInfo(body, goal_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling removeFollowers"); + } + // verify the required parameter 'goal_gid' is set + if (goal_gid === undefined || goal_gid === null) { + throw new Error("Missing the required parameter 'goal_gid' when calling removeFollowers"); + } + var pathParams = { + 'goal_gid': goal_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/goals/{goal_gid}/removeFollowers', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Remove a collaborator from a goal + * Removes followers from a goal. Returns the goal the followers were removed from. Each goal can be associated with zero or more followers in the system. Requests to add/remove followers, if successful, will return the complete updated goal record, described above. + * @param {<&vendorExtensions.x-jsdoc-type>} body The followers to be removed as collaborators + * @param {<&vendorExtensions.x-jsdoc-type>} goal_gid Globally unique identifier for the goal. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/GoalResponseData} + */ + }, { + key: "removeFollowers", + value: function removeFollowers(body, goal_gid, opts) { + return this.removeFollowersWithHttpInfo(body, goal_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Update a goal + * An existing goal can be updated by making a PUT request on the URL for that goal. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated goal record. + * @param {module:model/Object} body The updated fields for the goal. + * @param {String} goal_gid Globally unique identifier for the goal. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "updateGoalWithHttpInfo", + value: function updateGoalWithHttpInfo(body, goal_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling updateGoal"); + } + // verify the required parameter 'goal_gid' is set + if (goal_gid === undefined || goal_gid === null) { + throw new Error("Missing the required parameter 'goal_gid' when calling updateGoal"); + } + var pathParams = { + 'goal_gid': goal_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/goals/{goal_gid}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Update a goal + * An existing goal can be updated by making a PUT request on the URL for that goal. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated goal record. + * @param {<&vendorExtensions.x-jsdoc-type>} body The updated fields for the goal. + * @param {<&vendorExtensions.x-jsdoc-type>} goal_gid Globally unique identifier for the goal. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/GoalResponseData} + */ + }, { + key: "updateGoal", + value: function updateGoal(body, goal_gid, opts) { + return this.updateGoalWithHttpInfo(body, goal_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Update a goal metric + * Updates a goal's existing metric's `current_number_value` if one exists, otherwise responds with a 400 status code. Returns the complete updated goal metric record. + * @param {module:model/Object} body The updated fields for the goal metric. + * @param {String} goal_gid Globally unique identifier for the goal. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "updateGoalMetricWithHttpInfo", + value: function updateGoalMetricWithHttpInfo(body, goal_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling updateGoalMetric"); + } + // verify the required parameter 'goal_gid' is set + if (goal_gid === undefined || goal_gid === null) { + throw new Error("Missing the required parameter 'goal_gid' when calling updateGoalMetric"); + } + var pathParams = { + 'goal_gid': goal_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/goals/{goal_gid}/setMetricCurrentValue', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Update a goal metric + * Updates a goal's existing metric's `current_number_value` if one exists, otherwise responds with a 400 status code. Returns the complete updated goal metric record. + * @param {<&vendorExtensions.x-jsdoc-type>} body The updated fields for the goal metric. + * @param {<&vendorExtensions.x-jsdoc-type>} goal_gid Globally unique identifier for the goal. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/GoalResponseData} + */ + }, { + key: "updateGoalMetric", + value: function updateGoalMetric(body, goal_gid, opts) { + return this.updateGoalMetricWithHttpInfo(body, goal_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/JobsApi.js b/node_modules/asana/dist/api/JobsApi.js new file mode 100644 index 000000000..d85948272 --- /dev/null +++ b/node_modules/asana/dist/api/JobsApi.js @@ -0,0 +1,96 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.JobsApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* Jobs service. +* @module api/JobsApi +* @version 3.0.3 +*/ +var JobsApi = exports.JobsApi = /*#__PURE__*/function () { + /** + * Constructs a new JobsApi. + * @alias module:api/JobsApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function JobsApi(apiClient) { + _classCallCheck(this, JobsApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Get a job by id + * Returns the full record for a job. + * @param {String} job_gid Globally unique identifier for the job. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(JobsApi, [{ + key: "getJobWithHttpInfo", + value: function getJobWithHttpInfo(job_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'job_gid' is set + if (job_gid === undefined || job_gid === null) { + throw new Error("Missing the required parameter 'job_gid' when calling getJob"); + } + var pathParams = { + 'job_gid': job_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/jobs/{job_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a job by id + * Returns the full record for a job. + * @param {<&vendorExtensions.x-jsdoc-type>} job_gid Globally unique identifier for the job. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/JobResponseData} + */ + }, { + key: "getJob", + value: function getJob(job_gid, opts) { + return this.getJobWithHttpInfo(job_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/MembershipsApi.js b/node_modules/asana/dist/api/MembershipsApi.js new file mode 100644 index 000000000..ba0d9c295 --- /dev/null +++ b/node_modules/asana/dist/api/MembershipsApi.js @@ -0,0 +1,292 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.MembershipsApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* Memberships service. +* @module api/MembershipsApi +* @version 3.0.3 +*/ +var MembershipsApi = exports.MembershipsApi = /*#__PURE__*/function () { + /** + * Constructs a new MembershipsApi. + * @alias module:api/MembershipsApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function MembershipsApi(apiClient) { + _classCallCheck(this, MembershipsApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Create a membership + * Creates a new membership in a `goal` or `project`. `Teams` or `users` can be a member of `goals` or `projects`. Returns the full record of the newly created membership. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body The updated fields for the membership. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(MembershipsApi, [{ + key: "createMembershipWithHttpInfo", + value: function createMembershipWithHttpInfo(opts) { + opts = opts || {}; + var postBody = opts['body']; + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/memberships', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create a membership + * Creates a new membership in a `goal` or `project`. `Teams` or `users` can be a member of `goals` or `projects`. Returns the full record of the newly created membership. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body The updated fields for the membership. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/MembershipResponseData} + */ + }, { + key: "createMembership", + value: function createMembership(opts) { + return this.createMembershipWithHttpInfo(opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Delete a membership + * A specific, existing membership for a `goal` or `project` can be deleted by making a `DELETE` request on the URL for that membership. Returns an empty data record. + * @param {String} membership_gid Globally unique identifier for the membership. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "deleteMembershipWithHttpInfo", + value: function deleteMembershipWithHttpInfo(membership_gid) { + var postBody = null; + // verify the required parameter 'membership_gid' is set + if (membership_gid === undefined || membership_gid === null) { + throw new Error("Missing the required parameter 'membership_gid' when calling deleteMembership"); + } + var pathParams = { + 'membership_gid': membership_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/memberships/{membership_gid}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Delete a membership + * A specific, existing membership for a `goal` or `project` can be deleted by making a `DELETE` request on the URL for that membership. Returns an empty data record. + * @param {<&vendorExtensions.x-jsdoc-type>} membership_gid Globally unique identifier for the membership. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "deleteMembership", + value: function deleteMembership(membership_gid) { + return this.deleteMembershipWithHttpInfo(membership_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a membership + * Returns compact `project_membership` record for a single membership. `GET` only supports project memberships currently + * @param {String} membership_gid Globally unique identifier for the membership. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getMembershipWithHttpInfo", + value: function getMembershipWithHttpInfo(membership_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'membership_gid' is set + if (membership_gid === undefined || membership_gid === null) { + throw new Error("Missing the required parameter 'membership_gid' when calling getMembership"); + } + var pathParams = { + 'membership_gid': membership_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/memberships/{membership_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a membership + * Returns compact `project_membership` record for a single membership. `GET` only supports project memberships currently + * @param {<&vendorExtensions.x-jsdoc-type>} membership_gid Globally unique identifier for the membership. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectMembershipCompactResponseData} + */ + }, { + key: "getMembership", + value: function getMembership(membership_gid, opts) { + return this.getMembershipWithHttpInfo(membership_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get multiple memberships + * Returns compact `goal_membership` or `project_membership` records. The possible types for `parent` in this request are `goal` or `project`. An additional member (user GID or team GID) can be passed in to filter to a specific membership. + * @param {Object} opts Optional parameters + * @param {String} opts.parent Globally unique identifier for `goal` or `project`. + * @param {String} opts.member Globally unique identifier for `team` or `user`. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getMembershipsWithHttpInfo", + value: function getMembershipsWithHttpInfo(opts) { + opts = opts || {}; + var postBody = null; + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/memberships', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/memberships', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/memberships', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get multiple memberships + * Returns compact `goal_membership` or `project_membership` records. The possible types for `parent` in this request are `goal` or `project`. An additional member (user GID or team GID) can be passed in to filter to a specific membership. + * @param {Object} opts Optional parameters + * @param {String} opts.parent Globally unique identifier for `goal` or `project`. + * @param {String} opts.member Globally unique identifier for `team` or `user`. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/MembershipResponseArray} + */ + }, { + key: "getMemberships", + value: function getMemberships(opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getMembershipsWithHttpInfo(opts); + } + return this.getMembershipsWithHttpInfo(opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Update a membership + * An existing membership can be updated by making a `PUT` request on the URL for that goal. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Memberships on `goals` and `projects` can be updated. Returns the full record of the updated membership. + * @param {module:model/Object} body The membership to update. + * @param {String} membership_gid Globally unique identifier for the membership. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "updateMembershipWithHttpInfo", + value: function updateMembershipWithHttpInfo(body, membership_gid) { + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling updateMembership"); + } + // verify the required parameter 'membership_gid' is set + if (membership_gid === undefined || membership_gid === null) { + throw new Error("Missing the required parameter 'membership_gid' when calling updateMembership"); + } + var pathParams = { + 'membership_gid': membership_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/memberships/{membership_gid}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Update a membership + * An existing membership can be updated by making a `PUT` request on the URL for that goal. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Memberships on `goals` and `projects` can be updated. Returns the full record of the updated membership. + * @param {<&vendorExtensions.x-jsdoc-type>} body The membership to update. + * @param {<&vendorExtensions.x-jsdoc-type>} membership_gid Globally unique identifier for the membership. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/MembershipResponseData} + */ + }, { + key: "updateMembership", + value: function updateMembership(body, membership_gid) { + return this.updateMembershipWithHttpInfo(body, membership_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/OrganizationExportsApi.js b/node_modules/asana/dist/api/OrganizationExportsApi.js new file mode 100644 index 000000000..67eeda03a --- /dev/null +++ b/node_modules/asana/dist/api/OrganizationExportsApi.js @@ -0,0 +1,142 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.OrganizationExportsApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* OrganizationExports service. +* @module api/OrganizationExportsApi +* @version 3.0.3 +*/ +var OrganizationExportsApi = exports.OrganizationExportsApi = /*#__PURE__*/function () { + /** + * Constructs a new OrganizationExportsApi. + * @alias module:api/OrganizationExportsApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function OrganizationExportsApi(apiClient) { + _classCallCheck(this, OrganizationExportsApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Create an organization export request + * This method creates a request to export an Organization. Asana will complete the export at some point after you create the request. + * @param {module:model/Object} body The organization to export. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(OrganizationExportsApi, [{ + key: "createOrganizationExportWithHttpInfo", + value: function createOrganizationExportWithHttpInfo(body, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling createOrganizationExport"); + } + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/organization_exports', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create an organization export request + * This method creates a request to export an Organization. Asana will complete the export at some point after you create the request. + * @param {<&vendorExtensions.x-jsdoc-type>} body The organization to export. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/OrganizationExportResponseData} + */ + }, { + key: "createOrganizationExport", + value: function createOrganizationExport(body, opts) { + return this.createOrganizationExportWithHttpInfo(body, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get details on an org export request + * Returns details of a previously-requested Organization export. + * @param {String} organization_export_gid Globally unique identifier for the organization export. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getOrganizationExportWithHttpInfo", + value: function getOrganizationExportWithHttpInfo(organization_export_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'organization_export_gid' is set + if (organization_export_gid === undefined || organization_export_gid === null) { + throw new Error("Missing the required parameter 'organization_export_gid' when calling getOrganizationExport"); + } + var pathParams = { + 'organization_export_gid': organization_export_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/organization_exports/{organization_export_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get details on an org export request + * Returns details of a previously-requested Organization export. + * @param {<&vendorExtensions.x-jsdoc-type>} organization_export_gid Globally unique identifier for the organization export. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/OrganizationExportResponseData} + */ + }, { + key: "getOrganizationExport", + value: function getOrganizationExport(organization_export_gid, opts) { + return this.getOrganizationExportWithHttpInfo(organization_export_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/PortfolioMembershipsApi.js b/node_modules/asana/dist/api/PortfolioMembershipsApi.js new file mode 100644 index 000000000..32dbe7de5 --- /dev/null +++ b/node_modules/asana/dist/api/PortfolioMembershipsApi.js @@ -0,0 +1,240 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.PortfolioMembershipsApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* PortfolioMemberships service. +* @module api/PortfolioMembershipsApi +* @version 3.0.3 +*/ +var PortfolioMembershipsApi = exports.PortfolioMembershipsApi = /*#__PURE__*/function () { + /** + * Constructs a new PortfolioMembershipsApi. + * @alias module:api/PortfolioMembershipsApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function PortfolioMembershipsApi(apiClient) { + _classCallCheck(this, PortfolioMembershipsApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Get a portfolio membership + * Returns the complete portfolio record for a single portfolio membership. + * @param {String} portfolio_membership_gid + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(PortfolioMembershipsApi, [{ + key: "getPortfolioMembershipWithHttpInfo", + value: function getPortfolioMembershipWithHttpInfo(portfolio_membership_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'portfolio_membership_gid' is set + if (portfolio_membership_gid === undefined || portfolio_membership_gid === null) { + throw new Error("Missing the required parameter 'portfolio_membership_gid' when calling getPortfolioMembership"); + } + var pathParams = { + 'portfolio_membership_gid': portfolio_membership_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/portfolio_memberships/{portfolio_membership_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a portfolio membership + * Returns the complete portfolio record for a single portfolio membership. + * @param {<&vendorExtensions.x-jsdoc-type>} portfolio_membership_gid + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/PortfolioMembershipResponseData} + */ + }, { + key: "getPortfolioMembership", + value: function getPortfolioMembership(portfolio_membership_gid, opts) { + return this.getPortfolioMembershipWithHttpInfo(portfolio_membership_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get multiple portfolio memberships + * Returns a list of portfolio memberships in compact representation. You must specify `portfolio`, `portfolio` and `user`, or `workspace` and `user`. + * @param {Object} opts Optional parameters + * @param {String} opts.portfolio The portfolio to filter results on. + * @param {String} opts.workspace The workspace to filter results on. + * @param {String} opts.user A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getPortfolioMembershipsWithHttpInfo", + value: function getPortfolioMembershipsWithHttpInfo(opts) { + opts = opts || {}; + var postBody = null; + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/portfolio_memberships', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/portfolio_memberships', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/portfolio_memberships', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get multiple portfolio memberships + * Returns a list of portfolio memberships in compact representation. You must specify `portfolio`, `portfolio` and `user`, or `workspace` and `user`. + * @param {Object} opts Optional parameters + * @param {String} opts.portfolio The portfolio to filter results on. + * @param {String} opts.workspace The workspace to filter results on. + * @param {String} opts.user A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/PortfolioMembershipResponseArray} + */ + }, { + key: "getPortfolioMemberships", + value: function getPortfolioMemberships(opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getPortfolioMembershipsWithHttpInfo(opts); + } + return this.getPortfolioMembershipsWithHttpInfo(opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get memberships from a portfolio + * Returns the compact portfolio membership records for the portfolio. + * @param {String} portfolio_gid Globally unique identifier for the portfolio. + * @param {Object} opts Optional parameters + * @param {String} opts.user A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getPortfolioMembershipsForPortfolioWithHttpInfo", + value: function getPortfolioMembershipsForPortfolioWithHttpInfo(portfolio_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'portfolio_gid' is set + if (portfolio_gid === undefined || portfolio_gid === null) { + throw new Error("Missing the required parameter 'portfolio_gid' when calling getPortfolioMembershipsForPortfolio"); + } + var pathParams = { + 'portfolio_gid': portfolio_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/portfolios/{portfolio_gid}/portfolio_memberships', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/portfolios/{portfolio_gid}/portfolio_memberships', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/portfolios/{portfolio_gid}/portfolio_memberships', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get memberships from a portfolio + * Returns the compact portfolio membership records for the portfolio. + * @param {<&vendorExtensions.x-jsdoc-type>} portfolio_gid Globally unique identifier for the portfolio. + * @param {Object} opts Optional parameters + * @param {String} opts.user A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/PortfolioMembershipResponseArray} + */ + }, { + key: "getPortfolioMembershipsForPortfolio", + value: function getPortfolioMembershipsForPortfolio(portfolio_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getPortfolioMembershipsForPortfolioWithHttpInfo(portfolio_gid, opts); + } + return this.getPortfolioMembershipsForPortfolioWithHttpInfo(portfolio_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/PortfoliosApi.js b/node_modules/asana/dist/api/PortfoliosApi.js new file mode 100644 index 000000000..4bff60fea --- /dev/null +++ b/node_modules/asana/dist/api/PortfoliosApi.js @@ -0,0 +1,678 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.PortfoliosApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* Portfolios service. +* @module api/PortfoliosApi +* @version 3.0.3 +*/ +var PortfoliosApi = exports.PortfoliosApi = /*#__PURE__*/function () { + /** + * Constructs a new PortfoliosApi. + * @alias module:api/PortfoliosApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function PortfoliosApi(apiClient) { + _classCallCheck(this, PortfoliosApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Add a custom field to a portfolio + * Custom fields are associated with portfolios by way of custom field settings. This method creates a setting for the portfolio. + * @param {module:model/Object} body Information about the custom field setting. + * @param {String} portfolio_gid Globally unique identifier for the portfolio. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(PortfoliosApi, [{ + key: "addCustomFieldSettingForPortfolioWithHttpInfo", + value: function addCustomFieldSettingForPortfolioWithHttpInfo(body, portfolio_gid) { + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling addCustomFieldSettingForPortfolio"); + } + // verify the required parameter 'portfolio_gid' is set + if (portfolio_gid === undefined || portfolio_gid === null) { + throw new Error("Missing the required parameter 'portfolio_gid' when calling addCustomFieldSettingForPortfolio"); + } + var pathParams = { + 'portfolio_gid': portfolio_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/portfolios/{portfolio_gid}/addCustomFieldSetting', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Add a custom field to a portfolio + * Custom fields are associated with portfolios by way of custom field settings. This method creates a setting for the portfolio. + * @param {<&vendorExtensions.x-jsdoc-type>} body Information about the custom field setting. + * @param {<&vendorExtensions.x-jsdoc-type>} portfolio_gid Globally unique identifier for the portfolio. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/CustomFieldSettingResponseData} + */ + }, { + key: "addCustomFieldSettingForPortfolio", + value: function addCustomFieldSettingForPortfolio(body, portfolio_gid) { + return this.addCustomFieldSettingForPortfolioWithHttpInfo(body, portfolio_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Add a portfolio item + * Add an item to a portfolio. Returns an empty data block. + * @param {module:model/Object} body Information about the item being inserted. + * @param {String} portfolio_gid Globally unique identifier for the portfolio. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "addItemForPortfolioWithHttpInfo", + value: function addItemForPortfolioWithHttpInfo(body, portfolio_gid) { + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling addItemForPortfolio"); + } + // verify the required parameter 'portfolio_gid' is set + if (portfolio_gid === undefined || portfolio_gid === null) { + throw new Error("Missing the required parameter 'portfolio_gid' when calling addItemForPortfolio"); + } + var pathParams = { + 'portfolio_gid': portfolio_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/portfolios/{portfolio_gid}/addItem', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Add a portfolio item + * Add an item to a portfolio. Returns an empty data block. + * @param {<&vendorExtensions.x-jsdoc-type>} body Information about the item being inserted. + * @param {<&vendorExtensions.x-jsdoc-type>} portfolio_gid Globally unique identifier for the portfolio. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "addItemForPortfolio", + value: function addItemForPortfolio(body, portfolio_gid) { + return this.addItemForPortfolioWithHttpInfo(body, portfolio_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Add users to a portfolio + * Adds the specified list of users as members of the portfolio. Returns the updated portfolio record. + * @param {module:model/Object} body Information about the members being added. + * @param {String} portfolio_gid Globally unique identifier for the portfolio. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "addMembersForPortfolioWithHttpInfo", + value: function addMembersForPortfolioWithHttpInfo(body, portfolio_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling addMembersForPortfolio"); + } + // verify the required parameter 'portfolio_gid' is set + if (portfolio_gid === undefined || portfolio_gid === null) { + throw new Error("Missing the required parameter 'portfolio_gid' when calling addMembersForPortfolio"); + } + var pathParams = { + 'portfolio_gid': portfolio_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/portfolios/{portfolio_gid}/addMembers', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Add users to a portfolio + * Adds the specified list of users as members of the portfolio. Returns the updated portfolio record. + * @param {<&vendorExtensions.x-jsdoc-type>} body Information about the members being added. + * @param {<&vendorExtensions.x-jsdoc-type>} portfolio_gid Globally unique identifier for the portfolio. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/PortfolioResponseData} + */ + }, { + key: "addMembersForPortfolio", + value: function addMembersForPortfolio(body, portfolio_gid, opts) { + return this.addMembersForPortfolioWithHttpInfo(body, portfolio_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Create a portfolio + * Creates a new portfolio in the given workspace with the supplied name. Note that portfolios created in the Asana UI may have some state (like the “Priority” custom field) which is automatically added to the portfolio when it is created. Portfolios created via our API will *not* be created with the same initial state to allow integrations to create their own starting state on a portfolio. + * @param {module:model/Object} body The portfolio to create. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "createPortfolioWithHttpInfo", + value: function createPortfolioWithHttpInfo(body, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling createPortfolio"); + } + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/portfolios', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create a portfolio + * Creates a new portfolio in the given workspace with the supplied name. Note that portfolios created in the Asana UI may have some state (like the “Priority” custom field) which is automatically added to the portfolio when it is created. Portfolios created via our API will *not* be created with the same initial state to allow integrations to create their own starting state on a portfolio. + * @param {<&vendorExtensions.x-jsdoc-type>} body The portfolio to create. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/PortfolioResponseData} + */ + }, { + key: "createPortfolio", + value: function createPortfolio(body, opts) { + return this.createPortfolioWithHttpInfo(body, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Delete a portfolio + * An existing portfolio can be deleted by making a DELETE request on the URL for that portfolio. Returns an empty data record. + * @param {String} portfolio_gid Globally unique identifier for the portfolio. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "deletePortfolioWithHttpInfo", + value: function deletePortfolioWithHttpInfo(portfolio_gid) { + var postBody = null; + // verify the required parameter 'portfolio_gid' is set + if (portfolio_gid === undefined || portfolio_gid === null) { + throw new Error("Missing the required parameter 'portfolio_gid' when calling deletePortfolio"); + } + var pathParams = { + 'portfolio_gid': portfolio_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/portfolios/{portfolio_gid}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Delete a portfolio + * An existing portfolio can be deleted by making a DELETE request on the URL for that portfolio. Returns an empty data record. + * @param {<&vendorExtensions.x-jsdoc-type>} portfolio_gid Globally unique identifier for the portfolio. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "deletePortfolio", + value: function deletePortfolio(portfolio_gid) { + return this.deletePortfolioWithHttpInfo(portfolio_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get portfolio items + * Get a list of the items in compact form in a portfolio. + * @param {String} portfolio_gid Globally unique identifier for the portfolio. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getItemsForPortfolioWithHttpInfo", + value: function getItemsForPortfolioWithHttpInfo(portfolio_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'portfolio_gid' is set + if (portfolio_gid === undefined || portfolio_gid === null) { + throw new Error("Missing the required parameter 'portfolio_gid' when calling getItemsForPortfolio"); + } + var pathParams = { + 'portfolio_gid': portfolio_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/portfolios/{portfolio_gid}/items', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/portfolios/{portfolio_gid}/items', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/portfolios/{portfolio_gid}/items', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get portfolio items + * Get a list of the items in compact form in a portfolio. + * @param {<&vendorExtensions.x-jsdoc-type>} portfolio_gid Globally unique identifier for the portfolio. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectResponseArray} + */ + }, { + key: "getItemsForPortfolio", + value: function getItemsForPortfolio(portfolio_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getItemsForPortfolioWithHttpInfo(portfolio_gid, opts); + } + return this.getItemsForPortfolioWithHttpInfo(portfolio_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a portfolio + * Returns the complete portfolio record for a single portfolio. + * @param {String} portfolio_gid Globally unique identifier for the portfolio. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getPortfolioWithHttpInfo", + value: function getPortfolioWithHttpInfo(portfolio_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'portfolio_gid' is set + if (portfolio_gid === undefined || portfolio_gid === null) { + throw new Error("Missing the required parameter 'portfolio_gid' when calling getPortfolio"); + } + var pathParams = { + 'portfolio_gid': portfolio_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/portfolios/{portfolio_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a portfolio + * Returns the complete portfolio record for a single portfolio. + * @param {<&vendorExtensions.x-jsdoc-type>} portfolio_gid Globally unique identifier for the portfolio. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/PortfolioResponseData} + */ + }, { + key: "getPortfolio", + value: function getPortfolio(portfolio_gid, opts) { + return this.getPortfolioWithHttpInfo(portfolio_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get multiple portfolios + * Returns a list of the portfolios in compact representation that are owned by the current API user. + * @param {String} workspace The workspace or organization to filter portfolios on. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {String} opts.owner The user who owns the portfolio. Currently, API users can only get a list of portfolios that they themselves own, unless the request is made from a Service Account. In the case of a Service Account, if this parameter is specified, then all portfolios owned by this parameter are returned. Otherwise, all portfolios across the workspace are returned. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getPortfoliosWithHttpInfo", + value: function getPortfoliosWithHttpInfo(workspace, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'workspace' is set + if (workspace === undefined || workspace === null) { + throw new Error("Missing the required parameter 'workspace' when calling getPortfolios"); + } + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + queryParams['workspace'] = workspace; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/portfolios', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/portfolios', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/portfolios', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get multiple portfolios + * Returns a list of the portfolios in compact representation that are owned by the current API user. + * @param {<&vendorExtensions.x-jsdoc-type>} workspace The workspace or organization to filter portfolios on. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {String} opts.owner The user who owns the portfolio. Currently, API users can only get a list of portfolios that they themselves own, unless the request is made from a Service Account. In the case of a Service Account, if this parameter is specified, then all portfolios owned by this parameter are returned. Otherwise, all portfolios across the workspace are returned. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/PortfolioResponseArray} + */ + }, { + key: "getPortfolios", + value: function getPortfolios(workspace, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getPortfoliosWithHttpInfo(workspace, opts); + } + return this.getPortfoliosWithHttpInfo(workspace, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Remove a custom field from a portfolio + * Removes a custom field setting from a portfolio. + * @param {module:model/Object} body Information about the custom field setting being removed. + * @param {String} portfolio_gid Globally unique identifier for the portfolio. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "removeCustomFieldSettingForPortfolioWithHttpInfo", + value: function removeCustomFieldSettingForPortfolioWithHttpInfo(body, portfolio_gid) { + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling removeCustomFieldSettingForPortfolio"); + } + // verify the required parameter 'portfolio_gid' is set + if (portfolio_gid === undefined || portfolio_gid === null) { + throw new Error("Missing the required parameter 'portfolio_gid' when calling removeCustomFieldSettingForPortfolio"); + } + var pathParams = { + 'portfolio_gid': portfolio_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/portfolios/{portfolio_gid}/removeCustomFieldSetting', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Remove a custom field from a portfolio + * Removes a custom field setting from a portfolio. + * @param {<&vendorExtensions.x-jsdoc-type>} body Information about the custom field setting being removed. + * @param {<&vendorExtensions.x-jsdoc-type>} portfolio_gid Globally unique identifier for the portfolio. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "removeCustomFieldSettingForPortfolio", + value: function removeCustomFieldSettingForPortfolio(body, portfolio_gid) { + return this.removeCustomFieldSettingForPortfolioWithHttpInfo(body, portfolio_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Remove a portfolio item + * Remove an item from a portfolio. Returns an empty data block. + * @param {module:model/Object} body Information about the item being removed. + * @param {String} portfolio_gid Globally unique identifier for the portfolio. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "removeItemForPortfolioWithHttpInfo", + value: function removeItemForPortfolioWithHttpInfo(body, portfolio_gid) { + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling removeItemForPortfolio"); + } + // verify the required parameter 'portfolio_gid' is set + if (portfolio_gid === undefined || portfolio_gid === null) { + throw new Error("Missing the required parameter 'portfolio_gid' when calling removeItemForPortfolio"); + } + var pathParams = { + 'portfolio_gid': portfolio_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/portfolios/{portfolio_gid}/removeItem', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Remove a portfolio item + * Remove an item from a portfolio. Returns an empty data block. + * @param {<&vendorExtensions.x-jsdoc-type>} body Information about the item being removed. + * @param {<&vendorExtensions.x-jsdoc-type>} portfolio_gid Globally unique identifier for the portfolio. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "removeItemForPortfolio", + value: function removeItemForPortfolio(body, portfolio_gid) { + return this.removeItemForPortfolioWithHttpInfo(body, portfolio_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Remove users from a portfolio + * Removes the specified list of users from members of the portfolio. Returns the updated portfolio record. + * @param {module:model/Object} body Information about the members being removed. + * @param {String} portfolio_gid Globally unique identifier for the portfolio. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "removeMembersForPortfolioWithHttpInfo", + value: function removeMembersForPortfolioWithHttpInfo(body, portfolio_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling removeMembersForPortfolio"); + } + // verify the required parameter 'portfolio_gid' is set + if (portfolio_gid === undefined || portfolio_gid === null) { + throw new Error("Missing the required parameter 'portfolio_gid' when calling removeMembersForPortfolio"); + } + var pathParams = { + 'portfolio_gid': portfolio_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/portfolios/{portfolio_gid}/removeMembers', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Remove users from a portfolio + * Removes the specified list of users from members of the portfolio. Returns the updated portfolio record. + * @param {<&vendorExtensions.x-jsdoc-type>} body Information about the members being removed. + * @param {<&vendorExtensions.x-jsdoc-type>} portfolio_gid Globally unique identifier for the portfolio. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/PortfolioResponseData} + */ + }, { + key: "removeMembersForPortfolio", + value: function removeMembersForPortfolio(body, portfolio_gid, opts) { + return this.removeMembersForPortfolioWithHttpInfo(body, portfolio_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Update a portfolio + * An existing portfolio can be updated by making a PUT request on the URL for that portfolio. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated portfolio record. + * @param {module:model/Object} body The updated fields for the portfolio. + * @param {String} portfolio_gid Globally unique identifier for the portfolio. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "updatePortfolioWithHttpInfo", + value: function updatePortfolioWithHttpInfo(body, portfolio_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling updatePortfolio"); + } + // verify the required parameter 'portfolio_gid' is set + if (portfolio_gid === undefined || portfolio_gid === null) { + throw new Error("Missing the required parameter 'portfolio_gid' when calling updatePortfolio"); + } + var pathParams = { + 'portfolio_gid': portfolio_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/portfolios/{portfolio_gid}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Update a portfolio + * An existing portfolio can be updated by making a PUT request on the URL for that portfolio. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated portfolio record. + * @param {<&vendorExtensions.x-jsdoc-type>} body The updated fields for the portfolio. + * @param {<&vendorExtensions.x-jsdoc-type>} portfolio_gid Globally unique identifier for the portfolio. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/PortfolioResponseData} + */ + }, { + key: "updatePortfolio", + value: function updatePortfolio(body, portfolio_gid, opts) { + return this.updatePortfolioWithHttpInfo(body, portfolio_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/ProjectBriefsApi.js b/node_modules/asana/dist/api/ProjectBriefsApi.js new file mode 100644 index 000000000..c9081c45a --- /dev/null +++ b/node_modules/asana/dist/api/ProjectBriefsApi.js @@ -0,0 +1,245 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ProjectBriefsApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* ProjectBriefs service. +* @module api/ProjectBriefsApi +* @version 3.0.3 +*/ +var ProjectBriefsApi = exports.ProjectBriefsApi = /*#__PURE__*/function () { + /** + * Constructs a new ProjectBriefsApi. + * @alias module:api/ProjectBriefsApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function ProjectBriefsApi(apiClient) { + _classCallCheck(this, ProjectBriefsApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Create a project brief + * Creates a new project brief. Returns the full record of the newly created project brief. + * @param {module:model/Object} body The project brief to create. + * @param {String} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(ProjectBriefsApi, [{ + key: "createProjectBriefWithHttpInfo", + value: function createProjectBriefWithHttpInfo(body, project_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling createProjectBrief"); + } + // verify the required parameter 'project_gid' is set + if (project_gid === undefined || project_gid === null) { + throw new Error("Missing the required parameter 'project_gid' when calling createProjectBrief"); + } + var pathParams = { + 'project_gid': project_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/projects/{project_gid}/project_briefs', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create a project brief + * Creates a new project brief. Returns the full record of the newly created project brief. + * @param {<&vendorExtensions.x-jsdoc-type>} body The project brief to create. + * @param {<&vendorExtensions.x-jsdoc-type>} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectBriefResponseData} + */ + }, { + key: "createProjectBrief", + value: function createProjectBrief(body, project_gid, opts) { + return this.createProjectBriefWithHttpInfo(body, project_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Delete a project brief + * Deletes a specific, existing project brief. Returns an empty data record. + * @param {String} project_brief_gid Globally unique identifier for the project brief. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "deleteProjectBriefWithHttpInfo", + value: function deleteProjectBriefWithHttpInfo(project_brief_gid) { + var postBody = null; + // verify the required parameter 'project_brief_gid' is set + if (project_brief_gid === undefined || project_brief_gid === null) { + throw new Error("Missing the required parameter 'project_brief_gid' when calling deleteProjectBrief"); + } + var pathParams = { + 'project_brief_gid': project_brief_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/project_briefs/{project_brief_gid}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Delete a project brief + * Deletes a specific, existing project brief. Returns an empty data record. + * @param {<&vendorExtensions.x-jsdoc-type>} project_brief_gid Globally unique identifier for the project brief. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "deleteProjectBrief", + value: function deleteProjectBrief(project_brief_gid) { + return this.deleteProjectBriefWithHttpInfo(project_brief_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a project brief + * Get the full record for a project brief. + * @param {String} project_brief_gid Globally unique identifier for the project brief. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getProjectBriefWithHttpInfo", + value: function getProjectBriefWithHttpInfo(project_brief_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'project_brief_gid' is set + if (project_brief_gid === undefined || project_brief_gid === null) { + throw new Error("Missing the required parameter 'project_brief_gid' when calling getProjectBrief"); + } + var pathParams = { + 'project_brief_gid': project_brief_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/project_briefs/{project_brief_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a project brief + * Get the full record for a project brief. + * @param {<&vendorExtensions.x-jsdoc-type>} project_brief_gid Globally unique identifier for the project brief. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectBriefResponseData} + */ + }, { + key: "getProjectBrief", + value: function getProjectBrief(project_brief_gid, opts) { + return this.getProjectBriefWithHttpInfo(project_brief_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Update a project brief + * An existing project brief can be updated by making a PUT request on the URL for that project brief. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated project brief record. + * @param {module:model/Object} body The updated fields for the project brief. + * @param {String} project_brief_gid Globally unique identifier for the project brief. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "updateProjectBriefWithHttpInfo", + value: function updateProjectBriefWithHttpInfo(body, project_brief_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling updateProjectBrief"); + } + // verify the required parameter 'project_brief_gid' is set + if (project_brief_gid === undefined || project_brief_gid === null) { + throw new Error("Missing the required parameter 'project_brief_gid' when calling updateProjectBrief"); + } + var pathParams = { + 'project_brief_gid': project_brief_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/project_briefs/{project_brief_gid}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Update a project brief + * An existing project brief can be updated by making a PUT request on the URL for that project brief. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated project brief record. + * @param {<&vendorExtensions.x-jsdoc-type>} body The updated fields for the project brief. + * @param {<&vendorExtensions.x-jsdoc-type>} project_brief_gid Globally unique identifier for the project brief. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectBriefResponseData} + */ + }, { + key: "updateProjectBrief", + value: function updateProjectBrief(body, project_brief_gid, opts) { + return this.updateProjectBriefWithHttpInfo(body, project_brief_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/ProjectMembershipsApi.js b/node_modules/asana/dist/api/ProjectMembershipsApi.js new file mode 100644 index 000000000..c23d35f55 --- /dev/null +++ b/node_modules/asana/dist/api/ProjectMembershipsApi.js @@ -0,0 +1,170 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ProjectMembershipsApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* ProjectMemberships service. +* @module api/ProjectMembershipsApi +* @version 3.0.3 +*/ +var ProjectMembershipsApi = exports.ProjectMembershipsApi = /*#__PURE__*/function () { + /** + * Constructs a new ProjectMembershipsApi. + * @alias module:api/ProjectMembershipsApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function ProjectMembershipsApi(apiClient) { + _classCallCheck(this, ProjectMembershipsApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Get a project membership + * Returns the complete project record for a single project membership. + * @param {String} project_membership_gid + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(ProjectMembershipsApi, [{ + key: "getProjectMembershipWithHttpInfo", + value: function getProjectMembershipWithHttpInfo(project_membership_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'project_membership_gid' is set + if (project_membership_gid === undefined || project_membership_gid === null) { + throw new Error("Missing the required parameter 'project_membership_gid' when calling getProjectMembership"); + } + var pathParams = { + 'project_membership_gid': project_membership_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/project_memberships/{project_membership_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a project membership + * Returns the complete project record for a single project membership. + * @param {<&vendorExtensions.x-jsdoc-type>} project_membership_gid + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectMembershipNormalResponseData} + */ + }, { + key: "getProjectMembership", + value: function getProjectMembership(project_membership_gid, opts) { + return this.getProjectMembershipWithHttpInfo(project_membership_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get memberships from a project + * Returns the compact project membership records for the project. + * @param {String} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {String} opts.user A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getProjectMembershipsForProjectWithHttpInfo", + value: function getProjectMembershipsForProjectWithHttpInfo(project_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'project_gid' is set + if (project_gid === undefined || project_gid === null) { + throw new Error("Missing the required parameter 'project_gid' when calling getProjectMembershipsForProject"); + } + var pathParams = { + 'project_gid': project_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/projects/{project_gid}/project_memberships', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/projects/{project_gid}/project_memberships', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/projects/{project_gid}/project_memberships', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get memberships from a project + * Returns the compact project membership records for the project. + * @param {<&vendorExtensions.x-jsdoc-type>} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {String} opts.user A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectMembershipCompactArray} + */ + }, { + key: "getProjectMembershipsForProject", + value: function getProjectMembershipsForProject(project_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getProjectMembershipsForProjectWithHttpInfo(project_gid, opts); + } + return this.getProjectMembershipsForProjectWithHttpInfo(project_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/ProjectStatusesApi.js b/node_modules/asana/dist/api/ProjectStatusesApi.js new file mode 100644 index 000000000..206950734 --- /dev/null +++ b/node_modules/asana/dist/api/ProjectStatusesApi.js @@ -0,0 +1,263 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ProjectStatusesApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* ProjectStatuses service. +* @module api/ProjectStatusesApi +* @version 3.0.3 +*/ +var ProjectStatusesApi = exports.ProjectStatusesApi = /*#__PURE__*/function () { + /** + * Constructs a new ProjectStatusesApi. + * @alias module:api/ProjectStatusesApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function ProjectStatusesApi(apiClient) { + _classCallCheck(this, ProjectStatusesApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Create a project status + * *Deprecated: new integrations should prefer the `/status_updates` route.* Creates a new status update on the project. Returns the full record of the newly created project status update. + * @param {module:model/Object} body The project status to create. + * @param {String} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(ProjectStatusesApi, [{ + key: "createProjectStatusForProjectWithHttpInfo", + value: function createProjectStatusForProjectWithHttpInfo(body, project_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling createProjectStatusForProject"); + } + // verify the required parameter 'project_gid' is set + if (project_gid === undefined || project_gid === null) { + throw new Error("Missing the required parameter 'project_gid' when calling createProjectStatusForProject"); + } + var pathParams = { + 'project_gid': project_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/projects/{project_gid}/project_statuses', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create a project status + * *Deprecated: new integrations should prefer the `/status_updates` route.* Creates a new status update on the project. Returns the full record of the newly created project status update. + * @param {<&vendorExtensions.x-jsdoc-type>} body The project status to create. + * @param {<&vendorExtensions.x-jsdoc-type>} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectStatusResponseData} + */ + }, { + key: "createProjectStatusForProject", + value: function createProjectStatusForProject(body, project_gid, opts) { + return this.createProjectStatusForProjectWithHttpInfo(body, project_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Delete a project status + * *Deprecated: new integrations should prefer the `/status_updates/{status_gid}` route.* Deletes a specific, existing project status update. Returns an empty data record. + * @param {String} project_status_gid The project status update to get. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "deleteProjectStatusWithHttpInfo", + value: function deleteProjectStatusWithHttpInfo(project_status_gid) { + var postBody = null; + // verify the required parameter 'project_status_gid' is set + if (project_status_gid === undefined || project_status_gid === null) { + throw new Error("Missing the required parameter 'project_status_gid' when calling deleteProjectStatus"); + } + var pathParams = { + 'project_status_gid': project_status_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/project_statuses/{project_status_gid}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Delete a project status + * *Deprecated: new integrations should prefer the `/status_updates/{status_gid}` route.* Deletes a specific, existing project status update. Returns an empty data record. + * @param {<&vendorExtensions.x-jsdoc-type>} project_status_gid The project status update to get. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "deleteProjectStatus", + value: function deleteProjectStatus(project_status_gid) { + return this.deleteProjectStatusWithHttpInfo(project_status_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a project status + * *Deprecated: new integrations should prefer the `/status_updates/{status_gid}` route.* Returns the complete record for a single status update. + * @param {String} project_status_gid The project status update to get. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getProjectStatusWithHttpInfo", + value: function getProjectStatusWithHttpInfo(project_status_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'project_status_gid' is set + if (project_status_gid === undefined || project_status_gid === null) { + throw new Error("Missing the required parameter 'project_status_gid' when calling getProjectStatus"); + } + var pathParams = { + 'project_status_gid': project_status_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/project_statuses/{project_status_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a project status + * *Deprecated: new integrations should prefer the `/status_updates/{status_gid}` route.* Returns the complete record for a single status update. + * @param {<&vendorExtensions.x-jsdoc-type>} project_status_gid The project status update to get. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectStatusResponseData} + */ + }, { + key: "getProjectStatus", + value: function getProjectStatus(project_status_gid, opts) { + return this.getProjectStatusWithHttpInfo(project_status_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get statuses from a project + * *Deprecated: new integrations should prefer the `/status_updates` route.* Returns the compact project status update records for all updates on the project. + * @param {String} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getProjectStatusesForProjectWithHttpInfo", + value: function getProjectStatusesForProjectWithHttpInfo(project_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'project_gid' is set + if (project_gid === undefined || project_gid === null) { + throw new Error("Missing the required parameter 'project_gid' when calling getProjectStatusesForProject"); + } + var pathParams = { + 'project_gid': project_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/projects/{project_gid}/project_statuses', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/projects/{project_gid}/project_statuses', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/projects/{project_gid}/project_statuses', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get statuses from a project + * *Deprecated: new integrations should prefer the `/status_updates` route.* Returns the compact project status update records for all updates on the project. + * @param {<&vendorExtensions.x-jsdoc-type>} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectStatusResponseArray} + */ + }, { + key: "getProjectStatusesForProject", + value: function getProjectStatusesForProject(project_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getProjectStatusesForProjectWithHttpInfo(project_gid, opts); + } + return this.getProjectStatusesForProjectWithHttpInfo(project_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/ProjectTemplatesApi.js b/node_modules/asana/dist/api/ProjectTemplatesApi.js new file mode 100644 index 000000000..7b2d62f8f --- /dev/null +++ b/node_modules/asana/dist/api/ProjectTemplatesApi.js @@ -0,0 +1,327 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ProjectTemplatesApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* ProjectTemplates service. +* @module api/ProjectTemplatesApi +* @version 3.0.3 +*/ +var ProjectTemplatesApi = exports.ProjectTemplatesApi = /*#__PURE__*/function () { + /** + * Constructs a new ProjectTemplatesApi. + * @alias module:api/ProjectTemplatesApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function ProjectTemplatesApi(apiClient) { + _classCallCheck(this, ProjectTemplatesApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Delete a project template + * A specific, existing project template can be deleted by making a DELETE request on the URL for that project template. Returns an empty data record. + * @param {String} project_template_gid Globally unique identifier for the project template. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(ProjectTemplatesApi, [{ + key: "deleteProjectTemplateWithHttpInfo", + value: function deleteProjectTemplateWithHttpInfo(project_template_gid) { + var postBody = null; + // verify the required parameter 'project_template_gid' is set + if (project_template_gid === undefined || project_template_gid === null) { + throw new Error("Missing the required parameter 'project_template_gid' when calling deleteProjectTemplate"); + } + var pathParams = { + 'project_template_gid': project_template_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/project_templates/{project_template_gid}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Delete a project template + * A specific, existing project template can be deleted by making a DELETE request on the URL for that project template. Returns an empty data record. + * @param {<&vendorExtensions.x-jsdoc-type>} project_template_gid Globally unique identifier for the project template. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "deleteProjectTemplate", + value: function deleteProjectTemplate(project_template_gid) { + return this.deleteProjectTemplateWithHttpInfo(project_template_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a project template + * Returns the complete project template record for a single project template. + * @param {String} project_template_gid Globally unique identifier for the project template. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getProjectTemplateWithHttpInfo", + value: function getProjectTemplateWithHttpInfo(project_template_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'project_template_gid' is set + if (project_template_gid === undefined || project_template_gid === null) { + throw new Error("Missing the required parameter 'project_template_gid' when calling getProjectTemplate"); + } + var pathParams = { + 'project_template_gid': project_template_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/project_templates/{project_template_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a project template + * Returns the complete project template record for a single project template. + * @param {<&vendorExtensions.x-jsdoc-type>} project_template_gid Globally unique identifier for the project template. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectTemplateResponseData} + */ + }, { + key: "getProjectTemplate", + value: function getProjectTemplate(project_template_gid, opts) { + return this.getProjectTemplateWithHttpInfo(project_template_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get multiple project templates + * Returns the compact project template records for all project templates in the given team or workspace. + * @param {Object} opts Optional parameters + * @param {String} opts.workspace The workspace to filter results on. + * @param {String} opts.team The team to filter projects on. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getProjectTemplatesWithHttpInfo", + value: function getProjectTemplatesWithHttpInfo(opts) { + opts = opts || {}; + var postBody = null; + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/project_templates', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/project_templates', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/project_templates', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get multiple project templates + * Returns the compact project template records for all project templates in the given team or workspace. + * @param {Object} opts Optional parameters + * @param {String} opts.workspace The workspace to filter results on. + * @param {String} opts.team The team to filter projects on. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectTemplateResponseArray} + */ + }, { + key: "getProjectTemplates", + value: function getProjectTemplates(opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getProjectTemplatesWithHttpInfo(opts); + } + return this.getProjectTemplatesWithHttpInfo(opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a team's project templates + * Returns the compact project template records for all project templates in the team. + * @param {String} team_gid Globally unique identifier for the team. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getProjectTemplatesForTeamWithHttpInfo", + value: function getProjectTemplatesForTeamWithHttpInfo(team_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'team_gid' is set + if (team_gid === undefined || team_gid === null) { + throw new Error("Missing the required parameter 'team_gid' when calling getProjectTemplatesForTeam"); + } + var pathParams = { + 'team_gid': team_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/teams/{team_gid}/project_templates', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/teams/{team_gid}/project_templates', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/teams/{team_gid}/project_templates', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a team's project templates + * Returns the compact project template records for all project templates in the team. + * @param {<&vendorExtensions.x-jsdoc-type>} team_gid Globally unique identifier for the team. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectTemplateResponseArray} + */ + }, { + key: "getProjectTemplatesForTeam", + value: function getProjectTemplatesForTeam(team_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getProjectTemplatesForTeamWithHttpInfo(team_gid, opts); + } + return this.getProjectTemplatesForTeamWithHttpInfo(team_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Instantiate a project from a project template + * Creates and returns a job that will asynchronously handle the project instantiation. To form this request, it is recommended to first make a request to [get a project template](/reference/getprojecttemplate). Then, from the response, copy the `gid` from the object in the `requested_dates` array. This `gid` should be used in `requested_dates` to instantiate a project. _Note: The body of this request will differ if your workspace is an organization. To determine if your workspace is an organization, use the [is_organization](/reference/workspaces) parameter._ + * @param {String} project_template_gid Globally unique identifier for the project template. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body Describes the inputs used for instantiating a project, such as the resulting project's name, which team it should be created in, and values for date variables. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "instantiateProjectWithHttpInfo", + value: function instantiateProjectWithHttpInfo(project_template_gid, opts) { + opts = opts || {}; + var postBody = opts['body']; + // verify the required parameter 'project_template_gid' is set + if (project_template_gid === undefined || project_template_gid === null) { + throw new Error("Missing the required parameter 'project_template_gid' when calling instantiateProject"); + } + var pathParams = { + 'project_template_gid': project_template_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/project_templates/{project_template_gid}/instantiateProject', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Instantiate a project from a project template + * Creates and returns a job that will asynchronously handle the project instantiation. To form this request, it is recommended to first make a request to [get a project template](/reference/getprojecttemplate). Then, from the response, copy the `gid` from the object in the `requested_dates` array. This `gid` should be used in `requested_dates` to instantiate a project. _Note: The body of this request will differ if your workspace is an organization. To determine if your workspace is an organization, use the [is_organization](/reference/workspaces) parameter._ + * @param {<&vendorExtensions.x-jsdoc-type>} project_template_gid Globally unique identifier for the project template. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body Describes the inputs used for instantiating a project, such as the resulting project's name, which team it should be created in, and values for date variables. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/JobResponseData} + */ + }, { + key: "instantiateProject", + value: function instantiateProject(project_template_gid, opts) { + return this.instantiateProjectWithHttpInfo(project_template_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/ProjectsApi.js b/node_modules/asana/dist/api/ProjectsApi.js new file mode 100644 index 000000000..105dc5ec3 --- /dev/null +++ b/node_modules/asana/dist/api/ProjectsApi.js @@ -0,0 +1,1104 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ProjectsApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* Projects service. +* @module api/ProjectsApi +* @version 3.0.3 +*/ +var ProjectsApi = exports.ProjectsApi = /*#__PURE__*/function () { + /** + * Constructs a new ProjectsApi. + * @alias module:api/ProjectsApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function ProjectsApi(apiClient) { + _classCallCheck(this, ProjectsApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Add a custom field to a project + * Custom fields are associated with projects by way of custom field settings. This method creates a setting for the project. + * @param {module:model/Object} body Information about the custom field setting. + * @param {String} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(ProjectsApi, [{ + key: "addCustomFieldSettingForProjectWithHttpInfo", + value: function addCustomFieldSettingForProjectWithHttpInfo(body, project_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling addCustomFieldSettingForProject"); + } + // verify the required parameter 'project_gid' is set + if (project_gid === undefined || project_gid === null) { + throw new Error("Missing the required parameter 'project_gid' when calling addCustomFieldSettingForProject"); + } + var pathParams = { + 'project_gid': project_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/projects/{project_gid}/addCustomFieldSetting', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Add a custom field to a project + * Custom fields are associated with projects by way of custom field settings. This method creates a setting for the project. + * @param {<&vendorExtensions.x-jsdoc-type>} body Information about the custom field setting. + * @param {<&vendorExtensions.x-jsdoc-type>} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/CustomFieldSettingResponseData} + */ + }, { + key: "addCustomFieldSettingForProject", + value: function addCustomFieldSettingForProject(body, project_gid, opts) { + return this.addCustomFieldSettingForProjectWithHttpInfo(body, project_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Add followers to a project + * Adds the specified list of users as followers to the project. Followers are a subset of members who have opted in to receive \"tasks added\" notifications for a project. Therefore, if the users are not already members of the project, they will also become members as a result of this operation. Returns the updated project record. + * @param {module:model/Object} body Information about the followers being added. + * @param {String} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "addFollowersForProjectWithHttpInfo", + value: function addFollowersForProjectWithHttpInfo(body, project_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling addFollowersForProject"); + } + // verify the required parameter 'project_gid' is set + if (project_gid === undefined || project_gid === null) { + throw new Error("Missing the required parameter 'project_gid' when calling addFollowersForProject"); + } + var pathParams = { + 'project_gid': project_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/projects/{project_gid}/addFollowers', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Add followers to a project + * Adds the specified list of users as followers to the project. Followers are a subset of members who have opted in to receive \"tasks added\" notifications for a project. Therefore, if the users are not already members of the project, they will also become members as a result of this operation. Returns the updated project record. + * @param {<&vendorExtensions.x-jsdoc-type>} body Information about the followers being added. + * @param {<&vendorExtensions.x-jsdoc-type>} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectResponseData} + */ + }, { + key: "addFollowersForProject", + value: function addFollowersForProject(body, project_gid, opts) { + return this.addFollowersForProjectWithHttpInfo(body, project_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Add users to a project + * Adds the specified list of users as members of the project. Note that a user being added as a member may also be added as a *follower* as a result of this operation. This is because the user's default notification settings (i.e., in the \"Notifcations\" tab of \"My Profile Settings\") will override this endpoint's default behavior of setting \"Tasks added\" notifications to `false`. Returns the updated project record. + * @param {module:model/Object} body Information about the members being added. + * @param {String} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "addMembersForProjectWithHttpInfo", + value: function addMembersForProjectWithHttpInfo(body, project_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling addMembersForProject"); + } + // verify the required parameter 'project_gid' is set + if (project_gid === undefined || project_gid === null) { + throw new Error("Missing the required parameter 'project_gid' when calling addMembersForProject"); + } + var pathParams = { + 'project_gid': project_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/projects/{project_gid}/addMembers', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Add users to a project + * Adds the specified list of users as members of the project. Note that a user being added as a member may also be added as a *follower* as a result of this operation. This is because the user's default notification settings (i.e., in the \"Notifcations\" tab of \"My Profile Settings\") will override this endpoint's default behavior of setting \"Tasks added\" notifications to `false`. Returns the updated project record. + * @param {<&vendorExtensions.x-jsdoc-type>} body Information about the members being added. + * @param {<&vendorExtensions.x-jsdoc-type>} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectResponseData} + */ + }, { + key: "addMembersForProject", + value: function addMembersForProject(body, project_gid, opts) { + return this.addMembersForProjectWithHttpInfo(body, project_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Create a project + * Create a new project in a workspace or team. Every project is required to be created in a specific workspace or organization, and this cannot be changed once set. Note that you can use the `workspace` parameter regardless of whether or not it is an organization. If the workspace for your project is an organization, you must also supply a `team` to share the project with. Returns the full record of the newly created project. + * @param {module:model/Object} body The project to create. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "createProjectWithHttpInfo", + value: function createProjectWithHttpInfo(body, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling createProject"); + } + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/projects', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create a project + * Create a new project in a workspace or team. Every project is required to be created in a specific workspace or organization, and this cannot be changed once set. Note that you can use the `workspace` parameter regardless of whether or not it is an organization. If the workspace for your project is an organization, you must also supply a `team` to share the project with. Returns the full record of the newly created project. + * @param {<&vendorExtensions.x-jsdoc-type>} body The project to create. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectResponseData} + */ + }, { + key: "createProject", + value: function createProject(body, opts) { + return this.createProjectWithHttpInfo(body, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Create a project in a team + * Creates a project shared with the given team. Returns the full record of the newly created project. + * @param {module:model/Object} body The new project to create. + * @param {String} team_gid Globally unique identifier for the team. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "createProjectForTeamWithHttpInfo", + value: function createProjectForTeamWithHttpInfo(body, team_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling createProjectForTeam"); + } + // verify the required parameter 'team_gid' is set + if (team_gid === undefined || team_gid === null) { + throw new Error("Missing the required parameter 'team_gid' when calling createProjectForTeam"); + } + var pathParams = { + 'team_gid': team_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/teams/{team_gid}/projects', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create a project in a team + * Creates a project shared with the given team. Returns the full record of the newly created project. + * @param {<&vendorExtensions.x-jsdoc-type>} body The new project to create. + * @param {<&vendorExtensions.x-jsdoc-type>} team_gid Globally unique identifier for the team. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectResponseData} + */ + }, { + key: "createProjectForTeam", + value: function createProjectForTeam(body, team_gid, opts) { + return this.createProjectForTeamWithHttpInfo(body, team_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Create a project in a workspace + * Creates a project in the workspace. If the workspace for your project is an organization, you must also supply a team to share the project with. Returns the full record of the newly created project. + * @param {module:model/Object} body The new project to create. + * @param {String} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "createProjectForWorkspaceWithHttpInfo", + value: function createProjectForWorkspaceWithHttpInfo(body, workspace_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling createProjectForWorkspace"); + } + // verify the required parameter 'workspace_gid' is set + if (workspace_gid === undefined || workspace_gid === null) { + throw new Error("Missing the required parameter 'workspace_gid' when calling createProjectForWorkspace"); + } + var pathParams = { + 'workspace_gid': workspace_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/workspaces/{workspace_gid}/projects', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create a project in a workspace + * Creates a project in the workspace. If the workspace for your project is an organization, you must also supply a team to share the project with. Returns the full record of the newly created project. + * @param {<&vendorExtensions.x-jsdoc-type>} body The new project to create. + * @param {<&vendorExtensions.x-jsdoc-type>} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectResponseData} + */ + }, { + key: "createProjectForWorkspace", + value: function createProjectForWorkspace(body, workspace_gid, opts) { + return this.createProjectForWorkspaceWithHttpInfo(body, workspace_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Delete a project + * A specific, existing project can be deleted by making a DELETE request on the URL for that project. Returns an empty data record. + * @param {String} project_gid Globally unique identifier for the project. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "deleteProjectWithHttpInfo", + value: function deleteProjectWithHttpInfo(project_gid) { + var postBody = null; + // verify the required parameter 'project_gid' is set + if (project_gid === undefined || project_gid === null) { + throw new Error("Missing the required parameter 'project_gid' when calling deleteProject"); + } + var pathParams = { + 'project_gid': project_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/projects/{project_gid}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Delete a project + * A specific, existing project can be deleted by making a DELETE request on the URL for that project. Returns an empty data record. + * @param {<&vendorExtensions.x-jsdoc-type>} project_gid Globally unique identifier for the project. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "deleteProject", + value: function deleteProject(project_gid) { + return this.deleteProjectWithHttpInfo(project_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Duplicate a project + * Creates and returns a job that will asynchronously handle the duplication. + * @param {String} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body Describes the duplicate's name and the elements that will be duplicated. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "duplicateProjectWithHttpInfo", + value: function duplicateProjectWithHttpInfo(project_gid, opts) { + opts = opts || {}; + var postBody = opts['body']; + // verify the required parameter 'project_gid' is set + if (project_gid === undefined || project_gid === null) { + throw new Error("Missing the required parameter 'project_gid' when calling duplicateProject"); + } + var pathParams = { + 'project_gid': project_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/projects/{project_gid}/duplicate', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Duplicate a project + * Creates and returns a job that will asynchronously handle the duplication. + * @param {<&vendorExtensions.x-jsdoc-type>} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body Describes the duplicate's name and the elements that will be duplicated. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/JobResponseData} + */ + }, { + key: "duplicateProject", + value: function duplicateProject(project_gid, opts) { + return this.duplicateProjectWithHttpInfo(project_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a project + * Returns the complete project record for a single project. + * @param {String} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getProjectWithHttpInfo", + value: function getProjectWithHttpInfo(project_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'project_gid' is set + if (project_gid === undefined || project_gid === null) { + throw new Error("Missing the required parameter 'project_gid' when calling getProject"); + } + var pathParams = { + 'project_gid': project_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/projects/{project_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a project + * Returns the complete project record for a single project. + * @param {<&vendorExtensions.x-jsdoc-type>} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectResponseData} + */ + }, { + key: "getProject", + value: function getProject(project_gid, opts) { + return this.getProjectWithHttpInfo(project_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get multiple projects + * Returns the compact project records for some filtered set of projects. Use one or more of the parameters provided to filter the projects returned. *Note: This endpoint may timeout for large domains. Try filtering by team!* + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {String} opts.workspace The workspace or organization to filter projects on. + * @param {String} opts.team The team to filter projects on. + * @param {Boolean} opts.archived Only return projects whose `archived` field takes on the value of this parameter. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getProjectsWithHttpInfo", + value: function getProjectsWithHttpInfo(opts) { + opts = opts || {}; + var postBody = null; + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/projects', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/projects', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/projects', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get multiple projects + * Returns the compact project records for some filtered set of projects. Use one or more of the parameters provided to filter the projects returned. *Note: This endpoint may timeout for large domains. Try filtering by team!* + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {String} opts.workspace The workspace or organization to filter projects on. + * @param {String} opts.team The team to filter projects on. + * @param {Boolean} opts.archived Only return projects whose `archived` field takes on the value of this parameter. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectResponseArray} + */ + }, { + key: "getProjects", + value: function getProjects(opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getProjectsWithHttpInfo(opts); + } + return this.getProjectsWithHttpInfo(opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get projects a task is in + * Returns a compact representation of all of the projects the task is in. + * @param {String} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getProjectsForTaskWithHttpInfo", + value: function getProjectsForTaskWithHttpInfo(task_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling getProjectsForTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/tasks/{task_gid}/projects', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/tasks/{task_gid}/projects', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/tasks/{task_gid}/projects', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get projects a task is in + * Returns a compact representation of all of the projects the task is in. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectResponseArray} + */ + }, { + key: "getProjectsForTask", + value: function getProjectsForTask(task_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getProjectsForTaskWithHttpInfo(task_gid, opts); + } + return this.getProjectsForTaskWithHttpInfo(task_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a team's projects + * Returns the compact project records for all projects in the team. + * @param {String} team_gid Globally unique identifier for the team. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Boolean} opts.archived Only return projects whose `archived` field takes on the value of this parameter. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getProjectsForTeamWithHttpInfo", + value: function getProjectsForTeamWithHttpInfo(team_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'team_gid' is set + if (team_gid === undefined || team_gid === null) { + throw new Error("Missing the required parameter 'team_gid' when calling getProjectsForTeam"); + } + var pathParams = { + 'team_gid': team_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/teams/{team_gid}/projects', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/teams/{team_gid}/projects', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/teams/{team_gid}/projects', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a team's projects + * Returns the compact project records for all projects in the team. + * @param {<&vendorExtensions.x-jsdoc-type>} team_gid Globally unique identifier for the team. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Boolean} opts.archived Only return projects whose `archived` field takes on the value of this parameter. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectResponseArray} + */ + }, { + key: "getProjectsForTeam", + value: function getProjectsForTeam(team_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getProjectsForTeamWithHttpInfo(team_gid, opts); + } + return this.getProjectsForTeamWithHttpInfo(team_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get all projects in a workspace + * Returns the compact project records for all projects in the workspace. *Note: This endpoint may timeout for large domains. Prefer the `/teams/{team_gid}/projects` endpoint.* + * @param {String} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Boolean} opts.archived Only return projects whose `archived` field takes on the value of this parameter. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getProjectsForWorkspaceWithHttpInfo", + value: function getProjectsForWorkspaceWithHttpInfo(workspace_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'workspace_gid' is set + if (workspace_gid === undefined || workspace_gid === null) { + throw new Error("Missing the required parameter 'workspace_gid' when calling getProjectsForWorkspace"); + } + var pathParams = { + 'workspace_gid': workspace_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/workspaces/{workspace_gid}/projects', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/workspaces/{workspace_gid}/projects', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/workspaces/{workspace_gid}/projects', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get all projects in a workspace + * Returns the compact project records for all projects in the workspace. *Note: This endpoint may timeout for large domains. Prefer the `/teams/{team_gid}/projects` endpoint.* + * @param {<&vendorExtensions.x-jsdoc-type>} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Boolean} opts.archived Only return projects whose `archived` field takes on the value of this parameter. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectResponseArray} + */ + }, { + key: "getProjectsForWorkspace", + value: function getProjectsForWorkspace(workspace_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getProjectsForWorkspaceWithHttpInfo(workspace_gid, opts); + } + return this.getProjectsForWorkspaceWithHttpInfo(workspace_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get task count of a project + * Get an object that holds task count fields. **All fields are excluded by default**. You must [opt in](/docs/inputoutput-options) using `opt_fields` to get any information from this endpoint. This endpoint has an additional [rate limit](/docs/rate-limits) and each field counts especially high against our [cost limits](/docs/rate-limits#cost-limits). Milestones are just tasks, so they are included in the `num_tasks`, `num_incomplete_tasks`, and `num_completed_tasks` counts. + * @param {String} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTaskCountsForProjectWithHttpInfo", + value: function getTaskCountsForProjectWithHttpInfo(project_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'project_gid' is set + if (project_gid === undefined || project_gid === null) { + throw new Error("Missing the required parameter 'project_gid' when calling getTaskCountsForProject"); + } + var pathParams = { + 'project_gid': project_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/projects/{project_gid}/task_counts', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get task count of a project + * Get an object that holds task count fields. **All fields are excluded by default**. You must [opt in](/docs/inputoutput-options) using `opt_fields` to get any information from this endpoint. This endpoint has an additional [rate limit](/docs/rate-limits) and each field counts especially high against our [cost limits](/docs/rate-limits#cost-limits). Milestones are just tasks, so they are included in the `num_tasks`, `num_incomplete_tasks`, and `num_completed_tasks` counts. + * @param {<&vendorExtensions.x-jsdoc-type>} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TaskCountResponseData} + */ + }, { + key: "getTaskCountsForProject", + value: function getTaskCountsForProject(project_gid, opts) { + return this.getTaskCountsForProjectWithHttpInfo(project_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Create a project template from a project + * Creates and returns a job that will asynchronously handle the project template creation. Note that while the resulting project template can be accessed with the API, it won't be visible in the Asana UI until Project Templates 2.0 is launched in the app. See more in [this forum post](https://forum.asana.com/t/a-new-api-for-project-templates/156432). + * @param {module:model/Object} body Describes the inputs used for creating a project template, such as the resulting project template's name, which team it should be created in. + * @param {String} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "projectSaveAsTemplateWithHttpInfo", + value: function projectSaveAsTemplateWithHttpInfo(body, project_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling projectSaveAsTemplate"); + } + // verify the required parameter 'project_gid' is set + if (project_gid === undefined || project_gid === null) { + throw new Error("Missing the required parameter 'project_gid' when calling projectSaveAsTemplate"); + } + var pathParams = { + 'project_gid': project_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/projects/{project_gid}/saveAsTemplate', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create a project template from a project + * Creates and returns a job that will asynchronously handle the project template creation. Note that while the resulting project template can be accessed with the API, it won't be visible in the Asana UI until Project Templates 2.0 is launched in the app. See more in [this forum post](https://forum.asana.com/t/a-new-api-for-project-templates/156432). + * @param {<&vendorExtensions.x-jsdoc-type>} body Describes the inputs used for creating a project template, such as the resulting project template's name, which team it should be created in. + * @param {<&vendorExtensions.x-jsdoc-type>} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/JobResponseData} + */ + }, { + key: "projectSaveAsTemplate", + value: function projectSaveAsTemplate(body, project_gid, opts) { + return this.projectSaveAsTemplateWithHttpInfo(body, project_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Remove a custom field from a project + * Removes a custom field setting from a project. + * @param {module:model/Object} body Information about the custom field setting being removed. + * @param {String} project_gid Globally unique identifier for the project. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "removeCustomFieldSettingForProjectWithHttpInfo", + value: function removeCustomFieldSettingForProjectWithHttpInfo(body, project_gid) { + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling removeCustomFieldSettingForProject"); + } + // verify the required parameter 'project_gid' is set + if (project_gid === undefined || project_gid === null) { + throw new Error("Missing the required parameter 'project_gid' when calling removeCustomFieldSettingForProject"); + } + var pathParams = { + 'project_gid': project_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/projects/{project_gid}/removeCustomFieldSetting', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Remove a custom field from a project + * Removes a custom field setting from a project. + * @param {<&vendorExtensions.x-jsdoc-type>} body Information about the custom field setting being removed. + * @param {<&vendorExtensions.x-jsdoc-type>} project_gid Globally unique identifier for the project. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "removeCustomFieldSettingForProject", + value: function removeCustomFieldSettingForProject(body, project_gid) { + return this.removeCustomFieldSettingForProjectWithHttpInfo(body, project_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Remove followers from a project + * Removes the specified list of users from following the project, this will not affect project membership status. Returns the updated project record. + * @param {module:model/Object} body Information about the followers being removed. + * @param {String} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "removeFollowersForProjectWithHttpInfo", + value: function removeFollowersForProjectWithHttpInfo(body, project_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling removeFollowersForProject"); + } + // verify the required parameter 'project_gid' is set + if (project_gid === undefined || project_gid === null) { + throw new Error("Missing the required parameter 'project_gid' when calling removeFollowersForProject"); + } + var pathParams = { + 'project_gid': project_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/projects/{project_gid}/removeFollowers', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Remove followers from a project + * Removes the specified list of users from following the project, this will not affect project membership status. Returns the updated project record. + * @param {<&vendorExtensions.x-jsdoc-type>} body Information about the followers being removed. + * @param {<&vendorExtensions.x-jsdoc-type>} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectResponseData} + */ + }, { + key: "removeFollowersForProject", + value: function removeFollowersForProject(body, project_gid, opts) { + return this.removeFollowersForProjectWithHttpInfo(body, project_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Remove users from a project + * Removes the specified list of users from members of the project. Returns the updated project record. + * @param {module:model/Object} body Information about the members being removed. + * @param {String} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "removeMembersForProjectWithHttpInfo", + value: function removeMembersForProjectWithHttpInfo(body, project_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling removeMembersForProject"); + } + // verify the required parameter 'project_gid' is set + if (project_gid === undefined || project_gid === null) { + throw new Error("Missing the required parameter 'project_gid' when calling removeMembersForProject"); + } + var pathParams = { + 'project_gid': project_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/projects/{project_gid}/removeMembers', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Remove users from a project + * Removes the specified list of users from members of the project. Returns the updated project record. + * @param {<&vendorExtensions.x-jsdoc-type>} body Information about the members being removed. + * @param {<&vendorExtensions.x-jsdoc-type>} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectResponseData} + */ + }, { + key: "removeMembersForProject", + value: function removeMembersForProject(body, project_gid, opts) { + return this.removeMembersForProjectWithHttpInfo(body, project_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Update a project + * A specific, existing project can be updated by making a PUT request on the URL for that project. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the task. Returns the complete updated project record. + * @param {module:model/Object} body The updated fields for the project. + * @param {String} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "updateProjectWithHttpInfo", + value: function updateProjectWithHttpInfo(body, project_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling updateProject"); + } + // verify the required parameter 'project_gid' is set + if (project_gid === undefined || project_gid === null) { + throw new Error("Missing the required parameter 'project_gid' when calling updateProject"); + } + var pathParams = { + 'project_gid': project_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/projects/{project_gid}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Update a project + * A specific, existing project can be updated by making a PUT request on the URL for that project. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the task. Returns the complete updated project record. + * @param {<&vendorExtensions.x-jsdoc-type>} body The updated fields for the project. + * @param {<&vendorExtensions.x-jsdoc-type>} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/ProjectResponseData} + */ + }, { + key: "updateProject", + value: function updateProject(body, project_gid, opts) { + return this.updateProjectWithHttpInfo(body, project_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/RulesApi.js b/node_modules/asana/dist/api/RulesApi.js new file mode 100644 index 000000000..b07d37041 --- /dev/null +++ b/node_modules/asana/dist/api/RulesApi.js @@ -0,0 +1,95 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.RulesApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* Rules service. +* @module api/RulesApi +* @version 3.0.3 +*/ +var RulesApi = exports.RulesApi = /*#__PURE__*/function () { + /** + * Constructs a new RulesApi. + * @alias module:api/RulesApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function RulesApi(apiClient) { + _classCallCheck(this, RulesApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Trigger a rule + * Trigger a rule which uses an [\"incoming web request\"](/docs/incoming-web-requests) trigger. + * @param {module:model/Object} body A dictionary of variables accessible from within the rule. + * @param {String} rule_trigger_gid The ID of the incoming web request trigger. This value is a path parameter that is automatically generated for the API endpoint. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(RulesApi, [{ + key: "triggerRuleWithHttpInfo", + value: function triggerRuleWithHttpInfo(body, rule_trigger_gid) { + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling triggerRule"); + } + // verify the required parameter 'rule_trigger_gid' is set + if (rule_trigger_gid === undefined || rule_trigger_gid === null) { + throw new Error("Missing the required parameter 'rule_trigger_gid' when calling triggerRule"); + } + var pathParams = { + 'rule_trigger_gid': rule_trigger_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/rule_triggers/{rule_trigger_gid}/run', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Trigger a rule + * Trigger a rule which uses an [\"incoming web request\"](/docs/incoming-web-requests) trigger. + * @param {<&vendorExtensions.x-jsdoc-type>} body A dictionary of variables accessible from within the rule. + * @param {<&vendorExtensions.x-jsdoc-type>} rule_trigger_gid The ID of the incoming web request trigger. This value is a path parameter that is automatically generated for the API endpoint. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/RuleTriggerResponseData} + */ + }, { + key: "triggerRule", + value: function triggerRule(body, rule_trigger_gid) { + return this.triggerRuleWithHttpInfo(body, rule_trigger_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/SectionsApi.js b/node_modules/asana/dist/api/SectionsApi.js new file mode 100644 index 000000000..feeca9ae7 --- /dev/null +++ b/node_modules/asana/dist/api/SectionsApi.js @@ -0,0 +1,405 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SectionsApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* Sections service. +* @module api/SectionsApi +* @version 3.0.3 +*/ +var SectionsApi = exports.SectionsApi = /*#__PURE__*/function () { + /** + * Constructs a new SectionsApi. + * @alias module:api/SectionsApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function SectionsApi(apiClient) { + _classCallCheck(this, SectionsApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Add task to section + * Add a task to a specific, existing section. This will remove the task from other sections of the project. The task will be inserted at the top of a section unless an insert_before or insert_after parameter is declared. This does not work for separators (tasks with the resource_subtype of section). + * @param {String} section_gid The globally unique identifier for the section. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body The task and optionally the insert location. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(SectionsApi, [{ + key: "addTaskForSectionWithHttpInfo", + value: function addTaskForSectionWithHttpInfo(section_gid, opts) { + opts = opts || {}; + var postBody = opts['body']; + // verify the required parameter 'section_gid' is set + if (section_gid === undefined || section_gid === null) { + throw new Error("Missing the required parameter 'section_gid' when calling addTaskForSection"); + } + var pathParams = { + 'section_gid': section_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/sections/{section_gid}/addTask', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Add task to section + * Add a task to a specific, existing section. This will remove the task from other sections of the project. The task will be inserted at the top of a section unless an insert_before or insert_after parameter is declared. This does not work for separators (tasks with the resource_subtype of section). + * @param {<&vendorExtensions.x-jsdoc-type>} section_gid The globally unique identifier for the section. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body The task and optionally the insert location. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "addTaskForSection", + value: function addTaskForSection(section_gid, opts) { + return this.addTaskForSectionWithHttpInfo(section_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Create a section in a project + * Creates a new section in a project. Returns the full record of the newly created section. + * @param {String} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body The section to create. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "createSectionForProjectWithHttpInfo", + value: function createSectionForProjectWithHttpInfo(project_gid, opts) { + opts = opts || {}; + var postBody = opts['body']; + // verify the required parameter 'project_gid' is set + if (project_gid === undefined || project_gid === null) { + throw new Error("Missing the required parameter 'project_gid' when calling createSectionForProject"); + } + var pathParams = { + 'project_gid': project_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/projects/{project_gid}/sections', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create a section in a project + * Creates a new section in a project. Returns the full record of the newly created section. + * @param {<&vendorExtensions.x-jsdoc-type>} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body The section to create. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/SectionResponseData} + */ + }, { + key: "createSectionForProject", + value: function createSectionForProject(project_gid, opts) { + return this.createSectionForProjectWithHttpInfo(project_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Delete a section + * A specific, existing section can be deleted by making a DELETE request on the URL for that section. Note that sections must be empty to be deleted. The last remaining section cannot be deleted. Returns an empty data block. + * @param {String} section_gid The globally unique identifier for the section. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "deleteSectionWithHttpInfo", + value: function deleteSectionWithHttpInfo(section_gid) { + var postBody = null; + // verify the required parameter 'section_gid' is set + if (section_gid === undefined || section_gid === null) { + throw new Error("Missing the required parameter 'section_gid' when calling deleteSection"); + } + var pathParams = { + 'section_gid': section_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/sections/{section_gid}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Delete a section + * A specific, existing section can be deleted by making a DELETE request on the URL for that section. Note that sections must be empty to be deleted. The last remaining section cannot be deleted. Returns an empty data block. + * @param {<&vendorExtensions.x-jsdoc-type>} section_gid The globally unique identifier for the section. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "deleteSection", + value: function deleteSection(section_gid) { + return this.deleteSectionWithHttpInfo(section_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a section + * Returns the complete record for a single section. + * @param {String} section_gid The globally unique identifier for the section. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getSectionWithHttpInfo", + value: function getSectionWithHttpInfo(section_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'section_gid' is set + if (section_gid === undefined || section_gid === null) { + throw new Error("Missing the required parameter 'section_gid' when calling getSection"); + } + var pathParams = { + 'section_gid': section_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/sections/{section_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a section + * Returns the complete record for a single section. + * @param {<&vendorExtensions.x-jsdoc-type>} section_gid The globally unique identifier for the section. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/SectionResponseData} + */ + }, { + key: "getSection", + value: function getSection(section_gid, opts) { + return this.getSectionWithHttpInfo(section_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get sections in a project + * Returns the compact records for all sections in the specified project. + * @param {String} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getSectionsForProjectWithHttpInfo", + value: function getSectionsForProjectWithHttpInfo(project_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'project_gid' is set + if (project_gid === undefined || project_gid === null) { + throw new Error("Missing the required parameter 'project_gid' when calling getSectionsForProject"); + } + var pathParams = { + 'project_gid': project_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/projects/{project_gid}/sections', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/projects/{project_gid}/sections', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/projects/{project_gid}/sections', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get sections in a project + * Returns the compact records for all sections in the specified project. + * @param {<&vendorExtensions.x-jsdoc-type>} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/SectionResponseArray} + */ + }, { + key: "getSectionsForProject", + value: function getSectionsForProject(project_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getSectionsForProjectWithHttpInfo(project_gid, opts); + } + return this.getSectionsForProjectWithHttpInfo(project_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Move or Insert sections + * Move sections relative to each other. One of `before_section` or `after_section` is required. Sections cannot be moved between projects. Returns an empty data block. + * @param {String} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body The section's move action. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "insertSectionForProjectWithHttpInfo", + value: function insertSectionForProjectWithHttpInfo(project_gid, opts) { + opts = opts || {}; + var postBody = opts['body']; + // verify the required parameter 'project_gid' is set + if (project_gid === undefined || project_gid === null) { + throw new Error("Missing the required parameter 'project_gid' when calling insertSectionForProject"); + } + var pathParams = { + 'project_gid': project_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/projects/{project_gid}/sections/insert', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Move or Insert sections + * Move sections relative to each other. One of `before_section` or `after_section` is required. Sections cannot be moved between projects. Returns an empty data block. + * @param {<&vendorExtensions.x-jsdoc-type>} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body The section's move action. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "insertSectionForProject", + value: function insertSectionForProject(project_gid, opts) { + return this.insertSectionForProjectWithHttpInfo(project_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Update a section + * A specific, existing section can be updated by making a PUT request on the URL for that project. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. (note that at this time, the only field that can be updated is the `name` field.) When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the task. Returns the complete updated section record. + * @param {String} section_gid The globally unique identifier for the section. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body The section to create. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "updateSectionWithHttpInfo", + value: function updateSectionWithHttpInfo(section_gid, opts) { + opts = opts || {}; + var postBody = opts['body']; + // verify the required parameter 'section_gid' is set + if (section_gid === undefined || section_gid === null) { + throw new Error("Missing the required parameter 'section_gid' when calling updateSection"); + } + var pathParams = { + 'section_gid': section_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/sections/{section_gid}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Update a section + * A specific, existing section can be updated by making a PUT request on the URL for that project. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. (note that at this time, the only field that can be updated is the `name` field.) When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the task. Returns the complete updated section record. + * @param {<&vendorExtensions.x-jsdoc-type>} section_gid The globally unique identifier for the section. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body The section to create. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/SectionResponseData} + */ + }, { + key: "updateSection", + value: function updateSection(section_gid, opts) { + return this.updateSectionWithHttpInfo(section_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/StatusUpdatesApi.js b/node_modules/asana/dist/api/StatusUpdatesApi.js new file mode 100644 index 000000000..8829bfaef --- /dev/null +++ b/node_modules/asana/dist/api/StatusUpdatesApi.js @@ -0,0 +1,260 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.StatusUpdatesApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* StatusUpdates service. +* @module api/StatusUpdatesApi +* @version 3.0.3 +*/ +var StatusUpdatesApi = exports.StatusUpdatesApi = /*#__PURE__*/function () { + /** + * Constructs a new StatusUpdatesApi. + * @alias module:api/StatusUpdatesApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function StatusUpdatesApi(apiClient) { + _classCallCheck(this, StatusUpdatesApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Create a status update + * Creates a new status update on an object. Returns the full record of the newly created status update. + * @param {module:model/Object} body The status update to create. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(StatusUpdatesApi, [{ + key: "createStatusForObjectWithHttpInfo", + value: function createStatusForObjectWithHttpInfo(body, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling createStatusForObject"); + } + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/status_updates', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create a status update + * Creates a new status update on an object. Returns the full record of the newly created status update. + * @param {<&vendorExtensions.x-jsdoc-type>} body The status update to create. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/StatusUpdateResponseData} + */ + }, { + key: "createStatusForObject", + value: function createStatusForObject(body, opts) { + return this.createStatusForObjectWithHttpInfo(body, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Delete a status update + * Deletes a specific, existing status update. Returns an empty data record. + * @param {String} status_update_gid The status update to get. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "deleteStatusWithHttpInfo", + value: function deleteStatusWithHttpInfo(status_update_gid) { + var postBody = null; + // verify the required parameter 'status_update_gid' is set + if (status_update_gid === undefined || status_update_gid === null) { + throw new Error("Missing the required parameter 'status_update_gid' when calling deleteStatus"); + } + var pathParams = { + 'status_update_gid': status_update_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/status_updates/{status_update_gid}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Delete a status update + * Deletes a specific, existing status update. Returns an empty data record. + * @param {<&vendorExtensions.x-jsdoc-type>} status_update_gid The status update to get. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "deleteStatus", + value: function deleteStatus(status_update_gid) { + return this.deleteStatusWithHttpInfo(status_update_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a status update + * Returns the complete record for a single status update. + * @param {String} status_update_gid The status update to get. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getStatusWithHttpInfo", + value: function getStatusWithHttpInfo(status_update_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'status_update_gid' is set + if (status_update_gid === undefined || status_update_gid === null) { + throw new Error("Missing the required parameter 'status_update_gid' when calling getStatus"); + } + var pathParams = { + 'status_update_gid': status_update_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/status_updates/{status_update_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a status update + * Returns the complete record for a single status update. + * @param {<&vendorExtensions.x-jsdoc-type>} status_update_gid The status update to get. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/StatusUpdateResponseData} + */ + }, { + key: "getStatus", + value: function getStatus(status_update_gid, opts) { + return this.getStatusWithHttpInfo(status_update_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get status updates from an object + * Returns the compact status update records for all updates on the object. + * @param {String} parent Globally unique identifier for object to fetch statuses from. Must be a GID for a project, portfolio, or goal. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Date} opts.created_since Only return statuses that have been created since the given time. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getStatusesForObjectWithHttpInfo", + value: function getStatusesForObjectWithHttpInfo(parent, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'parent' is set + if (parent === undefined || parent === null) { + throw new Error("Missing the required parameter 'parent' when calling getStatusesForObject"); + } + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + queryParams['parent'] = parent; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/status_updates', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/status_updates', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/status_updates', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get status updates from an object + * Returns the compact status update records for all updates on the object. + * @param {<&vendorExtensions.x-jsdoc-type>} parent Globally unique identifier for object to fetch statuses from. Must be a GID for a project, portfolio, or goal. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Date} opts.created_since Only return statuses that have been created since the given time. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/StatusUpdateResponseArray} + */ + }, { + key: "getStatusesForObject", + value: function getStatusesForObject(parent, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getStatusesForObjectWithHttpInfo(parent, opts); + } + return this.getStatusesForObjectWithHttpInfo(parent, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/StoriesApi.js b/node_modules/asana/dist/api/StoriesApi.js new file mode 100644 index 000000000..55790a9f8 --- /dev/null +++ b/node_modules/asana/dist/api/StoriesApi.js @@ -0,0 +1,317 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.StoriesApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* Stories service. +* @module api/StoriesApi +* @version 3.0.3 +*/ +var StoriesApi = exports.StoriesApi = /*#__PURE__*/function () { + /** + * Constructs a new StoriesApi. + * @alias module:api/StoriesApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function StoriesApi(apiClient) { + _classCallCheck(this, StoriesApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Create a story on a task + * Adds a story to a task. This endpoint currently only allows for comment stories to be created. The comment will be authored by the currently authenticated user, and timestamped when the server receives the request. Returns the full record for the new story added to the task. + * @param {module:model/Object} body The story to create. + * @param {String} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(StoriesApi, [{ + key: "createStoryForTaskWithHttpInfo", + value: function createStoryForTaskWithHttpInfo(body, task_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling createStoryForTask"); + } + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling createStoryForTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tasks/{task_gid}/stories', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create a story on a task + * Adds a story to a task. This endpoint currently only allows for comment stories to be created. The comment will be authored by the currently authenticated user, and timestamped when the server receives the request. Returns the full record for the new story added to the task. + * @param {<&vendorExtensions.x-jsdoc-type>} body The story to create. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/StoryResponseData} + */ + }, { + key: "createStoryForTask", + value: function createStoryForTask(body, task_gid, opts) { + return this.createStoryForTaskWithHttpInfo(body, task_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Delete a story + * Deletes a story. A user can only delete stories they have created. Returns an empty data record. + * @param {String} story_gid Globally unique identifier for the story. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "deleteStoryWithHttpInfo", + value: function deleteStoryWithHttpInfo(story_gid) { + var postBody = null; + // verify the required parameter 'story_gid' is set + if (story_gid === undefined || story_gid === null) { + throw new Error("Missing the required parameter 'story_gid' when calling deleteStory"); + } + var pathParams = { + 'story_gid': story_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/stories/{story_gid}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Delete a story + * Deletes a story. A user can only delete stories they have created. Returns an empty data record. + * @param {<&vendorExtensions.x-jsdoc-type>} story_gid Globally unique identifier for the story. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "deleteStory", + value: function deleteStory(story_gid) { + return this.deleteStoryWithHttpInfo(story_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get stories from a task + * Returns the compact records for all stories on the task. + * @param {String} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getStoriesForTaskWithHttpInfo", + value: function getStoriesForTaskWithHttpInfo(task_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling getStoriesForTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/tasks/{task_gid}/stories', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/tasks/{task_gid}/stories', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/tasks/{task_gid}/stories', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get stories from a task + * Returns the compact records for all stories on the task. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/StoryResponseArray} + */ + }, { + key: "getStoriesForTask", + value: function getStoriesForTask(task_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getStoriesForTaskWithHttpInfo(task_gid, opts); + } + return this.getStoriesForTaskWithHttpInfo(task_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a story + * Returns the full record for a single story. + * @param {String} story_gid Globally unique identifier for the story. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getStoryWithHttpInfo", + value: function getStoryWithHttpInfo(story_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'story_gid' is set + if (story_gid === undefined || story_gid === null) { + throw new Error("Missing the required parameter 'story_gid' when calling getStory"); + } + var pathParams = { + 'story_gid': story_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/stories/{story_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a story + * Returns the full record for a single story. + * @param {<&vendorExtensions.x-jsdoc-type>} story_gid Globally unique identifier for the story. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/StoryResponseData} + */ + }, { + key: "getStory", + value: function getStory(story_gid, opts) { + return this.getStoryWithHttpInfo(story_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Update a story + * Updates the story and returns the full record for the updated story. Only comment stories can have their text updated, and only comment stories and attachment stories can be pinned. Only one of `text` and `html_text` can be specified. + * @param {module:model/Object} body The comment story to update. + * @param {String} story_gid Globally unique identifier for the story. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "updateStoryWithHttpInfo", + value: function updateStoryWithHttpInfo(body, story_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling updateStory"); + } + // verify the required parameter 'story_gid' is set + if (story_gid === undefined || story_gid === null) { + throw new Error("Missing the required parameter 'story_gid' when calling updateStory"); + } + var pathParams = { + 'story_gid': story_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/stories/{story_gid}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Update a story + * Updates the story and returns the full record for the updated story. Only comment stories can have their text updated, and only comment stories and attachment stories can be pinned. Only one of `text` and `html_text` can be specified. + * @param {<&vendorExtensions.x-jsdoc-type>} body The comment story to update. + * @param {<&vendorExtensions.x-jsdoc-type>} story_gid Globally unique identifier for the story. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/StoryResponseData} + */ + }, { + key: "updateStory", + value: function updateStory(body, story_gid, opts) { + return this.updateStoryWithHttpInfo(body, story_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/TagsApi.js b/node_modules/asana/dist/api/TagsApi.js new file mode 100644 index 000000000..53ece69e2 --- /dev/null +++ b/node_modules/asana/dist/api/TagsApi.js @@ -0,0 +1,495 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TagsApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* Tags service. +* @module api/TagsApi +* @version 3.0.3 +*/ +var TagsApi = exports.TagsApi = /*#__PURE__*/function () { + /** + * Constructs a new TagsApi. + * @alias module:api/TagsApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function TagsApi(apiClient) { + _classCallCheck(this, TagsApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Create a tag + * Creates a new tag in a workspace or organization. Every tag is required to be created in a specific workspace or organization, and this cannot be changed once set. Note that you can use the workspace parameter regardless of whether or not it is an organization. Returns the full record of the newly created tag. + * @param {module:model/Object} body The tag to create. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(TagsApi, [{ + key: "createTagWithHttpInfo", + value: function createTagWithHttpInfo(body, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling createTag"); + } + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tags', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create a tag + * Creates a new tag in a workspace or organization. Every tag is required to be created in a specific workspace or organization, and this cannot be changed once set. Note that you can use the workspace parameter regardless of whether or not it is an organization. Returns the full record of the newly created tag. + * @param {<&vendorExtensions.x-jsdoc-type>} body The tag to create. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TagResponseData} + */ + }, { + key: "createTag", + value: function createTag(body, opts) { + return this.createTagWithHttpInfo(body, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Create a tag in a workspace + * Creates a new tag in a workspace or organization. Every tag is required to be created in a specific workspace or organization, and this cannot be changed once set. Note that you can use the workspace parameter regardless of whether or not it is an organization. Returns the full record of the newly created tag. + * @param {module:model/Object} body The tag to create. + * @param {String} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "createTagForWorkspaceWithHttpInfo", + value: function createTagForWorkspaceWithHttpInfo(body, workspace_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling createTagForWorkspace"); + } + // verify the required parameter 'workspace_gid' is set + if (workspace_gid === undefined || workspace_gid === null) { + throw new Error("Missing the required parameter 'workspace_gid' when calling createTagForWorkspace"); + } + var pathParams = { + 'workspace_gid': workspace_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/workspaces/{workspace_gid}/tags', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create a tag in a workspace + * Creates a new tag in a workspace or organization. Every tag is required to be created in a specific workspace or organization, and this cannot be changed once set. Note that you can use the workspace parameter regardless of whether or not it is an organization. Returns the full record of the newly created tag. + * @param {<&vendorExtensions.x-jsdoc-type>} body The tag to create. + * @param {<&vendorExtensions.x-jsdoc-type>} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TagResponseData} + */ + }, { + key: "createTagForWorkspace", + value: function createTagForWorkspace(body, workspace_gid, opts) { + return this.createTagForWorkspaceWithHttpInfo(body, workspace_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Delete a tag + * A specific, existing tag can be deleted by making a DELETE request on the URL for that tag. Returns an empty data record. + * @param {String} tag_gid Globally unique identifier for the tag. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "deleteTagWithHttpInfo", + value: function deleteTagWithHttpInfo(tag_gid) { + var postBody = null; + // verify the required parameter 'tag_gid' is set + if (tag_gid === undefined || tag_gid === null) { + throw new Error("Missing the required parameter 'tag_gid' when calling deleteTag"); + } + var pathParams = { + 'tag_gid': tag_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tags/{tag_gid}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Delete a tag + * A specific, existing tag can be deleted by making a DELETE request on the URL for that tag. Returns an empty data record. + * @param {<&vendorExtensions.x-jsdoc-type>} tag_gid Globally unique identifier for the tag. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "deleteTag", + value: function deleteTag(tag_gid) { + return this.deleteTagWithHttpInfo(tag_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a tag + * Returns the complete tag record for a single tag. + * @param {String} tag_gid Globally unique identifier for the tag. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTagWithHttpInfo", + value: function getTagWithHttpInfo(tag_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'tag_gid' is set + if (tag_gid === undefined || tag_gid === null) { + throw new Error("Missing the required parameter 'tag_gid' when calling getTag"); + } + var pathParams = { + 'tag_gid': tag_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tags/{tag_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a tag + * Returns the complete tag record for a single tag. + * @param {<&vendorExtensions.x-jsdoc-type>} tag_gid Globally unique identifier for the tag. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TagResponseData} + */ + }, { + key: "getTag", + value: function getTag(tag_gid, opts) { + return this.getTagWithHttpInfo(tag_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get multiple tags + * Returns the compact tag records for some filtered set of tags. Use one or more of the parameters provided to filter the tags returned. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {String} opts.workspace The workspace to filter tags on. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTagsWithHttpInfo", + value: function getTagsWithHttpInfo(opts) { + opts = opts || {}; + var postBody = null; + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/tags', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/tags', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/tags', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get multiple tags + * Returns the compact tag records for some filtered set of tags. Use one or more of the parameters provided to filter the tags returned. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {String} opts.workspace The workspace to filter tags on. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TagResponseArray} + */ + }, { + key: "getTags", + value: function getTags(opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getTagsWithHttpInfo(opts); + } + return this.getTagsWithHttpInfo(opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a task's tags + * Get a compact representation of all of the tags the task has. + * @param {String} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTagsForTaskWithHttpInfo", + value: function getTagsForTaskWithHttpInfo(task_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling getTagsForTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/tasks/{task_gid}/tags', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/tasks/{task_gid}/tags', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/tasks/{task_gid}/tags', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a task's tags + * Get a compact representation of all of the tags the task has. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TagResponseArray} + */ + }, { + key: "getTagsForTask", + value: function getTagsForTask(task_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getTagsForTaskWithHttpInfo(task_gid, opts); + } + return this.getTagsForTaskWithHttpInfo(task_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get tags in a workspace + * Returns the compact tag records for some filtered set of tags. Use one or more of the parameters provided to filter the tags returned. + * @param {String} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTagsForWorkspaceWithHttpInfo", + value: function getTagsForWorkspaceWithHttpInfo(workspace_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'workspace_gid' is set + if (workspace_gid === undefined || workspace_gid === null) { + throw new Error("Missing the required parameter 'workspace_gid' when calling getTagsForWorkspace"); + } + var pathParams = { + 'workspace_gid': workspace_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/workspaces/{workspace_gid}/tags', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/workspaces/{workspace_gid}/tags', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/workspaces/{workspace_gid}/tags', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get tags in a workspace + * Returns the compact tag records for some filtered set of tags. Use one or more of the parameters provided to filter the tags returned. + * @param {<&vendorExtensions.x-jsdoc-type>} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TagResponseArray} + */ + }, { + key: "getTagsForWorkspace", + value: function getTagsForWorkspace(workspace_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getTagsForWorkspaceWithHttpInfo(workspace_gid, opts); + } + return this.getTagsForWorkspaceWithHttpInfo(workspace_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Update a tag + * Updates the properties of a tag. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the tag. Returns the complete updated tag record. + * @param {String} tag_gid Globally unique identifier for the tag. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "updateTagWithHttpInfo", + value: function updateTagWithHttpInfo(tag_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'tag_gid' is set + if (tag_gid === undefined || tag_gid === null) { + throw new Error("Missing the required parameter 'tag_gid' when calling updateTag"); + } + var pathParams = { + 'tag_gid': tag_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tags/{tag_gid}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Update a tag + * Updates the properties of a tag. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the tag. Returns the complete updated tag record. + * @param {<&vendorExtensions.x-jsdoc-type>} tag_gid Globally unique identifier for the tag. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TagResponseData} + */ + }, { + key: "updateTag", + value: function updateTag(tag_gid, opts) { + return this.updateTagWithHttpInfo(tag_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/TaskTemplatesApi.js b/node_modules/asana/dist/api/TaskTemplatesApi.js new file mode 100644 index 000000000..31461f526 --- /dev/null +++ b/node_modules/asana/dist/api/TaskTemplatesApi.js @@ -0,0 +1,253 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TaskTemplatesApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* TaskTemplates service. +* @module api/TaskTemplatesApi +* @version 3.0.3 +*/ +var TaskTemplatesApi = exports.TaskTemplatesApi = /*#__PURE__*/function () { + /** + * Constructs a new TaskTemplatesApi. + * @alias module:api/TaskTemplatesApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function TaskTemplatesApi(apiClient) { + _classCallCheck(this, TaskTemplatesApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Delete a task template + * A specific, existing task template can be deleted by making a DELETE request on the URL for that task template. Returns an empty data record. + * @param {String} task_template_gid Globally unique identifier for the task template. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(TaskTemplatesApi, [{ + key: "deleteTaskTemplateWithHttpInfo", + value: function deleteTaskTemplateWithHttpInfo(task_template_gid) { + var postBody = null; + // verify the required parameter 'task_template_gid' is set + if (task_template_gid === undefined || task_template_gid === null) { + throw new Error("Missing the required parameter 'task_template_gid' when calling deleteTaskTemplate"); + } + var pathParams = { + 'task_template_gid': task_template_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/task_templates/{task_template_gid}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Delete a task template + * A specific, existing task template can be deleted by making a DELETE request on the URL for that task template. Returns an empty data record. + * @param {<&vendorExtensions.x-jsdoc-type>} task_template_gid Globally unique identifier for the task template. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "deleteTaskTemplate", + value: function deleteTaskTemplate(task_template_gid) { + return this.deleteTaskTemplateWithHttpInfo(task_template_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a task template + * Returns the complete task template record for a single task template. + * @param {String} task_template_gid Globally unique identifier for the task template. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTaskTemplateWithHttpInfo", + value: function getTaskTemplateWithHttpInfo(task_template_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'task_template_gid' is set + if (task_template_gid === undefined || task_template_gid === null) { + throw new Error("Missing the required parameter 'task_template_gid' when calling getTaskTemplate"); + } + var pathParams = { + 'task_template_gid': task_template_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/task_templates/{task_template_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a task template + * Returns the complete task template record for a single task template. + * @param {<&vendorExtensions.x-jsdoc-type>} task_template_gid Globally unique identifier for the task template. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TaskTemplateResponseData} + */ + }, { + key: "getTaskTemplate", + value: function getTaskTemplate(task_template_gid, opts) { + return this.getTaskTemplateWithHttpInfo(task_template_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get multiple task templates + * Returns the compact task template records for some filtered set of task templates. You must specify a `project` + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {String} opts.project The project to filter task templates on. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTaskTemplatesWithHttpInfo", + value: function getTaskTemplatesWithHttpInfo(opts) { + opts = opts || {}; + var postBody = null; + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/task_templates', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/task_templates', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/task_templates', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get multiple task templates + * Returns the compact task template records for some filtered set of task templates. You must specify a `project` + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {String} opts.project The project to filter task templates on. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TaskTemplateResponseArray} + */ + }, { + key: "getTaskTemplates", + value: function getTaskTemplates(opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getTaskTemplatesWithHttpInfo(opts); + } + return this.getTaskTemplatesWithHttpInfo(opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Instantiate a task from a task template + * Creates and returns a job that will asynchronously handle the task instantiation. + * @param {String} task_template_gid Globally unique identifier for the task template. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body Describes the inputs used for instantiating a task - the task's name. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "instantiateTaskWithHttpInfo", + value: function instantiateTaskWithHttpInfo(task_template_gid, opts) { + opts = opts || {}; + var postBody = opts['body']; + // verify the required parameter 'task_template_gid' is set + if (task_template_gid === undefined || task_template_gid === null) { + throw new Error("Missing the required parameter 'task_template_gid' when calling instantiateTask"); + } + var pathParams = { + 'task_template_gid': task_template_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/task_templates/{task_template_gid}/instantiateTask', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Instantiate a task from a task template + * Creates and returns a job that will asynchronously handle the task instantiation. + * @param {<&vendorExtensions.x-jsdoc-type>} task_template_gid Globally unique identifier for the task template. + * @param {Object} opts Optional parameters + * @param {module:model/Object} opts.body Describes the inputs used for instantiating a task - the task's name. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/JobResponseData} + */ + }, { + key: "instantiateTask", + value: function instantiateTask(task_template_gid, opts) { + return this.instantiateTaskWithHttpInfo(task_template_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/TasksApi.js b/node_modules/asana/dist/api/TasksApi.js new file mode 100644 index 000000000..52daf1e0a --- /dev/null +++ b/node_modules/asana/dist/api/TasksApi.js @@ -0,0 +1,1713 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TasksApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* Tasks service. +* @module api/TasksApi +* @version 3.0.3 +*/ +var TasksApi = exports.TasksApi = /*#__PURE__*/function () { + /** + * Constructs a new TasksApi. + * @alias module:api/TasksApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function TasksApi(apiClient) { + _classCallCheck(this, TasksApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Set dependencies for a task + * Marks a set of tasks as dependencies of this task, if they are not already dependencies. *A task can have at most 30 dependents and dependencies combined*. + * @param {module:model/Object} body The list of tasks to set as dependencies. + * @param {String} task_gid The task to operate on. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(TasksApi, [{ + key: "addDependenciesForTaskWithHttpInfo", + value: function addDependenciesForTaskWithHttpInfo(body, task_gid) { + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling addDependenciesForTask"); + } + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling addDependenciesForTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tasks/{task_gid}/addDependencies', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Set dependencies for a task + * Marks a set of tasks as dependencies of this task, if they are not already dependencies. *A task can have at most 30 dependents and dependencies combined*. + * @param {<&vendorExtensions.x-jsdoc-type>} body The list of tasks to set as dependencies. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "addDependenciesForTask", + value: function addDependenciesForTask(body, task_gid) { + return this.addDependenciesForTaskWithHttpInfo(body, task_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Set dependents for a task + * Marks a set of tasks as dependents of this task, if they are not already dependents. *A task can have at most 30 dependents and dependencies combined*. + * @param {module:model/Object} body The list of tasks to add as dependents. + * @param {String} task_gid The task to operate on. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "addDependentsForTaskWithHttpInfo", + value: function addDependentsForTaskWithHttpInfo(body, task_gid) { + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling addDependentsForTask"); + } + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling addDependentsForTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tasks/{task_gid}/addDependents', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Set dependents for a task + * Marks a set of tasks as dependents of this task, if they are not already dependents. *A task can have at most 30 dependents and dependencies combined*. + * @param {<&vendorExtensions.x-jsdoc-type>} body The list of tasks to add as dependents. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "addDependentsForTask", + value: function addDependentsForTask(body, task_gid) { + return this.addDependentsForTaskWithHttpInfo(body, task_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Add followers to a task + * Adds followers to a task. Returns an empty data block. Each task can be associated with zero or more followers in the system. Requests to add/remove followers, if successful, will return the complete updated task record, described above. + * @param {module:model/Object} body The followers to add to the task. + * @param {String} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "addFollowersForTaskWithHttpInfo", + value: function addFollowersForTaskWithHttpInfo(body, task_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling addFollowersForTask"); + } + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling addFollowersForTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tasks/{task_gid}/addFollowers', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Add followers to a task + * Adds followers to a task. Returns an empty data block. Each task can be associated with zero or more followers in the system. Requests to add/remove followers, if successful, will return the complete updated task record, described above. + * @param {<&vendorExtensions.x-jsdoc-type>} body The followers to add to the task. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TaskResponseData} + */ + }, { + key: "addFollowersForTask", + value: function addFollowersForTask(body, task_gid, opts) { + return this.addFollowersForTaskWithHttpInfo(body, task_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Add a project to a task + * Adds the task to the specified project, in the optional location specified. If no location arguments are given, the task will be added to the end of the project. `addProject` can also be used to reorder a task within a project or section that already contains it. At most one of `insert_before`, `insert_after`, or `section` should be specified. Inserting into a section in an non-order-dependent way can be done by specifying section, otherwise, to insert within a section in a particular place, specify `insert_before` or `insert_after` and a task within the section to anchor the position of this task. Returns an empty data block. + * @param {module:model/Object} body The project to add the task to. + * @param {String} task_gid The task to operate on. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "addProjectForTaskWithHttpInfo", + value: function addProjectForTaskWithHttpInfo(body, task_gid) { + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling addProjectForTask"); + } + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling addProjectForTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tasks/{task_gid}/addProject', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Add a project to a task + * Adds the task to the specified project, in the optional location specified. If no location arguments are given, the task will be added to the end of the project. `addProject` can also be used to reorder a task within a project or section that already contains it. At most one of `insert_before`, `insert_after`, or `section` should be specified. Inserting into a section in an non-order-dependent way can be done by specifying section, otherwise, to insert within a section in a particular place, specify `insert_before` or `insert_after` and a task within the section to anchor the position of this task. Returns an empty data block. + * @param {<&vendorExtensions.x-jsdoc-type>} body The project to add the task to. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "addProjectForTask", + value: function addProjectForTask(body, task_gid) { + return this.addProjectForTaskWithHttpInfo(body, task_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Add a tag to a task + * Adds a tag to a task. Returns an empty data block. + * @param {module:model/Object} body The tag to add to the task. + * @param {String} task_gid The task to operate on. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "addTagForTaskWithHttpInfo", + value: function addTagForTaskWithHttpInfo(body, task_gid) { + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling addTagForTask"); + } + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling addTagForTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tasks/{task_gid}/addTag', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Add a tag to a task + * Adds a tag to a task. Returns an empty data block. + * @param {<&vendorExtensions.x-jsdoc-type>} body The tag to add to the task. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "addTagForTask", + value: function addTagForTask(body, task_gid) { + return this.addTagForTaskWithHttpInfo(body, task_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Create a subtask + * Creates a new subtask and adds it to the parent task. Returns the full record for the newly created subtask. + * @param {module:model/Object} body The new subtask to create. + * @param {String} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "createSubtaskForTaskWithHttpInfo", + value: function createSubtaskForTaskWithHttpInfo(body, task_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling createSubtaskForTask"); + } + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling createSubtaskForTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tasks/{task_gid}/subtasks', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create a subtask + * Creates a new subtask and adds it to the parent task. Returns the full record for the newly created subtask. + * @param {<&vendorExtensions.x-jsdoc-type>} body The new subtask to create. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TaskResponseData} + */ + }, { + key: "createSubtaskForTask", + value: function createSubtaskForTask(body, task_gid, opts) { + return this.createSubtaskForTaskWithHttpInfo(body, task_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Create a task + * Creating a new task is as easy as POSTing to the `/tasks` endpoint with a data block containing the fields you’d like to set on the task. Any unspecified fields will take on default values. Every task is required to be created in a specific workspace, and this workspace cannot be changed once set. The workspace need not be set explicitly if you specify `projects` or a `parent` task instead. + * @param {module:model/Object} body The task to create. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "createTaskWithHttpInfo", + value: function createTaskWithHttpInfo(body, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling createTask"); + } + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tasks', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create a task + * Creating a new task is as easy as POSTing to the `/tasks` endpoint with a data block containing the fields you’d like to set on the task. Any unspecified fields will take on default values. Every task is required to be created in a specific workspace, and this workspace cannot be changed once set. The workspace need not be set explicitly if you specify `projects` or a `parent` task instead. + * @param {<&vendorExtensions.x-jsdoc-type>} body The task to create. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TaskResponseData} + */ + }, { + key: "createTask", + value: function createTask(body, opts) { + return this.createTaskWithHttpInfo(body, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Delete a task + * A specific, existing task can be deleted by making a DELETE request on the URL for that task. Deleted tasks go into the “trash” of the user making the delete request. Tasks can be recovered from the trash within a period of 30 days; afterward they are completely removed from the system. Returns an empty data record. + * @param {String} task_gid The task to operate on. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "deleteTaskWithHttpInfo", + value: function deleteTaskWithHttpInfo(task_gid) { + var postBody = null; + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling deleteTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tasks/{task_gid}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Delete a task + * A specific, existing task can be deleted by making a DELETE request on the URL for that task. Deleted tasks go into the “trash” of the user making the delete request. Tasks can be recovered from the trash within a period of 30 days; afterward they are completely removed from the system. Returns an empty data record. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "deleteTask", + value: function deleteTask(task_gid) { + return this.deleteTaskWithHttpInfo(task_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Duplicate a task + * Creates and returns a job that will asynchronously handle the duplication. + * @param {module:model/Object} body Describes the duplicate's name and the fields that will be duplicated. + * @param {String} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "duplicateTaskWithHttpInfo", + value: function duplicateTaskWithHttpInfo(body, task_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling duplicateTask"); + } + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling duplicateTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tasks/{task_gid}/duplicate', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Duplicate a task + * Creates and returns a job that will asynchronously handle the duplication. + * @param {<&vendorExtensions.x-jsdoc-type>} body Describes the duplicate's name and the fields that will be duplicated. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/JobResponseData} + */ + }, { + key: "duplicateTask", + value: function duplicateTask(body, task_gid, opts) { + return this.duplicateTaskWithHttpInfo(body, task_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get dependencies from a task + * Returns the compact representations of all of the dependencies of a task. + * @param {String} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getDependenciesForTaskWithHttpInfo", + value: function getDependenciesForTaskWithHttpInfo(task_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling getDependenciesForTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/tasks/{task_gid}/dependencies', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/tasks/{task_gid}/dependencies', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/tasks/{task_gid}/dependencies', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get dependencies from a task + * Returns the compact representations of all of the dependencies of a task. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TaskResponseArray} + */ + }, { + key: "getDependenciesForTask", + value: function getDependenciesForTask(task_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getDependenciesForTaskWithHttpInfo(task_gid, opts); + } + return this.getDependenciesForTaskWithHttpInfo(task_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get dependents from a task + * Returns the compact representations of all of the dependents of a task. + * @param {String} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getDependentsForTaskWithHttpInfo", + value: function getDependentsForTaskWithHttpInfo(task_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling getDependentsForTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/tasks/{task_gid}/dependents', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/tasks/{task_gid}/dependents', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/tasks/{task_gid}/dependents', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get dependents from a task + * Returns the compact representations of all of the dependents of a task. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TaskResponseArray} + */ + }, { + key: "getDependentsForTask", + value: function getDependentsForTask(task_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getDependentsForTaskWithHttpInfo(task_gid, opts); + } + return this.getDependentsForTaskWithHttpInfo(task_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get subtasks from a task + * Returns a compact representation of all of the subtasks of a task. + * @param {String} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getSubtasksForTaskWithHttpInfo", + value: function getSubtasksForTaskWithHttpInfo(task_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling getSubtasksForTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/tasks/{task_gid}/subtasks', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/tasks/{task_gid}/subtasks', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/tasks/{task_gid}/subtasks', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get subtasks from a task + * Returns a compact representation of all of the subtasks of a task. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TaskResponseArray} + */ + }, { + key: "getSubtasksForTask", + value: function getSubtasksForTask(task_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getSubtasksForTaskWithHttpInfo(task_gid, opts); + } + return this.getSubtasksForTaskWithHttpInfo(task_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a task + * Returns the complete task record for a single task. + * @param {String} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTaskWithHttpInfo", + value: function getTaskWithHttpInfo(task_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling getTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tasks/{task_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a task + * Returns the complete task record for a single task. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TaskResponseData} + */ + }, { + key: "getTask", + value: function getTask(task_gid, opts) { + return this.getTaskWithHttpInfo(task_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a task for a given custom ID + * Returns a task given a custom ID shortcode. + * @param {String} workspace_gid Globally unique identifier for the workspace or organization. + * @param {String} custom_id Generated custom ID for a task. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTaskForCustomIDWithHttpInfo", + value: function getTaskForCustomIDWithHttpInfo(workspace_gid, custom_id) { + var postBody = null; + // verify the required parameter 'workspace_gid' is set + if (workspace_gid === undefined || workspace_gid === null) { + throw new Error("Missing the required parameter 'workspace_gid' when calling getTaskForCustomID"); + } + // verify the required parameter 'custom_id' is set + if (custom_id === undefined || custom_id === null) { + throw new Error("Missing the required parameter 'custom_id' when calling getTaskForCustomID"); + } + var pathParams = { + 'workspace_gid': workspace_gid, + 'custom_id': custom_id + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/workspaces/{workspace_gid}/tasks/custom_id/{custom_id}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a task for a given custom ID + * Returns a task given a custom ID shortcode. + * @param {<&vendorExtensions.x-jsdoc-type>} workspace_gid Globally unique identifier for the workspace or organization. + * @param {<&vendorExtensions.x-jsdoc-type>} custom_id Generated custom ID for a task. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TaskResponseData} + */ + }, { + key: "getTaskForCustomID", + value: function getTaskForCustomID(workspace_gid, custom_id) { + return this.getTaskForCustomIDWithHttpInfo(workspace_gid, custom_id).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get multiple tasks + * Returns the compact task records for some filtered set of tasks. Use one or more of the parameters provided to filter the tasks returned. You must specify a `project` or `tag` if you do not specify `assignee` and `workspace`. For more complex task retrieval, use [workspaces/{workspace_gid}/tasks/search](/reference/searchtasksforworkspace). + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {String} opts.assignee The assignee to filter tasks on. If searching for unassigned tasks, assignee.any = null can be specified. *Note: If you specify `assignee`, you must also specify the `workspace` to filter on.* + * @param {String} opts.project The project to filter tasks on. + * @param {String} opts.section The section to filter tasks on. + * @param {String} opts.workspace The workspace to filter tasks on. *Note: If you specify `workspace`, you must also specify the `assignee` to filter on.* + * @param {Date} opts.completed_since Only return tasks that are either incomplete or that have been completed since this time. + * @param {Date} opts.modified_since Only return tasks that have been modified since the given time. *Note: A task is considered “modified” if any of its properties change, or associations between it and other objects are modified (e.g. a task being added to a project). A task is not considered modified just because another object it is associated with (e.g. a subtask) is modified. Actions that count as modifying the task include assigning, renaming, completing, and adding stories.* + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTasksWithHttpInfo", + value: function getTasksWithHttpInfo(opts) { + opts = opts || {}; + var postBody = null; + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/tasks', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/tasks', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/tasks', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get multiple tasks + * Returns the compact task records for some filtered set of tasks. Use one or more of the parameters provided to filter the tasks returned. You must specify a `project` or `tag` if you do not specify `assignee` and `workspace`. For more complex task retrieval, use [workspaces/{workspace_gid}/tasks/search](/reference/searchtasksforworkspace). + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {String} opts.assignee The assignee to filter tasks on. If searching for unassigned tasks, assignee.any = null can be specified. *Note: If you specify `assignee`, you must also specify the `workspace` to filter on.* + * @param {String} opts.project The project to filter tasks on. + * @param {String} opts.section The section to filter tasks on. + * @param {String} opts.workspace The workspace to filter tasks on. *Note: If you specify `workspace`, you must also specify the `assignee` to filter on.* + * @param {Date} opts.completed_since Only return tasks that are either incomplete or that have been completed since this time. + * @param {Date} opts.modified_since Only return tasks that have been modified since the given time. *Note: A task is considered “modified” if any of its properties change, or associations between it and other objects are modified (e.g. a task being added to a project). A task is not considered modified just because another object it is associated with (e.g. a subtask) is modified. Actions that count as modifying the task include assigning, renaming, completing, and adding stories.* + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TaskResponseArray} + */ + }, { + key: "getTasks", + value: function getTasks(opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getTasksWithHttpInfo(opts); + } + return this.getTasksWithHttpInfo(opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get tasks from a project + * Returns the compact task records for all tasks within the given project, ordered by their priority within the project. Tasks can exist in more than one project at a time. + * @param {String} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {String} opts.completed_since Only return tasks that are either incomplete or that have been completed since this time. Accepts a date-time string or the keyword *now*. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTasksForProjectWithHttpInfo", + value: function getTasksForProjectWithHttpInfo(project_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'project_gid' is set + if (project_gid === undefined || project_gid === null) { + throw new Error("Missing the required parameter 'project_gid' when calling getTasksForProject"); + } + var pathParams = { + 'project_gid': project_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/projects/{project_gid}/tasks', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/projects/{project_gid}/tasks', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/projects/{project_gid}/tasks', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get tasks from a project + * Returns the compact task records for all tasks within the given project, ordered by their priority within the project. Tasks can exist in more than one project at a time. + * @param {<&vendorExtensions.x-jsdoc-type>} project_gid Globally unique identifier for the project. + * @param {Object} opts Optional parameters + * @param {String} opts.completed_since Only return tasks that are either incomplete or that have been completed since this time. Accepts a date-time string or the keyword *now*. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TaskResponseArray} + */ + }, { + key: "getTasksForProject", + value: function getTasksForProject(project_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getTasksForProjectWithHttpInfo(project_gid, opts); + } + return this.getTasksForProjectWithHttpInfo(project_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get tasks from a section + * *Board view only*: Returns the compact section records for all tasks within the given section. + * @param {String} section_gid The globally unique identifier for the section. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {String} opts.completed_since Only return tasks that are either incomplete or that have been completed since this time. Accepts a date-time string or the keyword *now*. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTasksForSectionWithHttpInfo", + value: function getTasksForSectionWithHttpInfo(section_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'section_gid' is set + if (section_gid === undefined || section_gid === null) { + throw new Error("Missing the required parameter 'section_gid' when calling getTasksForSection"); + } + var pathParams = { + 'section_gid': section_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/sections/{section_gid}/tasks', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/sections/{section_gid}/tasks', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/sections/{section_gid}/tasks', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get tasks from a section + * *Board view only*: Returns the compact section records for all tasks within the given section. + * @param {<&vendorExtensions.x-jsdoc-type>} section_gid The globally unique identifier for the section. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {String} opts.completed_since Only return tasks that are either incomplete or that have been completed since this time. Accepts a date-time string or the keyword *now*. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TaskResponseArray} + */ + }, { + key: "getTasksForSection", + value: function getTasksForSection(section_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getTasksForSectionWithHttpInfo(section_gid, opts); + } + return this.getTasksForSectionWithHttpInfo(section_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get tasks from a tag + * Returns the compact task records for all tasks with the given tag. Tasks can have more than one tag at a time. + * @param {String} tag_gid Globally unique identifier for the tag. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTasksForTagWithHttpInfo", + value: function getTasksForTagWithHttpInfo(tag_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'tag_gid' is set + if (tag_gid === undefined || tag_gid === null) { + throw new Error("Missing the required parameter 'tag_gid' when calling getTasksForTag"); + } + var pathParams = { + 'tag_gid': tag_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/tags/{tag_gid}/tasks', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/tags/{tag_gid}/tasks', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/tags/{tag_gid}/tasks', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get tasks from a tag + * Returns the compact task records for all tasks with the given tag. Tasks can have more than one tag at a time. + * @param {<&vendorExtensions.x-jsdoc-type>} tag_gid Globally unique identifier for the tag. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TaskResponseArray} + */ + }, { + key: "getTasksForTag", + value: function getTasksForTag(tag_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getTasksForTagWithHttpInfo(tag_gid, opts); + } + return this.getTasksForTagWithHttpInfo(tag_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get tasks from a user task list + * Returns the compact list of tasks in a user’s My Tasks list. *Note: Access control is enforced for this endpoint as with all Asana API endpoints, meaning a user’s private tasks will be filtered out if the API-authenticated user does not have access to them.* *Note: Both complete and incomplete tasks are returned by default unless they are filtered out (for example, setting `completed_since=now` will return only incomplete tasks, which is the default view for “My Tasks” in Asana.)* + * @param {String} user_task_list_gid Globally unique identifier for the user task list. + * @param {Object} opts Optional parameters + * @param {String} opts.completed_since Only return tasks that are either incomplete or that have been completed since this time. Accepts a date-time string or the keyword *now*. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTasksForUserTaskListWithHttpInfo", + value: function getTasksForUserTaskListWithHttpInfo(user_task_list_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'user_task_list_gid' is set + if (user_task_list_gid === undefined || user_task_list_gid === null) { + throw new Error("Missing the required parameter 'user_task_list_gid' when calling getTasksForUserTaskList"); + } + var pathParams = { + 'user_task_list_gid': user_task_list_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/user_task_lists/{user_task_list_gid}/tasks', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/user_task_lists/{user_task_list_gid}/tasks', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/user_task_lists/{user_task_list_gid}/tasks', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get tasks from a user task list + * Returns the compact list of tasks in a user’s My Tasks list. *Note: Access control is enforced for this endpoint as with all Asana API endpoints, meaning a user’s private tasks will be filtered out if the API-authenticated user does not have access to them.* *Note: Both complete and incomplete tasks are returned by default unless they are filtered out (for example, setting `completed_since=now` will return only incomplete tasks, which is the default view for “My Tasks” in Asana.)* + * @param {<&vendorExtensions.x-jsdoc-type>} user_task_list_gid Globally unique identifier for the user task list. + * @param {Object} opts Optional parameters + * @param {String} opts.completed_since Only return tasks that are either incomplete or that have been completed since this time. Accepts a date-time string or the keyword *now*. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TaskResponseArray} + */ + }, { + key: "getTasksForUserTaskList", + value: function getTasksForUserTaskList(user_task_list_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getTasksForUserTaskListWithHttpInfo(user_task_list_gid, opts); + } + return this.getTasksForUserTaskListWithHttpInfo(user_task_list_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Unlink dependencies from a task + * Unlinks a set of dependencies from this task. + * @param {module:model/Object} body The list of tasks to unlink as dependencies. + * @param {String} task_gid The task to operate on. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "removeDependenciesForTaskWithHttpInfo", + value: function removeDependenciesForTaskWithHttpInfo(body, task_gid) { + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling removeDependenciesForTask"); + } + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling removeDependenciesForTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tasks/{task_gid}/removeDependencies', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Unlink dependencies from a task + * Unlinks a set of dependencies from this task. + * @param {<&vendorExtensions.x-jsdoc-type>} body The list of tasks to unlink as dependencies. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "removeDependenciesForTask", + value: function removeDependenciesForTask(body, task_gid) { + return this.removeDependenciesForTaskWithHttpInfo(body, task_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Unlink dependents from a task + * Unlinks a set of dependents from this task. + * @param {module:model/Object} body The list of tasks to remove as dependents. + * @param {String} task_gid The task to operate on. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "removeDependentsForTaskWithHttpInfo", + value: function removeDependentsForTaskWithHttpInfo(body, task_gid) { + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling removeDependentsForTask"); + } + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling removeDependentsForTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tasks/{task_gid}/removeDependents', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Unlink dependents from a task + * Unlinks a set of dependents from this task. + * @param {<&vendorExtensions.x-jsdoc-type>} body The list of tasks to remove as dependents. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "removeDependentsForTask", + value: function removeDependentsForTask(body, task_gid) { + return this.removeDependentsForTaskWithHttpInfo(body, task_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Remove followers from a task + * Removes each of the specified followers from the task if they are following. Returns the complete, updated record for the affected task. + * @param {module:model/Object} body The followers to remove from the task. + * @param {String} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "removeFollowerForTaskWithHttpInfo", + value: function removeFollowerForTaskWithHttpInfo(body, task_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling removeFollowerForTask"); + } + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling removeFollowerForTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tasks/{task_gid}/removeFollowers', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Remove followers from a task + * Removes each of the specified followers from the task if they are following. Returns the complete, updated record for the affected task. + * @param {<&vendorExtensions.x-jsdoc-type>} body The followers to remove from the task. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TaskResponseData} + */ + }, { + key: "removeFollowerForTask", + value: function removeFollowerForTask(body, task_gid, opts) { + return this.removeFollowerForTaskWithHttpInfo(body, task_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Remove a project from a task + * Removes the task from the specified project. The task will still exist in the system, but it will not be in the project anymore. Returns an empty data block. + * @param {module:model/Object} body The project to remove the task from. + * @param {String} task_gid The task to operate on. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "removeProjectForTaskWithHttpInfo", + value: function removeProjectForTaskWithHttpInfo(body, task_gid) { + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling removeProjectForTask"); + } + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling removeProjectForTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tasks/{task_gid}/removeProject', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Remove a project from a task + * Removes the task from the specified project. The task will still exist in the system, but it will not be in the project anymore. Returns an empty data block. + * @param {<&vendorExtensions.x-jsdoc-type>} body The project to remove the task from. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "removeProjectForTask", + value: function removeProjectForTask(body, task_gid) { + return this.removeProjectForTaskWithHttpInfo(body, task_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Remove a tag from a task + * Removes a tag from a task. Returns an empty data block. + * @param {module:model/Object} body The tag to remove from the task. + * @param {String} task_gid The task to operate on. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "removeTagForTaskWithHttpInfo", + value: function removeTagForTaskWithHttpInfo(body, task_gid) { + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling removeTagForTask"); + } + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling removeTagForTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tasks/{task_gid}/removeTag', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Remove a tag from a task + * Removes a tag from a task. Returns an empty data block. + * @param {<&vendorExtensions.x-jsdoc-type>} body The tag to remove from the task. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "removeTagForTask", + value: function removeTagForTask(body, task_gid) { + return this.removeTagForTaskWithHttpInfo(body, task_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Search tasks in a workspace + * To mirror the functionality of the Asana web app's advanced search feature, the Asana API has a task search endpoint that allows you to build complex filters to find and retrieve the exact data you need. #### Premium access Like the Asana web product's advance search feature, this search endpoint will only be available to premium Asana users. A user is premium if any of the following is true: - The workspace in which the search is being performed is a premium workspace - The user is a member of a premium team inside the workspace Even if a user is only a member of a premium team inside a non-premium workspace, search will allow them to find data anywhere in the workspace, not just inside the premium team. Making a search request using credentials of a non-premium user will result in a `402 Payment Required` error. #### Pagination Search results are not stable; repeating the same query multiple times may return the data in a different order, even if the data do not change. Because of this, the traditional [pagination](https://developers.asana.com/docs/#pagination) available elsewhere in the Asana API is not available here. However, you can paginate manually by sorting the search results by their creation time and then modifying each subsequent query to exclude data you have already seen. Page sizes are limited to a maximum of 100 items, and can be specified by the `limit` query parameter. #### Eventual consistency Changes in Asana (regardless of whether they’re made though the web product or the API) are forwarded to our search infrastructure to be indexed. This process can take between 10 and 60 seconds to complete under normal operation, and longer during some production incidents. Making a change to a task that would alter its presence in a particular search query will not be reflected immediately. This is also true of the advanced search feature in the web product. #### Rate limits You may receive a `429 Too Many Requests` response if you hit any of our [rate limits](https://developers.asana.com/docs/#rate-limits). #### Custom field parameters | Parameter name | Custom field type | Accepted type | |---|---|---| | custom_fields.{gid}.is_set | All | Boolean | | custom_fields.{gid}.value | Text | String | | custom_fields.{gid}.value | Number | Number | | custom_fields.{gid}.value | Enum | Enum option ID | | custom_fields.{gid}.starts_with | Text only | String | | custom_fields.{gid}.ends_with | Text only | String | | custom_fields.{gid}.contains | Text only | String | | custom_fields.{gid}.less_than | Number only | Number | | custom_fields.{gid}.greater_than | Number only | Number | For example, if the gid of the custom field is 12345, these query parameter to find tasks where it is set would be `custom_fields.12345.is_set=true`. To match an exact value for an enum custom field, use the gid of the desired enum option and not the name of the enum option: `custom_fields.12345.value=67890`. **Not Supported**: searching for multiple exact matches of a custom field, searching for multi-enum custom field *Note: If you specify `projects.any` and `sections.any`, you will receive tasks for the project **and** tasks for the section. If you're looking for only tasks in a section, omit the `projects.any` from the request.* + * @param {String} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {String} opts.text Performs full-text search on both task name and description + * @param {module:model/String} opts.resource_subtype Filters results by the task's resource_subtype (default to <.>) + * @param {String} opts.assignee.any Comma-separated list of user identifiers + * @param {String} opts.assignee.not Comma-separated list of user identifiers + * @param {String} opts.portfolios.any Comma-separated list of portfolio IDs + * @param {String} opts.projects.any Comma-separated list of project IDs + * @param {String} opts.projects.not Comma-separated list of project IDs + * @param {String} opts.projects.all Comma-separated list of project IDs + * @param {String} opts.sections.any Comma-separated list of section or column IDs + * @param {String} opts.sections.not Comma-separated list of section or column IDs + * @param {String} opts.sections.all Comma-separated list of section or column IDs + * @param {String} opts.tags.any Comma-separated list of tag IDs + * @param {String} opts.tags.not Comma-separated list of tag IDs + * @param {String} opts.tags.all Comma-separated list of tag IDs + * @param {String} opts.teams.any Comma-separated list of team IDs + * @param {String} opts.followers.not Comma-separated list of user identifiers + * @param {String} opts.created_by.any Comma-separated list of user identifiers + * @param {String} opts.created_by.not Comma-separated list of user identifiers + * @param {String} opts.assigned_by.any Comma-separated list of user identifiers + * @param {String} opts.assigned_by.not Comma-separated list of user identifiers + * @param {String} opts.liked_by.not Comma-separated list of user identifiers + * @param {String} opts.commented_on_by.not Comma-separated list of user identifiers + * @param {Date} opts.due_on.before ISO 8601 date string + * @param {Date} opts.due_on.after ISO 8601 date string + * @param {Date} opts.due_on ISO 8601 date string or `null` + * @param {Date} opts.due_at.before ISO 8601 datetime string + * @param {Date} opts.due_at.after ISO 8601 datetime string + * @param {Date} opts.start_on.before ISO 8601 date string + * @param {Date} opts.start_on.after ISO 8601 date string + * @param {Date} opts.start_on ISO 8601 date string or `null` + * @param {Date} opts.created_on.before ISO 8601 date string + * @param {Date} opts.created_on.after ISO 8601 date string + * @param {Date} opts.created_on ISO 8601 date string or `null` + * @param {Date} opts.created_at.before ISO 8601 datetime string + * @param {Date} opts.created_at.after ISO 8601 datetime string + * @param {Date} opts.completed_on.before ISO 8601 date string + * @param {Date} opts.completed_on.after ISO 8601 date string + * @param {Date} opts.completed_on ISO 8601 date string or `null` + * @param {Date} opts.completed_at.before ISO 8601 datetime string + * @param {Date} opts.completed_at.after ISO 8601 datetime string + * @param {Date} opts.modified_on.before ISO 8601 date string + * @param {Date} opts.modified_on.after ISO 8601 date string + * @param {Date} opts.modified_on ISO 8601 date string or `null` + * @param {Date} opts.modified_at.before ISO 8601 datetime string + * @param {Date} opts.modified_at.after ISO 8601 datetime string + * @param {Boolean} opts.is_blocking Filter to incomplete tasks with dependents + * @param {Boolean} opts.is_blocked Filter to tasks with incomplete dependencies + * @param {Boolean} opts.has_attachment Filter to tasks with attachments + * @param {Boolean} opts.completed Filter to completed tasks + * @param {Boolean} opts.is_subtask Filter to subtasks + * @param {module:model/String} opts.sort_by One of `due_date`, `created_at`, `completed_at`, `likes`, or `modified_at`, defaults to `modified_at` (default to <.>) + * @param {Boolean} opts.sort_ascending Default `false` (default to <.>) + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "searchTasksForWorkspaceWithHttpInfo", + value: function searchTasksForWorkspaceWithHttpInfo(workspace_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'workspace_gid' is set + if (workspace_gid === undefined || workspace_gid === null) { + throw new Error("Missing the required parameter 'workspace_gid' when calling searchTasksForWorkspace"); + } + var pathParams = { + 'workspace_gid': workspace_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + + // Checks if the user provided custom field query parameters and adds it to the request + for (var _i = 0, _Object$entries = Object.entries(opts); _i < _Object$entries.length; _i++) { + var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), + key = _Object$entries$_i[0], + value = _Object$entries$_i[1]; + var matchDotCase = /custom_fields\.(.*?)\..*/; + var matchSnakeCase = /custom_fields_(.*?)_.*/; + // If the provided custom fields query param key is in the following format: custom_fields.. (EX: custom_fields.123.is_set) + if (matchDotCase.test(key)) { + queryParams[key] = value; + // If the provided custom fields query param key is in the following format: custom_fields__ (EX: custom_fields_123_is_set) + } else if (matchSnakeCase.test(key)) { + var custom_field_gid = matchSnakeCase.exec(key)[1]; + var custom_field_query_param_key = key.replace("custom_fields_".concat(custom_field_gid, "_"), "custom_fields.".concat(custom_field_gid, ".")); + queryParams[custom_field_query_param_key] = value; + } + } + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/workspaces/{workspace_gid}/tasks/search', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/workspaces/{workspace_gid}/tasks/search', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/workspaces/{workspace_gid}/tasks/search', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Search tasks in a workspace + * To mirror the functionality of the Asana web app's advanced search feature, the Asana API has a task search endpoint that allows you to build complex filters to find and retrieve the exact data you need. #### Premium access Like the Asana web product's advance search feature, this search endpoint will only be available to premium Asana users. A user is premium if any of the following is true: - The workspace in which the search is being performed is a premium workspace - The user is a member of a premium team inside the workspace Even if a user is only a member of a premium team inside a non-premium workspace, search will allow them to find data anywhere in the workspace, not just inside the premium team. Making a search request using credentials of a non-premium user will result in a `402 Payment Required` error. #### Pagination Search results are not stable; repeating the same query multiple times may return the data in a different order, even if the data do not change. Because of this, the traditional [pagination](https://developers.asana.com/docs/#pagination) available elsewhere in the Asana API is not available here. However, you can paginate manually by sorting the search results by their creation time and then modifying each subsequent query to exclude data you have already seen. Page sizes are limited to a maximum of 100 items, and can be specified by the `limit` query parameter. #### Eventual consistency Changes in Asana (regardless of whether they’re made though the web product or the API) are forwarded to our search infrastructure to be indexed. This process can take between 10 and 60 seconds to complete under normal operation, and longer during some production incidents. Making a change to a task that would alter its presence in a particular search query will not be reflected immediately. This is also true of the advanced search feature in the web product. #### Rate limits You may receive a `429 Too Many Requests` response if you hit any of our [rate limits](https://developers.asana.com/docs/#rate-limits). #### Custom field parameters | Parameter name | Custom field type | Accepted type | |---|---|---| | custom_fields.{gid}.is_set | All | Boolean | | custom_fields.{gid}.value | Text | String | | custom_fields.{gid}.value | Number | Number | | custom_fields.{gid}.value | Enum | Enum option ID | | custom_fields.{gid}.starts_with | Text only | String | | custom_fields.{gid}.ends_with | Text only | String | | custom_fields.{gid}.contains | Text only | String | | custom_fields.{gid}.less_than | Number only | Number | | custom_fields.{gid}.greater_than | Number only | Number | For example, if the gid of the custom field is 12345, these query parameter to find tasks where it is set would be `custom_fields.12345.is_set=true`. To match an exact value for an enum custom field, use the gid of the desired enum option and not the name of the enum option: `custom_fields.12345.value=67890`. **Not Supported**: searching for multiple exact matches of a custom field, searching for multi-enum custom field *Note: If you specify `projects.any` and `sections.any`, you will receive tasks for the project **and** tasks for the section. If you're looking for only tasks in a section, omit the `projects.any` from the request.* + * @param {<&vendorExtensions.x-jsdoc-type>} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {String} opts.text Performs full-text search on both task name and description + * @param {module:model/String} opts.resource_subtype Filters results by the task's resource_subtype (default to <.>) + * @param {String} opts.assignee.any Comma-separated list of user identifiers + * @param {String} opts.assignee.not Comma-separated list of user identifiers + * @param {String} opts.portfolios.any Comma-separated list of portfolio IDs + * @param {String} opts.projects.any Comma-separated list of project IDs + * @param {String} opts.projects.not Comma-separated list of project IDs + * @param {String} opts.projects.all Comma-separated list of project IDs + * @param {String} opts.sections.any Comma-separated list of section or column IDs + * @param {String} opts.sections.not Comma-separated list of section or column IDs + * @param {String} opts.sections.all Comma-separated list of section or column IDs + * @param {String} opts.tags.any Comma-separated list of tag IDs + * @param {String} opts.tags.not Comma-separated list of tag IDs + * @param {String} opts.tags.all Comma-separated list of tag IDs + * @param {String} opts.teams.any Comma-separated list of team IDs + * @param {String} opts.followers.not Comma-separated list of user identifiers + * @param {String} opts.created_by.any Comma-separated list of user identifiers + * @param {String} opts.created_by.not Comma-separated list of user identifiers + * @param {String} opts.assigned_by.any Comma-separated list of user identifiers + * @param {String} opts.assigned_by.not Comma-separated list of user identifiers + * @param {String} opts.liked_by.not Comma-separated list of user identifiers + * @param {String} opts.commented_on_by.not Comma-separated list of user identifiers + * @param {Date} opts.due_on.before ISO 8601 date string + * @param {Date} opts.due_on.after ISO 8601 date string + * @param {Date} opts.due_on ISO 8601 date string or `null` + * @param {Date} opts.due_at.before ISO 8601 datetime string + * @param {Date} opts.due_at.after ISO 8601 datetime string + * @param {Date} opts.start_on.before ISO 8601 date string + * @param {Date} opts.start_on.after ISO 8601 date string + * @param {Date} opts.start_on ISO 8601 date string or `null` + * @param {Date} opts.created_on.before ISO 8601 date string + * @param {Date} opts.created_on.after ISO 8601 date string + * @param {Date} opts.created_on ISO 8601 date string or `null` + * @param {Date} opts.created_at.before ISO 8601 datetime string + * @param {Date} opts.created_at.after ISO 8601 datetime string + * @param {Date} opts.completed_on.before ISO 8601 date string + * @param {Date} opts.completed_on.after ISO 8601 date string + * @param {Date} opts.completed_on ISO 8601 date string or `null` + * @param {Date} opts.completed_at.before ISO 8601 datetime string + * @param {Date} opts.completed_at.after ISO 8601 datetime string + * @param {Date} opts.modified_on.before ISO 8601 date string + * @param {Date} opts.modified_on.after ISO 8601 date string + * @param {Date} opts.modified_on ISO 8601 date string or `null` + * @param {Date} opts.modified_at.before ISO 8601 datetime string + * @param {Date} opts.modified_at.after ISO 8601 datetime string + * @param {Boolean} opts.is_blocking Filter to incomplete tasks with dependents + * @param {Boolean} opts.is_blocked Filter to tasks with incomplete dependencies + * @param {Boolean} opts.has_attachment Filter to tasks with attachments + * @param {Boolean} opts.completed Filter to completed tasks + * @param {Boolean} opts.is_subtask Filter to subtasks + * @param {module:model/String} opts.sort_by One of `due_date`, `created_at`, `completed_at`, `likes`, or `modified_at`, defaults to `modified_at` (default to <.>) + * @param {Boolean} opts.sort_ascending Default `false` (default to <.>) + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TaskResponseArray} + */ + }, { + key: "searchTasksForWorkspace", + value: function searchTasksForWorkspace(workspace_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.searchTasksForWorkspaceWithHttpInfo(workspace_gid, opts); + } + return this.searchTasksForWorkspaceWithHttpInfo(workspace_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Set the parent of a task + * parent, or no parent task at all. Returns an empty data block. When using `insert_before` and `insert_after`, at most one of those two options can be specified, and they must already be subtasks of the parent. + * @param {module:model/Object} body The new parent of the subtask. + * @param {String} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "setParentForTaskWithHttpInfo", + value: function setParentForTaskWithHttpInfo(body, task_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling setParentForTask"); + } + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling setParentForTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tasks/{task_gid}/setParent', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Set the parent of a task + * parent, or no parent task at all. Returns an empty data block. When using `insert_before` and `insert_after`, at most one of those two options can be specified, and they must already be subtasks of the parent. + * @param {<&vendorExtensions.x-jsdoc-type>} body The new parent of the subtask. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TaskResponseData} + */ + }, { + key: "setParentForTask", + value: function setParentForTask(body, task_gid, opts) { + return this.setParentForTaskWithHttpInfo(body, task_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Update a task + * A specific, existing task can be updated by making a PUT request on the URL for that task. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the task. Returns the complete updated task record. + * @param {module:model/Object} body The task to update. + * @param {String} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "updateTaskWithHttpInfo", + value: function updateTaskWithHttpInfo(body, task_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling updateTask"); + } + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling updateTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tasks/{task_gid}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Update a task + * A specific, existing task can be updated by making a PUT request on the URL for that task. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the task. Returns the complete updated task record. + * @param {<&vendorExtensions.x-jsdoc-type>} body The task to update. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TaskResponseData} + */ + }, { + key: "updateTask", + value: function updateTask(body, task_gid, opts) { + return this.updateTaskWithHttpInfo(body, task_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/TeamMembershipsApi.js b/node_modules/asana/dist/api/TeamMembershipsApi.js new file mode 100644 index 000000000..f3344694c --- /dev/null +++ b/node_modules/asana/dist/api/TeamMembershipsApi.js @@ -0,0 +1,317 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TeamMembershipsApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* TeamMemberships service. +* @module api/TeamMembershipsApi +* @version 3.0.3 +*/ +var TeamMembershipsApi = exports.TeamMembershipsApi = /*#__PURE__*/function () { + /** + * Constructs a new TeamMembershipsApi. + * @alias module:api/TeamMembershipsApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function TeamMembershipsApi(apiClient) { + _classCallCheck(this, TeamMembershipsApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Get a team membership + * Returns the complete team membership record for a single team membership. + * @param {String} team_membership_gid + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(TeamMembershipsApi, [{ + key: "getTeamMembershipWithHttpInfo", + value: function getTeamMembershipWithHttpInfo(team_membership_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'team_membership_gid' is set + if (team_membership_gid === undefined || team_membership_gid === null) { + throw new Error("Missing the required parameter 'team_membership_gid' when calling getTeamMembership"); + } + var pathParams = { + 'team_membership_gid': team_membership_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/team_memberships/{team_membership_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a team membership + * Returns the complete team membership record for a single team membership. + * @param {<&vendorExtensions.x-jsdoc-type>} team_membership_gid + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TeamMembershipResponseData} + */ + }, { + key: "getTeamMembership", + value: function getTeamMembership(team_membership_gid, opts) { + return this.getTeamMembershipWithHttpInfo(team_membership_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get team memberships + * Returns compact team membership records. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {String} opts.team Globally unique identifier for the team. + * @param {String} opts.user A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. This parameter must be used with the workspace parameter. + * @param {String} opts.workspace Globally unique identifier for the workspace. This parameter must be used with the user parameter. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTeamMembershipsWithHttpInfo", + value: function getTeamMembershipsWithHttpInfo(opts) { + opts = opts || {}; + var postBody = null; + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/team_memberships', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/team_memberships', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/team_memberships', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get team memberships + * Returns compact team membership records. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {String} opts.team Globally unique identifier for the team. + * @param {String} opts.user A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. This parameter must be used with the workspace parameter. + * @param {String} opts.workspace Globally unique identifier for the workspace. This parameter must be used with the user parameter. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TeamMembershipResponseArray} + */ + }, { + key: "getTeamMemberships", + value: function getTeamMemberships(opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getTeamMembershipsWithHttpInfo(opts); + } + return this.getTeamMembershipsWithHttpInfo(opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get memberships from a team + * Returns the compact team memberships for the team. + * @param {String} team_gid Globally unique identifier for the team. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTeamMembershipsForTeamWithHttpInfo", + value: function getTeamMembershipsForTeamWithHttpInfo(team_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'team_gid' is set + if (team_gid === undefined || team_gid === null) { + throw new Error("Missing the required parameter 'team_gid' when calling getTeamMembershipsForTeam"); + } + var pathParams = { + 'team_gid': team_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/teams/{team_gid}/team_memberships', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/teams/{team_gid}/team_memberships', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/teams/{team_gid}/team_memberships', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get memberships from a team + * Returns the compact team memberships for the team. + * @param {<&vendorExtensions.x-jsdoc-type>} team_gid Globally unique identifier for the team. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TeamMembershipResponseArray} + */ + }, { + key: "getTeamMembershipsForTeam", + value: function getTeamMembershipsForTeam(team_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getTeamMembershipsForTeamWithHttpInfo(team_gid, opts); + } + return this.getTeamMembershipsForTeamWithHttpInfo(team_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get memberships from a user + * Returns the compact team membership records for the user. + * @param {String} user_gid A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. + * @param {String} workspace Globally unique identifier for the workspace. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTeamMembershipsForUserWithHttpInfo", + value: function getTeamMembershipsForUserWithHttpInfo(user_gid, workspace, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'user_gid' is set + if (user_gid === undefined || user_gid === null) { + throw new Error("Missing the required parameter 'user_gid' when calling getTeamMembershipsForUser"); + } + // verify the required parameter 'workspace' is set + if (workspace === undefined || workspace === null) { + throw new Error("Missing the required parameter 'workspace' when calling getTeamMembershipsForUser"); + } + var pathParams = { + 'user_gid': user_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + queryParams['workspace'] = workspace; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/users/{user_gid}/team_memberships', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/users/{user_gid}/team_memberships', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/users/{user_gid}/team_memberships', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get memberships from a user + * Returns the compact team membership records for the user. + * @param {<&vendorExtensions.x-jsdoc-type>} user_gid A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. + * @param {<&vendorExtensions.x-jsdoc-type>} workspace Globally unique identifier for the workspace. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TeamMembershipResponseArray} + */ + }, { + key: "getTeamMembershipsForUser", + value: function getTeamMembershipsForUser(user_gid, workspace, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getTeamMembershipsForUserWithHttpInfo(user_gid, workspace, opts); + } + return this.getTeamMembershipsForUserWithHttpInfo(user_gid, workspace, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/TeamsApi.js b/node_modules/asana/dist/api/TeamsApi.js new file mode 100644 index 000000000..ba236db32 --- /dev/null +++ b/node_modules/asana/dist/api/TeamsApi.js @@ -0,0 +1,448 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TeamsApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* Teams service. +* @module api/TeamsApi +* @version 3.0.3 +*/ +var TeamsApi = exports.TeamsApi = /*#__PURE__*/function () { + /** + * Constructs a new TeamsApi. + * @alias module:api/TeamsApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function TeamsApi(apiClient) { + _classCallCheck(this, TeamsApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Add a user to a team + * The user making this call must be a member of the team in order to add others. The user being added must exist in the same organization as the team. Returns the complete team membership record for the newly added user. + * @param {module:model/Object} body The user to add to the team. + * @param {String} team_gid Globally unique identifier for the team. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(TeamsApi, [{ + key: "addUserForTeamWithHttpInfo", + value: function addUserForTeamWithHttpInfo(body, team_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling addUserForTeam"); + } + // verify the required parameter 'team_gid' is set + if (team_gid === undefined || team_gid === null) { + throw new Error("Missing the required parameter 'team_gid' when calling addUserForTeam"); + } + var pathParams = { + 'team_gid': team_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/teams/{team_gid}/addUser', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Add a user to a team + * The user making this call must be a member of the team in order to add others. The user being added must exist in the same organization as the team. Returns the complete team membership record for the newly added user. + * @param {<&vendorExtensions.x-jsdoc-type>} body The user to add to the team. + * @param {<&vendorExtensions.x-jsdoc-type>} team_gid Globally unique identifier for the team. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TeamMembershipResponseData} + */ + }, { + key: "addUserForTeam", + value: function addUserForTeam(body, team_gid, opts) { + return this.addUserForTeamWithHttpInfo(body, team_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Create a team + * Creates a team within the current workspace. + * @param {module:model/Object} body The team to create. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "createTeamWithHttpInfo", + value: function createTeamWithHttpInfo(body, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling createTeam"); + } + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/teams', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create a team + * Creates a team within the current workspace. + * @param {<&vendorExtensions.x-jsdoc-type>} body The team to create. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TeamResponseData} + */ + }, { + key: "createTeam", + value: function createTeam(body, opts) { + return this.createTeamWithHttpInfo(body, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a team + * Returns the full record for a single team. + * @param {String} team_gid Globally unique identifier for the team. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTeamWithHttpInfo", + value: function getTeamWithHttpInfo(team_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'team_gid' is set + if (team_gid === undefined || team_gid === null) { + throw new Error("Missing the required parameter 'team_gid' when calling getTeam"); + } + var pathParams = { + 'team_gid': team_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/teams/{team_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a team + * Returns the full record for a single team. + * @param {<&vendorExtensions.x-jsdoc-type>} team_gid Globally unique identifier for the team. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TeamResponseData} + */ + }, { + key: "getTeam", + value: function getTeam(team_gid, opts) { + return this.getTeamWithHttpInfo(team_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get teams for a user + * Returns the compact records for all teams to which the given user is assigned. + * @param {String} user_gid A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. + * @param {String} organization The workspace or organization to filter teams on. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTeamsForUserWithHttpInfo", + value: function getTeamsForUserWithHttpInfo(user_gid, organization, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'user_gid' is set + if (user_gid === undefined || user_gid === null) { + throw new Error("Missing the required parameter 'user_gid' when calling getTeamsForUser"); + } + // verify the required parameter 'organization' is set + if (organization === undefined || organization === null) { + throw new Error("Missing the required parameter 'organization' when calling getTeamsForUser"); + } + var pathParams = { + 'user_gid': user_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + queryParams['organization'] = organization; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/users/{user_gid}/teams', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/users/{user_gid}/teams', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/users/{user_gid}/teams', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get teams for a user + * Returns the compact records for all teams to which the given user is assigned. + * @param {<&vendorExtensions.x-jsdoc-type>} user_gid A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. + * @param {<&vendorExtensions.x-jsdoc-type>} organization The workspace or organization to filter teams on. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TeamResponseArray} + */ + }, { + key: "getTeamsForUser", + value: function getTeamsForUser(user_gid, organization, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getTeamsForUserWithHttpInfo(user_gid, organization, opts); + } + return this.getTeamsForUserWithHttpInfo(user_gid, organization, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get teams in a workspace + * Returns the compact records for all teams in the workspace visible to the authorized user. + * @param {String} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTeamsForWorkspaceWithHttpInfo", + value: function getTeamsForWorkspaceWithHttpInfo(workspace_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'workspace_gid' is set + if (workspace_gid === undefined || workspace_gid === null) { + throw new Error("Missing the required parameter 'workspace_gid' when calling getTeamsForWorkspace"); + } + var pathParams = { + 'workspace_gid': workspace_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/workspaces/{workspace_gid}/teams', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/workspaces/{workspace_gid}/teams', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/workspaces/{workspace_gid}/teams', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get teams in a workspace + * Returns the compact records for all teams in the workspace visible to the authorized user. + * @param {<&vendorExtensions.x-jsdoc-type>} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TeamResponseArray} + */ + }, { + key: "getTeamsForWorkspace", + value: function getTeamsForWorkspace(workspace_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getTeamsForWorkspaceWithHttpInfo(workspace_gid, opts); + } + return this.getTeamsForWorkspaceWithHttpInfo(workspace_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Remove a user from a team + * The user making this call must be a member of the team in order to remove themselves or others. + * @param {module:model/Object} body The user to remove from the team. + * @param {String} team_gid Globally unique identifier for the team. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "removeUserForTeamWithHttpInfo", + value: function removeUserForTeamWithHttpInfo(body, team_gid) { + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling removeUserForTeam"); + } + // verify the required parameter 'team_gid' is set + if (team_gid === undefined || team_gid === null) { + throw new Error("Missing the required parameter 'team_gid' when calling removeUserForTeam"); + } + var pathParams = { + 'team_gid': team_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/teams/{team_gid}/removeUser', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Remove a user from a team + * The user making this call must be a member of the team in order to remove themselves or others. + * @param {<&vendorExtensions.x-jsdoc-type>} body The user to remove from the team. + * @param {<&vendorExtensions.x-jsdoc-type>} team_gid Globally unique identifier for the team. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "removeUserForTeam", + value: function removeUserForTeam(body, team_gid) { + return this.removeUserForTeamWithHttpInfo(body, team_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Update a team + * Updates a team within the current workspace. + * @param {module:model/Object} body The team to update. + * @param {String} team_gid Globally unique identifier for the team. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "updateTeamWithHttpInfo", + value: function updateTeamWithHttpInfo(body, team_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling updateTeam"); + } + // verify the required parameter 'team_gid' is set + if (team_gid === undefined || team_gid === null) { + throw new Error("Missing the required parameter 'team_gid' when calling updateTeam"); + } + var pathParams = { + 'team_gid': team_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/teams/{team_gid}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Update a team + * Updates a team within the current workspace. + * @param {<&vendorExtensions.x-jsdoc-type>} body The team to update. + * @param {<&vendorExtensions.x-jsdoc-type>} team_gid Globally unique identifier for the team. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TeamResponseData} + */ + }, { + key: "updateTeam", + value: function updateTeam(body, team_gid, opts) { + return this.updateTeamWithHttpInfo(body, team_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/TimePeriodsApi.js b/node_modules/asana/dist/api/TimePeriodsApi.js new file mode 100644 index 000000000..748ebea07 --- /dev/null +++ b/node_modules/asana/dist/api/TimePeriodsApi.js @@ -0,0 +1,171 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TimePeriodsApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* TimePeriods service. +* @module api/TimePeriodsApi +* @version 3.0.3 +*/ +var TimePeriodsApi = exports.TimePeriodsApi = /*#__PURE__*/function () { + /** + * Constructs a new TimePeriodsApi. + * @alias module:api/TimePeriodsApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function TimePeriodsApi(apiClient) { + _classCallCheck(this, TimePeriodsApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Get a time period + * Returns the full record for a single time period. + * @param {String} time_period_gid Globally unique identifier for the time period. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(TimePeriodsApi, [{ + key: "getTimePeriodWithHttpInfo", + value: function getTimePeriodWithHttpInfo(time_period_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'time_period_gid' is set + if (time_period_gid === undefined || time_period_gid === null) { + throw new Error("Missing the required parameter 'time_period_gid' when calling getTimePeriod"); + } + var pathParams = { + 'time_period_gid': time_period_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/time_periods/{time_period_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a time period + * Returns the full record for a single time period. + * @param {<&vendorExtensions.x-jsdoc-type>} time_period_gid Globally unique identifier for the time period. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TimePeriodResponseData} + */ + }, { + key: "getTimePeriod", + value: function getTimePeriod(time_period_gid, opts) { + return this.getTimePeriodWithHttpInfo(time_period_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get time periods + * Returns compact time period records. + * @param {String} workspace Globally unique identifier for the workspace. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Date} opts.start_on ISO 8601 date string + * @param {Date} opts.end_on ISO 8601 date string + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTimePeriodsWithHttpInfo", + value: function getTimePeriodsWithHttpInfo(workspace, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'workspace' is set + if (workspace === undefined || workspace === null) { + throw new Error("Missing the required parameter 'workspace' when calling getTimePeriods"); + } + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + queryParams['workspace'] = workspace; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/time_periods', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/time_periods', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/time_periods', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get time periods + * Returns compact time period records. + * @param {<&vendorExtensions.x-jsdoc-type>} workspace Globally unique identifier for the workspace. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Date} opts.start_on ISO 8601 date string + * @param {Date} opts.end_on ISO 8601 date string + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TimePeriodResponseArray} + */ + }, { + key: "getTimePeriods", + value: function getTimePeriods(workspace, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getTimePeriodsWithHttpInfo(workspace, opts); + } + return this.getTimePeriodsWithHttpInfo(workspace, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/TimeTrackingEntriesApi.js b/node_modules/asana/dist/api/TimeTrackingEntriesApi.js new file mode 100644 index 000000000..11b85275a --- /dev/null +++ b/node_modules/asana/dist/api/TimeTrackingEntriesApi.js @@ -0,0 +1,317 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TimeTrackingEntriesApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* TimeTrackingEntries service. +* @module api/TimeTrackingEntriesApi +* @version 3.0.3 +*/ +var TimeTrackingEntriesApi = exports.TimeTrackingEntriesApi = /*#__PURE__*/function () { + /** + * Constructs a new TimeTrackingEntriesApi. + * @alias module:api/TimeTrackingEntriesApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function TimeTrackingEntriesApi(apiClient) { + _classCallCheck(this, TimeTrackingEntriesApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Create a time tracking entry + * Creates a time tracking entry on a given task. Returns the record of the newly created time tracking entry. + * @param {module:model/Object} body Information about the time tracking entry. + * @param {String} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(TimeTrackingEntriesApi, [{ + key: "createTimeTrackingEntryWithHttpInfo", + value: function createTimeTrackingEntryWithHttpInfo(body, task_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling createTimeTrackingEntry"); + } + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling createTimeTrackingEntry"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/tasks/{task_gid}/time_tracking_entries', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Create a time tracking entry + * Creates a time tracking entry on a given task. Returns the record of the newly created time tracking entry. + * @param {<&vendorExtensions.x-jsdoc-type>} body Information about the time tracking entry. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TimeTrackingEntryBaseData} + */ + }, { + key: "createTimeTrackingEntry", + value: function createTimeTrackingEntry(body, task_gid, opts) { + return this.createTimeTrackingEntryWithHttpInfo(body, task_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Delete a time tracking entry + * A specific, existing time tracking entry can be deleted by making a `DELETE` request on the URL for that time tracking entry. Returns an empty data record. + * @param {String} time_tracking_entry_gid Globally unique identifier for the time tracking entry. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "deleteTimeTrackingEntryWithHttpInfo", + value: function deleteTimeTrackingEntryWithHttpInfo(time_tracking_entry_gid) { + var postBody = null; + // verify the required parameter 'time_tracking_entry_gid' is set + if (time_tracking_entry_gid === undefined || time_tracking_entry_gid === null) { + throw new Error("Missing the required parameter 'time_tracking_entry_gid' when calling deleteTimeTrackingEntry"); + } + var pathParams = { + 'time_tracking_entry_gid': time_tracking_entry_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/time_tracking_entries/{time_tracking_entry_gid}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Delete a time tracking entry + * A specific, existing time tracking entry can be deleted by making a `DELETE` request on the URL for that time tracking entry. Returns an empty data record. + * @param {<&vendorExtensions.x-jsdoc-type>} time_tracking_entry_gid Globally unique identifier for the time tracking entry. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "deleteTimeTrackingEntry", + value: function deleteTimeTrackingEntry(time_tracking_entry_gid) { + return this.deleteTimeTrackingEntryWithHttpInfo(time_tracking_entry_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get time tracking entries for a task + * Returns time tracking entries for a given task. + * @param {String} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTimeTrackingEntriesForTaskWithHttpInfo", + value: function getTimeTrackingEntriesForTaskWithHttpInfo(task_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'task_gid' is set + if (task_gid === undefined || task_gid === null) { + throw new Error("Missing the required parameter 'task_gid' when calling getTimeTrackingEntriesForTask"); + } + var pathParams = { + 'task_gid': task_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/tasks/{task_gid}/time_tracking_entries', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/tasks/{task_gid}/time_tracking_entries', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/tasks/{task_gid}/time_tracking_entries', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get time tracking entries for a task + * Returns time tracking entries for a given task. + * @param {<&vendorExtensions.x-jsdoc-type>} task_gid The task to operate on. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TimeTrackingEntryCompactArray} + */ + }, { + key: "getTimeTrackingEntriesForTask", + value: function getTimeTrackingEntriesForTask(task_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getTimeTrackingEntriesForTaskWithHttpInfo(task_gid, opts); + } + return this.getTimeTrackingEntriesForTaskWithHttpInfo(task_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a time tracking entry + * Returns the complete time tracking entry record for a single time tracking entry. + * @param {String} time_tracking_entry_gid Globally unique identifier for the time tracking entry. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getTimeTrackingEntryWithHttpInfo", + value: function getTimeTrackingEntryWithHttpInfo(time_tracking_entry_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'time_tracking_entry_gid' is set + if (time_tracking_entry_gid === undefined || time_tracking_entry_gid === null) { + throw new Error("Missing the required parameter 'time_tracking_entry_gid' when calling getTimeTrackingEntry"); + } + var pathParams = { + 'time_tracking_entry_gid': time_tracking_entry_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/time_tracking_entries/{time_tracking_entry_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a time tracking entry + * Returns the complete time tracking entry record for a single time tracking entry. + * @param {<&vendorExtensions.x-jsdoc-type>} time_tracking_entry_gid Globally unique identifier for the time tracking entry. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TimeTrackingEntryBaseData} + */ + }, { + key: "getTimeTrackingEntry", + value: function getTimeTrackingEntry(time_tracking_entry_gid, opts) { + return this.getTimeTrackingEntryWithHttpInfo(time_tracking_entry_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Update a time tracking entry + * A specific, existing time tracking entry can be updated by making a `PUT` request on the URL for that time tracking entry. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the task. Returns the complete updated time tracking entry record. + * @param {module:model/Object} body The updated fields for the time tracking entry. + * @param {String} time_tracking_entry_gid Globally unique identifier for the time tracking entry. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "updateTimeTrackingEntryWithHttpInfo", + value: function updateTimeTrackingEntryWithHttpInfo(body, time_tracking_entry_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling updateTimeTrackingEntry"); + } + // verify the required parameter 'time_tracking_entry_gid' is set + if (time_tracking_entry_gid === undefined || time_tracking_entry_gid === null) { + throw new Error("Missing the required parameter 'time_tracking_entry_gid' when calling updateTimeTrackingEntry"); + } + var pathParams = { + 'time_tracking_entry_gid': time_tracking_entry_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/time_tracking_entries/{time_tracking_entry_gid}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Update a time tracking entry + * A specific, existing time tracking entry can be updated by making a `PUT` request on the URL for that time tracking entry. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the task. Returns the complete updated time tracking entry record. + * @param {<&vendorExtensions.x-jsdoc-type>} body The updated fields for the time tracking entry. + * @param {<&vendorExtensions.x-jsdoc-type>} time_tracking_entry_gid Globally unique identifier for the time tracking entry. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/TimeTrackingEntryBaseData} + */ + }, { + key: "updateTimeTrackingEntry", + value: function updateTimeTrackingEntry(body, time_tracking_entry_gid, opts) { + return this.updateTimeTrackingEntryWithHttpInfo(body, time_tracking_entry_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/TypeaheadApi.js b/node_modules/asana/dist/api/TypeaheadApi.js new file mode 100644 index 000000000..4eb3f41c0 --- /dev/null +++ b/node_modules/asana/dist/api/TypeaheadApi.js @@ -0,0 +1,129 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TypeaheadApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* Typeahead service. +* @module api/TypeaheadApi +* @version 3.0.3 +*/ +var TypeaheadApi = exports.TypeaheadApi = /*#__PURE__*/function () { + /** + * Constructs a new TypeaheadApi. + * @alias module:api/TypeaheadApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function TypeaheadApi(apiClient) { + _classCallCheck(this, TypeaheadApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Get objects via typeahead + * Retrieves objects in the workspace based via an auto-completion/typeahead search algorithm. This feature is meant to provide results quickly, so do not rely on this API to provide extremely accurate search results. The result set is limited to a single page of results with a maximum size, so you won’t be able to fetch large numbers of results. The typeahead search API provides search for objects from a single workspace. This endpoint should be used to query for objects when creating an auto-completion/typeahead search feature. This API is meant to provide results quickly and should not be relied upon for accurate or exhaustive search results. The results sets are limited in size and cannot be paginated. Queries return a compact representation of each object which is typically the gid and name fields. Interested in a specific set of fields or all of the fields?! Of course you are. Use field selectors to manipulate what data is included in a response. Resources with type `user` are returned in order of most contacted to least contacted. This is determined by task assignments, adding the user to projects, and adding the user as a follower to tasks, messages, etc. Resources with type `project` are returned in order of recency. This is determined when the user visits the project, is added to the project, and completes tasks in the project. Resources with type `task` are returned with priority placed on tasks the user is following, but no guarantee on the order of those tasks. Resources with type `project_template` are returned with priority placed on favorited project templates. Leaving the `query` string empty or omitted will give you results, still following the resource ordering above. This could be used to list users or projects that are relevant for the requesting user's api token. + * @param {String} workspace_gid Globally unique identifier for the workspace or organization. + * @param {module:model/String} resource_type The type of values the typeahead should return. You can choose from one of the following: `custom_field`, `goal`, `project`, `project_template`, `portfolio`, `tag`, `task`, `team`, and `user`. Note that unlike in the names of endpoints, the types listed here are in singular form (e.g. `task`). Using multiple types is not yet supported. + * @param {Object} opts Optional parameters + * @param {module:model/String} opts.type *Deprecated: new integrations should prefer the resource_type field.* (default to <.>) + * @param {String} opts.query The string that will be used to search for relevant objects. If an empty string is passed in, the API will return results. + * @param {Number} opts.count The number of results to return. The default is 20 if this parameter is omitted, with a minimum of 1 and a maximum of 100. If there are fewer results found than requested, all will be returned. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(TypeaheadApi, [{ + key: "typeaheadForWorkspaceWithHttpInfo", + value: function typeaheadForWorkspaceWithHttpInfo(workspace_gid, resource_type, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'workspace_gid' is set + if (workspace_gid === undefined || workspace_gid === null) { + throw new Error("Missing the required parameter 'workspace_gid' when calling typeaheadForWorkspace"); + } + // verify the required parameter 'resource_type' is set + if (resource_type === undefined || resource_type === null) { + throw new Error("Missing the required parameter 'resource_type' when calling typeaheadForWorkspace"); + } + var pathParams = { + 'workspace_gid': workspace_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + queryParams['resource_type'] = resource_type; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/workspaces/{workspace_gid}/typeahead', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/workspaces/{workspace_gid}/typeahead', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/workspaces/{workspace_gid}/typeahead', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get objects via typeahead + * Retrieves objects in the workspace based via an auto-completion/typeahead search algorithm. This feature is meant to provide results quickly, so do not rely on this API to provide extremely accurate search results. The result set is limited to a single page of results with a maximum size, so you won’t be able to fetch large numbers of results. The typeahead search API provides search for objects from a single workspace. This endpoint should be used to query for objects when creating an auto-completion/typeahead search feature. This API is meant to provide results quickly and should not be relied upon for accurate or exhaustive search results. The results sets are limited in size and cannot be paginated. Queries return a compact representation of each object which is typically the gid and name fields. Interested in a specific set of fields or all of the fields?! Of course you are. Use field selectors to manipulate what data is included in a response. Resources with type `user` are returned in order of most contacted to least contacted. This is determined by task assignments, adding the user to projects, and adding the user as a follower to tasks, messages, etc. Resources with type `project` are returned in order of recency. This is determined when the user visits the project, is added to the project, and completes tasks in the project. Resources with type `task` are returned with priority placed on tasks the user is following, but no guarantee on the order of those tasks. Resources with type `project_template` are returned with priority placed on favorited project templates. Leaving the `query` string empty or omitted will give you results, still following the resource ordering above. This could be used to list users or projects that are relevant for the requesting user's api token. + * @param {<&vendorExtensions.x-jsdoc-type>} workspace_gid Globally unique identifier for the workspace or organization. + * @param {<&vendorExtensions.x-jsdoc-type>} resource_type The type of values the typeahead should return. You can choose from one of the following: `custom_field`, `goal`, `project`, `project_template`, `portfolio`, `tag`, `task`, `team`, and `user`. Note that unlike in the names of endpoints, the types listed here are in singular form (e.g. `task`). Using multiple types is not yet supported. + * @param {Object} opts Optional parameters + * @param {module:model/String} opts.type *Deprecated: new integrations should prefer the resource_type field.* (default to <.>) + * @param {String} opts.query The string that will be used to search for relevant objects. If an empty string is passed in, the API will return results. + * @param {Number} opts.count The number of results to return. The default is 20 if this parameter is omitted, with a minimum of 1 and a maximum of 100. If there are fewer results found than requested, all will be returned. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/AsanaNamedResourceArray} + */ + }, { + key: "typeaheadForWorkspace", + value: function typeaheadForWorkspace(workspace_gid, resource_type, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.typeaheadForWorkspaceWithHttpInfo(workspace_gid, resource_type, opts); + } + return this.typeaheadForWorkspaceWithHttpInfo(workspace_gid, resource_type, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/UserTaskListsApi.js b/node_modules/asana/dist/api/UserTaskListsApi.js new file mode 100644 index 000000000..f61124177 --- /dev/null +++ b/node_modules/asana/dist/api/UserTaskListsApi.js @@ -0,0 +1,151 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.UserTaskListsApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* UserTaskLists service. +* @module api/UserTaskListsApi +* @version 3.0.3 +*/ +var UserTaskListsApi = exports.UserTaskListsApi = /*#__PURE__*/function () { + /** + * Constructs a new UserTaskListsApi. + * @alias module:api/UserTaskListsApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function UserTaskListsApi(apiClient) { + _classCallCheck(this, UserTaskListsApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Get a user task list + * Returns the full record for a user task list. + * @param {String} user_task_list_gid Globally unique identifier for the user task list. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(UserTaskListsApi, [{ + key: "getUserTaskListWithHttpInfo", + value: function getUserTaskListWithHttpInfo(user_task_list_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'user_task_list_gid' is set + if (user_task_list_gid === undefined || user_task_list_gid === null) { + throw new Error("Missing the required parameter 'user_task_list_gid' when calling getUserTaskList"); + } + var pathParams = { + 'user_task_list_gid': user_task_list_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/user_task_lists/{user_task_list_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a user task list + * Returns the full record for a user task list. + * @param {<&vendorExtensions.x-jsdoc-type>} user_task_list_gid Globally unique identifier for the user task list. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/UserTaskListResponseData} + */ + }, { + key: "getUserTaskList", + value: function getUserTaskList(user_task_list_gid, opts) { + return this.getUserTaskListWithHttpInfo(user_task_list_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a user's task list + * Returns the full record for a user's task list. + * @param {String} user_gid A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. + * @param {String} workspace The workspace in which to get the user task list. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getUserTaskListForUserWithHttpInfo", + value: function getUserTaskListForUserWithHttpInfo(user_gid, workspace, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'user_gid' is set + if (user_gid === undefined || user_gid === null) { + throw new Error("Missing the required parameter 'user_gid' when calling getUserTaskListForUser"); + } + // verify the required parameter 'workspace' is set + if (workspace === undefined || workspace === null) { + throw new Error("Missing the required parameter 'workspace' when calling getUserTaskListForUser"); + } + var pathParams = { + 'user_gid': user_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + queryParams['workspace'] = workspace; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/users/{user_gid}/user_task_list', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a user's task list + * Returns the full record for a user's task list. + * @param {<&vendorExtensions.x-jsdoc-type>} user_gid A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. + * @param {<&vendorExtensions.x-jsdoc-type>} workspace The workspace in which to get the user task list. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/UserTaskListResponseData} + */ + }, { + key: "getUserTaskListForUser", + value: function getUserTaskListForUser(user_gid, workspace, opts) { + return this.getUserTaskListForUserWithHttpInfo(user_gid, workspace, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/UsersApi.js b/node_modules/asana/dist/api/UsersApi.js new file mode 100644 index 000000000..dc12c99ed --- /dev/null +++ b/node_modules/asana/dist/api/UsersApi.js @@ -0,0 +1,390 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.UsersApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* Users service. +* @module api/UsersApi +* @version 3.0.3 +*/ +var UsersApi = exports.UsersApi = /*#__PURE__*/function () { + /** + * Constructs a new UsersApi. + * @alias module:api/UsersApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function UsersApi(apiClient) { + _classCallCheck(this, UsersApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Get a user's favorites + * Returns all of a user's favorites in the given workspace, of the given type. Results are given in order (The same order as Asana's sidebar). + * @param {String} user_gid A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. + * @param {module:model/String} resource_type The resource type of favorites to be returned. + * @param {String} workspace The workspace in which to get favorites. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(UsersApi, [{ + key: "getFavoritesForUserWithHttpInfo", + value: function getFavoritesForUserWithHttpInfo(user_gid, resource_type, workspace, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'user_gid' is set + if (user_gid === undefined || user_gid === null) { + throw new Error("Missing the required parameter 'user_gid' when calling getFavoritesForUser"); + } + // verify the required parameter 'resource_type' is set + if (resource_type === undefined || resource_type === null) { + throw new Error("Missing the required parameter 'resource_type' when calling getFavoritesForUser"); + } + // verify the required parameter 'workspace' is set + if (workspace === undefined || workspace === null) { + throw new Error("Missing the required parameter 'workspace' when calling getFavoritesForUser"); + } + var pathParams = { + 'user_gid': user_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + queryParams['resource_type'] = resource_type; + queryParams['workspace'] = workspace; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/users/{user_gid}/favorites', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/users/{user_gid}/favorites', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/users/{user_gid}/favorites', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a user's favorites + * Returns all of a user's favorites in the given workspace, of the given type. Results are given in order (The same order as Asana's sidebar). + * @param {<&vendorExtensions.x-jsdoc-type>} user_gid A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. + * @param {<&vendorExtensions.x-jsdoc-type>} resource_type The resource type of favorites to be returned. + * @param {<&vendorExtensions.x-jsdoc-type>} workspace The workspace in which to get favorites. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/AsanaNamedResourceArray} + */ + }, { + key: "getFavoritesForUser", + value: function getFavoritesForUser(user_gid, resource_type, workspace, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getFavoritesForUserWithHttpInfo(user_gid, resource_type, workspace, opts); + } + return this.getFavoritesForUserWithHttpInfo(user_gid, resource_type, workspace, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a user + * Returns the full user record for the single user with the provided ID. + * @param {String} user_gid A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getUserWithHttpInfo", + value: function getUserWithHttpInfo(user_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'user_gid' is set + if (user_gid === undefined || user_gid === null) { + throw new Error("Missing the required parameter 'user_gid' when calling getUser"); + } + var pathParams = { + 'user_gid': user_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/users/{user_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a user + * Returns the full user record for the single user with the provided ID. + * @param {<&vendorExtensions.x-jsdoc-type>} user_gid A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/UserResponseData} + */ + }, { + key: "getUser", + value: function getUser(user_gid, opts) { + return this.getUserWithHttpInfo(user_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get multiple users + * Returns the user records for all users in all workspaces and organizations accessible to the authenticated user. Accepts an optional workspace ID parameter. Results are sorted by user ID. + * @param {Object} opts Optional parameters + * @param {String} opts.workspace The workspace or organization ID to filter users on. + * @param {String} opts.team The team ID to filter users on. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getUsersWithHttpInfo", + value: function getUsersWithHttpInfo(opts) { + opts = opts || {}; + var postBody = null; + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/users', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/users', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/users', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get multiple users + * Returns the user records for all users in all workspaces and organizations accessible to the authenticated user. Accepts an optional workspace ID parameter. Results are sorted by user ID. + * @param {Object} opts Optional parameters + * @param {String} opts.workspace The workspace or organization ID to filter users on. + * @param {String} opts.team The team ID to filter users on. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/UserResponseArray} + */ + }, { + key: "getUsers", + value: function getUsers(opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getUsersWithHttpInfo(opts); + } + return this.getUsersWithHttpInfo(opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get users in a team + * Returns the compact records for all users that are members of the team. Results are sorted alphabetically and limited to 2000. For more results use the `/users` endpoint. + * @param {String} team_gid Globally unique identifier for the team. + * @param {Object} opts Optional parameters + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getUsersForTeamWithHttpInfo", + value: function getUsersForTeamWithHttpInfo(team_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'team_gid' is set + if (team_gid === undefined || team_gid === null) { + throw new Error("Missing the required parameter 'team_gid' when calling getUsersForTeam"); + } + var pathParams = { + 'team_gid': team_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/teams/{team_gid}/users', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/teams/{team_gid}/users', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/teams/{team_gid}/users', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get users in a team + * Returns the compact records for all users that are members of the team. Results are sorted alphabetically and limited to 2000. For more results use the `/users` endpoint. + * @param {<&vendorExtensions.x-jsdoc-type>} team_gid Globally unique identifier for the team. + * @param {Object} opts Optional parameters + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/UserResponseArray} + */ + }, { + key: "getUsersForTeam", + value: function getUsersForTeam(team_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getUsersForTeamWithHttpInfo(team_gid, opts); + } + return this.getUsersForTeamWithHttpInfo(team_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get users in a workspace or organization + * Returns the compact records for all users in the specified workspace or organization. Results are sorted alphabetically and limited to 2000. For more results use the `/users` endpoint. + * @param {String} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getUsersForWorkspaceWithHttpInfo", + value: function getUsersForWorkspaceWithHttpInfo(workspace_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'workspace_gid' is set + if (workspace_gid === undefined || workspace_gid === null) { + throw new Error("Missing the required parameter 'workspace_gid' when calling getUsersForWorkspace"); + } + var pathParams = { + 'workspace_gid': workspace_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/workspaces/{workspace_gid}/users', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/workspaces/{workspace_gid}/users', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/workspaces/{workspace_gid}/users', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get users in a workspace or organization + * Returns the compact records for all users in the specified workspace or organization. Results are sorted alphabetically and limited to 2000. For more results use the `/users` endpoint. + * @param {<&vendorExtensions.x-jsdoc-type>} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/UserResponseArray} + */ + }, { + key: "getUsersForWorkspace", + value: function getUsersForWorkspace(workspace_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getUsersForWorkspaceWithHttpInfo(workspace_gid, opts); + } + return this.getUsersForWorkspaceWithHttpInfo(workspace_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/WebhooksApi.js b/node_modules/asana/dist/api/WebhooksApi.js new file mode 100644 index 000000000..6be51febd --- /dev/null +++ b/node_modules/asana/dist/api/WebhooksApi.js @@ -0,0 +1,310 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.WebhooksApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* Webhooks service. +* @module api/WebhooksApi +* @version 3.0.3 +*/ +var WebhooksApi = exports.WebhooksApi = /*#__PURE__*/function () { + /** + * Constructs a new WebhooksApi. + * @alias module:api/WebhooksApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function WebhooksApi(apiClient) { + _classCallCheck(this, WebhooksApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Establish a webhook + * Establishing a webhook is a two-part process. First, a simple HTTP POST request initiates the creation similar to creating any other resource. Next, in the middle of this request comes the confirmation handshake. When a webhook is created, we will send a test POST to the target with an `X-Hook-Secret` header. The target must respond with a `200 OK` or `204 No Content` and a matching `X-Hook-Secret` header to confirm that this webhook subscription is indeed expected. We strongly recommend storing this secret to be used to verify future webhook event signatures. The POST request to create the webhook will then return with the status of the request. If you do not acknowledge the webhook’s confirmation handshake it will fail to setup, and you will receive an error in response to your attempt to create it. This means you need to be able to receive and complete the webhook *while* the POST request is in-flight (in other words, have a server that can handle requests asynchronously). Invalid hostnames like localhost will recieve a 403 Forbidden status code. ``` # Request curl -H \"Authorization: Bearer <personal_access_token>\" \\ -X POST https://app.asana.com/api/1.0/webhooks \\ -d \"resource=8675309\" \\ -d \"target=https://example.com/receive-webhook/7654\" ``` ``` # Handshake sent to https://example.com/ POST /receive-webhook/7654 X-Hook-Secret: b537207f20cbfa02357cf448134da559e8bd39d61597dcd5631b8012eae53e81 ``` ``` # Handshake response sent by example.com HTTP/1.1 200 X-Hook-Secret: b537207f20cbfa02357cf448134da559e8bd39d61597dcd5631b8012eae53e81 ``` ``` # Response HTTP/1.1 201 { \"data\": { \"gid\": \"43214\", \"resource\": { \"gid\": \"8675309\", \"name\": \"Bugs\" }, \"target\": \"https://example.com/receive-webhook/7654\", \"active\": false, \"last_success_at\": null, \"last_failure_at\": null, \"last_failure_content\": null } } ``` + * @param {module:model/Object} body The webhook workspace and target. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(WebhooksApi, [{ + key: "createWebhookWithHttpInfo", + value: function createWebhookWithHttpInfo(body, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling createWebhook"); + } + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/webhooks', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Establish a webhook + * Establishing a webhook is a two-part process. First, a simple HTTP POST request initiates the creation similar to creating any other resource. Next, in the middle of this request comes the confirmation handshake. When a webhook is created, we will send a test POST to the target with an `X-Hook-Secret` header. The target must respond with a `200 OK` or `204 No Content` and a matching `X-Hook-Secret` header to confirm that this webhook subscription is indeed expected. We strongly recommend storing this secret to be used to verify future webhook event signatures. The POST request to create the webhook will then return with the status of the request. If you do not acknowledge the webhook’s confirmation handshake it will fail to setup, and you will receive an error in response to your attempt to create it. This means you need to be able to receive and complete the webhook *while* the POST request is in-flight (in other words, have a server that can handle requests asynchronously). Invalid hostnames like localhost will recieve a 403 Forbidden status code. ``` # Request curl -H \"Authorization: Bearer <personal_access_token>\" \\ -X POST https://app.asana.com/api/1.0/webhooks \\ -d \"resource=8675309\" \\ -d \"target=https://example.com/receive-webhook/7654\" ``` ``` # Handshake sent to https://example.com/ POST /receive-webhook/7654 X-Hook-Secret: b537207f20cbfa02357cf448134da559e8bd39d61597dcd5631b8012eae53e81 ``` ``` # Handshake response sent by example.com HTTP/1.1 200 X-Hook-Secret: b537207f20cbfa02357cf448134da559e8bd39d61597dcd5631b8012eae53e81 ``` ``` # Response HTTP/1.1 201 { \"data\": { \"gid\": \"43214\", \"resource\": { \"gid\": \"8675309\", \"name\": \"Bugs\" }, \"target\": \"https://example.com/receive-webhook/7654\", \"active\": false, \"last_success_at\": null, \"last_failure_at\": null, \"last_failure_content\": null } } ``` + * @param {<&vendorExtensions.x-jsdoc-type>} body The webhook workspace and target. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/WebhookResponseData} + */ + }, { + key: "createWebhook", + value: function createWebhook(body, opts) { + return this.createWebhookWithHttpInfo(body, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Delete a webhook + * This method *permanently* removes a webhook. Note that it may be possible to receive a request that was already in flight after deleting the webhook, but no further requests will be issued. + * @param {String} webhook_gid Globally unique identifier for the webhook. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "deleteWebhookWithHttpInfo", + value: function deleteWebhookWithHttpInfo(webhook_gid) { + var postBody = null; + // verify the required parameter 'webhook_gid' is set + if (webhook_gid === undefined || webhook_gid === null) { + throw new Error("Missing the required parameter 'webhook_gid' when calling deleteWebhook"); + } + var pathParams = { + 'webhook_gid': webhook_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/webhooks/{webhook_gid}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Delete a webhook + * This method *permanently* removes a webhook. Note that it may be possible to receive a request that was already in flight after deleting the webhook, but no further requests will be issued. + * @param {<&vendorExtensions.x-jsdoc-type>} webhook_gid Globally unique identifier for the webhook. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "deleteWebhook", + value: function deleteWebhook(webhook_gid) { + return this.deleteWebhookWithHttpInfo(webhook_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a webhook + * Returns the full record for the given webhook. + * @param {String} webhook_gid Globally unique identifier for the webhook. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getWebhookWithHttpInfo", + value: function getWebhookWithHttpInfo(webhook_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'webhook_gid' is set + if (webhook_gid === undefined || webhook_gid === null) { + throw new Error("Missing the required parameter 'webhook_gid' when calling getWebhook"); + } + var pathParams = { + 'webhook_gid': webhook_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/webhooks/{webhook_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a webhook + * Returns the full record for the given webhook. + * @param {<&vendorExtensions.x-jsdoc-type>} webhook_gid Globally unique identifier for the webhook. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/WebhookResponseData} + */ + }, { + key: "getWebhook", + value: function getWebhook(webhook_gid, opts) { + return this.getWebhookWithHttpInfo(webhook_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get multiple webhooks + * Get the compact representation of all webhooks your app has registered for the authenticated user in the given workspace. + * @param {String} workspace The workspace to query for webhooks in. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {String} opts.resource Only return webhooks for the given resource. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getWebhooksWithHttpInfo", + value: function getWebhooksWithHttpInfo(workspace, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'workspace' is set + if (workspace === undefined || workspace === null) { + throw new Error("Missing the required parameter 'workspace' when calling getWebhooks"); + } + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + queryParams['workspace'] = workspace; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/webhooks', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/webhooks', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/webhooks', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get multiple webhooks + * Get the compact representation of all webhooks your app has registered for the authenticated user in the given workspace. + * @param {<&vendorExtensions.x-jsdoc-type>} workspace The workspace to query for webhooks in. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {String} opts.resource Only return webhooks for the given resource. + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/WebhookResponseArray} + */ + }, { + key: "getWebhooks", + value: function getWebhooks(workspace, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getWebhooksWithHttpInfo(workspace, opts); + } + return this.getWebhooksWithHttpInfo(workspace, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Update a webhook + * An existing webhook's filters can be updated by making a PUT request on the URL for that webhook. Note that the webhook's previous `filters` array will be completely overwritten by the `filters` sent in the PUT request. + * @param {module:model/Object} body The updated filters for the webhook. + * @param {String} webhook_gid Globally unique identifier for the webhook. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "updateWebhookWithHttpInfo", + value: function updateWebhookWithHttpInfo(body, webhook_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling updateWebhook"); + } + // verify the required parameter 'webhook_gid' is set + if (webhook_gid === undefined || webhook_gid === null) { + throw new Error("Missing the required parameter 'webhook_gid' when calling updateWebhook"); + } + var pathParams = { + 'webhook_gid': webhook_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/webhooks/{webhook_gid}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Update a webhook + * An existing webhook's filters can be updated by making a PUT request on the URL for that webhook. Note that the webhook's previous `filters` array will be completely overwritten by the `filters` sent in the PUT request. + * @param {<&vendorExtensions.x-jsdoc-type>} body The updated filters for the webhook. + * @param {<&vendorExtensions.x-jsdoc-type>} webhook_gid Globally unique identifier for the webhook. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/WebhookResponseData} + */ + }, { + key: "updateWebhook", + value: function updateWebhook(body, webhook_gid, opts) { + return this.updateWebhookWithHttpInfo(body, webhook_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/WorkspaceMembershipsApi.js b/node_modules/asana/dist/api/WorkspaceMembershipsApi.js new file mode 100644 index 000000000..8499c1eb2 --- /dev/null +++ b/node_modules/asana/dist/api/WorkspaceMembershipsApi.js @@ -0,0 +1,242 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.WorkspaceMembershipsApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* WorkspaceMemberships service. +* @module api/WorkspaceMembershipsApi +* @version 3.0.3 +*/ +var WorkspaceMembershipsApi = exports.WorkspaceMembershipsApi = /*#__PURE__*/function () { + /** + * Constructs a new WorkspaceMembershipsApi. + * @alias module:api/WorkspaceMembershipsApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function WorkspaceMembershipsApi(apiClient) { + _classCallCheck(this, WorkspaceMembershipsApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Get a workspace membership + * Returns the complete workspace record for a single workspace membership. + * @param {String} workspace_membership_gid + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(WorkspaceMembershipsApi, [{ + key: "getWorkspaceMembershipWithHttpInfo", + value: function getWorkspaceMembershipWithHttpInfo(workspace_membership_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'workspace_membership_gid' is set + if (workspace_membership_gid === undefined || workspace_membership_gid === null) { + throw new Error("Missing the required parameter 'workspace_membership_gid' when calling getWorkspaceMembership"); + } + var pathParams = { + 'workspace_membership_gid': workspace_membership_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/workspace_memberships/{workspace_membership_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a workspace membership + * Returns the complete workspace record for a single workspace membership. + * @param {<&vendorExtensions.x-jsdoc-type>} workspace_membership_gid + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/WorkspaceMembershipResponseData} + */ + }, { + key: "getWorkspaceMembership", + value: function getWorkspaceMembership(workspace_membership_gid, opts) { + return this.getWorkspaceMembershipWithHttpInfo(workspace_membership_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get workspace memberships for a user + * Returns the compact workspace membership records for the user. + * @param {String} user_gid A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getWorkspaceMembershipsForUserWithHttpInfo", + value: function getWorkspaceMembershipsForUserWithHttpInfo(user_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'user_gid' is set + if (user_gid === undefined || user_gid === null) { + throw new Error("Missing the required parameter 'user_gid' when calling getWorkspaceMembershipsForUser"); + } + var pathParams = { + 'user_gid': user_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/users/{user_gid}/workspace_memberships', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/users/{user_gid}/workspace_memberships', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/users/{user_gid}/workspace_memberships', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get workspace memberships for a user + * Returns the compact workspace membership records for the user. + * @param {<&vendorExtensions.x-jsdoc-type>} user_gid A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/WorkspaceMembershipResponseArray} + */ + }, { + key: "getWorkspaceMembershipsForUser", + value: function getWorkspaceMembershipsForUser(user_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getWorkspaceMembershipsForUserWithHttpInfo(user_gid, opts); + } + return this.getWorkspaceMembershipsForUserWithHttpInfo(user_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get the workspace memberships for a workspace + * Returns the compact workspace membership records for the workspace. + * @param {String} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {String} opts.user A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getWorkspaceMembershipsForWorkspaceWithHttpInfo", + value: function getWorkspaceMembershipsForWorkspaceWithHttpInfo(workspace_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'workspace_gid' is set + if (workspace_gid === undefined || workspace_gid === null) { + throw new Error("Missing the required parameter 'workspace_gid' when calling getWorkspaceMembershipsForWorkspace"); + } + var pathParams = { + 'workspace_gid': workspace_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/workspaces/{workspace_gid}/workspace_memberships', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/workspaces/{workspace_gid}/workspace_memberships', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/workspaces/{workspace_gid}/workspace_memberships', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get the workspace memberships for a workspace + * Returns the compact workspace membership records for the workspace. + * @param {<&vendorExtensions.x-jsdoc-type>} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {String} opts.user A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/WorkspaceMembershipResponseArray} + */ + }, { + key: "getWorkspaceMembershipsForWorkspace", + value: function getWorkspaceMembershipsForWorkspace(workspace_gid, opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getWorkspaceMembershipsForWorkspaceWithHttpInfo(workspace_gid, opts); + } + return this.getWorkspaceMembershipsForWorkspaceWithHttpInfo(workspace_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/api/WorkspacesApi.js b/node_modules/asana/dist/api/WorkspacesApi.js new file mode 100644 index 000000000..031277ac1 --- /dev/null +++ b/node_modules/asana/dist/api/WorkspacesApi.js @@ -0,0 +1,315 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.WorkspacesApi = void 0; +var _ApiClient = require("../ApiClient"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* + * Asana + * This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/openapi/master/defs/asana_oas.yaml). + * + * OpenAPI spec version: 1.0 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 3.0.54 + * + * Do not edit the class manually. + * + */ +var Collection = require('../utils/collection'); + +/** +* Workspaces service. +* @module api/WorkspacesApi +* @version 3.0.3 +*/ +var WorkspacesApi = exports.WorkspacesApi = /*#__PURE__*/function () { + /** + * Constructs a new WorkspacesApi. + * @alias module:api/WorkspacesApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instanc + e} if unspecified. + */ + function WorkspacesApi(apiClient) { + _classCallCheck(this, WorkspacesApi); + this.apiClient = apiClient || _ApiClient.ApiClient.instance; + } + + /** + * Add a user to a workspace or organization + * Add a user to a workspace or organization. The user can be referenced by their globally unique user ID or their email address. Returns the full user record for the invited user. + * @param {module:model/Object} body The user to add to the workspace. + * @param {String} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + return _createClass(WorkspacesApi, [{ + key: "addUserForWorkspaceWithHttpInfo", + value: function addUserForWorkspaceWithHttpInfo(body, workspace_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling addUserForWorkspace"); + } + // verify the required parameter 'workspace_gid' is set + if (workspace_gid === undefined || workspace_gid === null) { + throw new Error("Missing the required parameter 'workspace_gid' when calling addUserForWorkspace"); + } + var pathParams = { + 'workspace_gid': workspace_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/workspaces/{workspace_gid}/addUser', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Add a user to a workspace or organization + * Add a user to a workspace or organization. The user can be referenced by their globally unique user ID or their email address. Returns the full user record for the invited user. + * @param {<&vendorExtensions.x-jsdoc-type>} body The user to add to the workspace. + * @param {<&vendorExtensions.x-jsdoc-type>} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/UserBaseResponseData} + */ + }, { + key: "addUserForWorkspace", + value: function addUserForWorkspace(body, workspace_gid, opts) { + return this.addUserForWorkspaceWithHttpInfo(body, workspace_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get a workspace + * Returns the full workspace record for a single workspace. + * @param {String} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getWorkspaceWithHttpInfo", + value: function getWorkspaceWithHttpInfo(workspace_gid, opts) { + opts = opts || {}; + var postBody = null; + // verify the required parameter 'workspace_gid' is set + if (workspace_gid === undefined || workspace_gid === null) { + throw new Error("Missing the required parameter 'workspace_gid' when calling getWorkspace"); + } + var pathParams = { + 'workspace_gid': workspace_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/workspaces/{workspace_gid}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get a workspace + * Returns the full workspace record for a single workspace. + * @param {<&vendorExtensions.x-jsdoc-type>} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/WorkspaceResponseData} + */ + }, { + key: "getWorkspace", + value: function getWorkspace(workspace_gid, opts) { + return this.getWorkspaceWithHttpInfo(workspace_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Get multiple workspaces + * Returns the compact records for all workspaces visible to the authorized user. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "getWorkspacesWithHttpInfo", + value: function getWorkspacesWithHttpInfo(opts) { + opts = opts || {}; + var postBody = null; + var pathParams = {}; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = []; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return Collection.fromApiClient(this.apiClient.callApi('/workspaces', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType), this.apiClient, { + 'path': '/workspaces', + 'httpMethod': 'GET', + 'pathParams': pathParams, + 'queryParams': queryParams, + 'headerParams': headerParams, + 'formParams': formParams, + 'bodyParam': postBody, + 'authNames': authNames, + 'contentTypes': contentTypes, + 'accepts': accepts, + 'returnType': returnType + }); + } + return this.apiClient.callApi('/workspaces', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Get multiple workspaces + * Returns the compact records for all workspaces visible to the authorized user. + * @param {Object} opts Optional parameters + * @param {Number} opts.limit Results per page. The number of objects to return per page. The value must be between 1 and 100. + * @param {String} opts.offset Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/WorkspaceResponseArray} + */ + }, { + key: "getWorkspaces", + value: function getWorkspaces(opts) { + // Check if RETURN_COLLECTION is set and return a collection object if it is + if (this.apiClient.RETURN_COLLECTION) { + return this.getWorkspacesWithHttpInfo(opts); + } + return this.getWorkspacesWithHttpInfo(opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Remove a user from a workspace or organization + * Remove a user from a workspace or organization. The user making this call must be an admin in the workspace. The user can be referenced by their globally unique user ID or their email address. Returns an empty data record. + * @param {module:model/Object} body The user to remove from the workspace. + * @param {String} workspace_gid Globally unique identifier for the workspace or organization. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "removeUserForWorkspaceWithHttpInfo", + value: function removeUserForWorkspaceWithHttpInfo(body, workspace_gid) { + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling removeUserForWorkspace"); + } + // verify the required parameter 'workspace_gid' is set + if (workspace_gid === undefined || workspace_gid === null) { + throw new Error("Missing the required parameter 'workspace_gid' when calling removeUserForWorkspace"); + } + var pathParams = { + 'workspace_gid': workspace_gid + }; + var queryParams = {}; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/workspaces/{workspace_gid}/removeUser', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Remove a user from a workspace or organization + * Remove a user from a workspace or organization. The user making this call must be an admin in the workspace. The user can be referenced by their globally unique user ID or their email address. Returns an empty data record. + * @param {<&vendorExtensions.x-jsdoc-type>} body The user to remove from the workspace. + * @param {<&vendorExtensions.x-jsdoc-type>} workspace_gid Globally unique identifier for the workspace or organization. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/EmptyResponseData} + */ + }, { + key: "removeUserForWorkspace", + value: function removeUserForWorkspace(body, workspace_gid) { + return this.removeUserForWorkspaceWithHttpInfo(body, workspace_gid).then(function (response_and_data) { + return response_and_data.data; + }); + } + + /** + * Update a workspace + * A specific, existing workspace can be updated by making a PUT request on the URL for that workspace. Only the fields provided in the data block will be updated; any unspecified fields will remain unchanged. Currently the only field that can be modified for a workspace is its name. Returns the complete, updated workspace record. + * @param {module:model/Object} body The workspace object with all updated properties. + * @param {String} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data and HTTP response + */ + }, { + key: "updateWorkspaceWithHttpInfo", + value: function updateWorkspaceWithHttpInfo(body, workspace_gid, opts) { + opts = opts || {}; + var postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling updateWorkspace"); + } + // verify the required parameter 'workspace_gid' is set + if (workspace_gid === undefined || workspace_gid === null) { + throw new Error("Missing the required parameter 'workspace_gid' when calling updateWorkspace"); + } + var pathParams = { + 'workspace_gid': workspace_gid + }; + var queryParams = {}; + opts = opts || {}; + queryParams = opts; + var headerParams = {}; + var formParams = {}; + var authNames = ['personalAccessToken']; + var contentTypes = ['application/json; charset=UTF-8']; + var accepts = ['application/json; charset=UTF-8']; + var returnType = 'Blob'; + return this.apiClient.callApi('/workspaces/{workspace_gid}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType); + } + + /** + * Update a workspace + * A specific, existing workspace can be updated by making a PUT request on the URL for that workspace. Only the fields provided in the data block will be updated; any unspecified fields will remain unchanged. Currently the only field that can be modified for a workspace is its name. Returns the complete, updated workspace record. + * @param {<&vendorExtensions.x-jsdoc-type>} body The workspace object with all updated properties. + * @param {<&vendorExtensions.x-jsdoc-type>} workspace_gid Globally unique identifier for the workspace or organization. + * @param {Object} opts Optional parameters + * @param {Array.} opts.opt_fields This endpoint returns a compact resource, which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include. + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/WorkspaceResponseData} + */ + }, { + key: "updateWorkspace", + value: function updateWorkspace(body, workspace_gid, opts) { + return this.updateWorkspaceWithHttpInfo(body, workspace_gid, opts).then(function (response_and_data) { + return response_and_data.data; + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/asana/dist/asana-min.js b/node_modules/asana/dist/asana-min.js deleted file mode 100644 index ce9a3a389..000000000 --- a/node_modules/asana/dist/asana-min.js +++ /dev/null @@ -1 +0,0 @@ -!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Asana=t()}}(function(){var t,e,r;return function(){return function t(e,r,n){function o(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(i)return i(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var l=r[s]={exports:{}};e[s][0].call(l.exports,function(t){return o(e[s][1][t]||t)},l,l.exports,t,e,r,n)}return r[s].exports}for(var i="function"==typeof require&&require,s=0;s0){for(var t=0;t0;return e||this.push(t)||(e=!0),e&&this._buffer.push(t),!e},o.prototype._readUnbuffered=function(){throw new Error("not implemented")},e.exports=o},{stream:97,util:119}],76:[function(t,e,r){var n=t("bluebird"),o=t("./resource_stream");function i(t,e,r){if(!i.isCollectionResponse(t))throw new Error("Cannot create Collection from response that does not have resources");this.data=t.data,this._response=t,this._dispatcher=e,this._dispatchOptions=r}i.fromDispatch=function(t,e,r){return t.then(function(t){return new i(t,e,r)})},i.isCollectionResponse=function(t){return"object"==typeof t&&"object"==typeof t.data&&"number"==typeof t.data.length},i.prototype.stream=function(){return new o(this)},i.prototype.nextPage=function(){var t=this,e=t._response.next_page;if("object"==typeof e&&null!==e){var r=e.uri;return i.fromDispatch(t._dispatcher.dispatch({method:"GET",url:r,json:!0},t._dispatchOptions),t._dispatcher,t._dispatchOptions)}return n.resolve(null)},i.prototype.fetch=function(t){var e=this;return t=t||1e5,new n(function(r,n){var o=[];!function e(i){null===i?r(o):([].push.apply(o,i.data),o.length>=t?(o=o.slice(0,t),r(o)):i.nextPage().then(e).catch(n))}(e)})},e.exports=i},{"./resource_stream":78,bluebird:80}],77:[function(t,e,r){var n=t("./buffered_readable");function o(t,e,r){n.call(this,{objectMode:!0}),this.resourceId=e,this.events=t,this.syncToken=null,this.options=r||{},this.options.periodSeconds=this.options.periodSeconds||5,this._lastPollTime=0,this._polling=!1}t("util").inherits(o,n),o.prototype._readUnbuffered=function(){this._polling||this._schedule()},o.prototype._schedule=function(){var t=this;if(0===t._lastPollTime)t._poll();else{var e=Date.now(),r=Math.max(0,1e3*t.options.periodSeconds-(e-t._lastPollTime));setTimeout(function(){t._poll()},r)}},o.prototype._poll=function(){var t=this;t._polling=!0,t._lastPollTime=Date.now(),t.events.get(t.resourceId,t.syncToken).then(function(e){t.syncToken=e.sync;var r=!0;e.data&&e.data.length>0&&e.data.forEach(function(e){r=r&&t.pushBuffered(e)}),r&&t._schedule()}).catch(function(e){t.emit("error",e),t._schedule()})},e.exports=o},{"./buffered_readable":75,util:119}],78:[function(t,e,r){var n=t("./buffered_readable");function o(t){n.call(this,{objectMode:!0}),this._collection=t,this._fetching=!1,this._pushCollection()}t("util").inherits(o,n),o.prototype._pushCollection=function(){var t=this;t._collection.data.forEach(function(e){t.pushBuffered(e)})},o.prototype._readUnbuffered=function(){var t=this;t._collection?t._fetching||(t._fetching=!0,t._collection.nextPage().then(function(e){t._fetching=!1,e?(t._collection=e,t._pushCollection()):t.pushBuffered(null)}).catch(function(e){t._fetching=!1,t._collection=null,t.emit("error",e)})):t.pushBuffered(null)},e.exports=o},{"./buffered_readable":75,util:119}],79:[function(t,e,r){"use strict";r.byteLength=function(t){var e=c(t),r=e[0],n=e[1];return 3*(r+n)/4-n},r.toByteArray=function(t){var e,r,n=c(t),s=n[0],a=n[1],u=new i((p=s,h=a,3*(p+h)/4-h)),l=0,f=a>0?s-4:s;var p,h;for(r=0;r>16&255,u[l++]=e>>8&255,u[l++]=255&e;2===a&&(e=o[t.charCodeAt(r)]<<2|o[t.charCodeAt(r+1)]>>4,u[l++]=255&e);1===a&&(e=o[t.charCodeAt(r)]<<10|o[t.charCodeAt(r+1)]<<4|o[t.charCodeAt(r+2)]>>2,u[l++]=e>>8&255,u[l++]=255&e);return u},r.fromByteArray=function(t){for(var e,r=t.length,o=r%3,i=[],s=0,a=r-o;sa?a:s+16383));1===o?(e=t[r-1],i.push(n[e>>2]+n[e<<4&63]+"==")):2===o&&(e=(t[r-2]<<8)+t[r-1],i.push(n[e>>10]+n[e>>4&63]+n[e<<2&63]+"="));return i.join("")};for(var n=[],o=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,u=s.length;a0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function l(t,e,r){for(var o,i,s=[],a=e;a>18&63]+n[i>>12&63]+n[i>>6&63]+n[63&i]);return s.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},{}],80:[function(e,r,n){(function(e,o,i){!function(e){if("object"==typeof n&&void 0!==r)r.exports=e();else if("function"==typeof t&&t.amd)t([],e);else{var i;"undefined"!=typeof window?i=window:void 0!==o?i=o:"undefined"!=typeof self&&(i=self),i.Promise=e()}}(function(){var t,r,n;return function t(e,r,n){function o(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof _dereq_&&_dereq_;if(!a&&u)return u(s,!0);if(i)return i(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var l=r[s]={exports:{}};e[s][0].call(l.exports,function(t){var r=e[s][1][t];return o(r||t)},l,l.exports,t,e,r,n)}return r[s].exports}for(var i="function"==typeof _dereq_&&_dereq_,s=0;s0;)c(t)}function c(t){var e=t.shift();if("function"!=typeof e)e._settlePromises();else{var r=t.shift(),n=t.shift();e.call(r,n)}}a.prototype.setScheduler=function(t){var e=this._schedule;return this._schedule=t,this._customScheduler=!0,e},a.prototype.hasCustomScheduler=function(){return this._customScheduler},a.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues},a.prototype.fatalError=function(t,r){r?(e.stderr.write("Fatal "+(t instanceof Error?t.stack:t)+"\n"),e.exit(2)):this.throwLater(t)},a.prototype.throwLater=function(t,e){if(1===arguments.length&&(e=t,t=function(){throw e}),"undefined"!=typeof setTimeout)setTimeout(function(){t(e)},0);else try{this._schedule(function(){t(e)})}catch(t){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")}},a.prototype.invokeLater=function(t,e,r){this._lateQueue.push(t,e,r),this._queueTick()},a.prototype.invoke=function(t,e,r){this._normalQueue.push(t,e,r),this._queueTick()},a.prototype.settlePromises=function(t){this._normalQueue._pushOne(t),this._queueTick()},a.prototype._drainQueues=function(){u(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,u(this._lateQueue)},a.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},a.prototype._reset=function(){this._isTickUsed=!1},r.exports=a,r.exports.firstLineError=o},{"./queue":26,"./schedule":29}],3:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){var o=!1,i=function(t,e){this._reject(e)},s=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(i,i,null,this,t)},a=function(t,e){0==(50397184&this._bitField)&&this._resolveCallback(e.target)},u=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(i){o||(o=!0,t.prototype._propagateFrom=n.propagateFromFunction(),t.prototype._boundValue=n.boundValueFunction());var c=r(i),l=new t(e);l._propagateFrom(this,1);var f=this._target();if(l._setBoundTo(c),c instanceof t){var p={promiseRejectionQueued:!1,promise:l,target:f,bindingPromise:c};f._then(e,s,void 0,l,p),c._then(a,u,void 0,l,p),l._setOnCancel(c)}else l._resolveCallback(f);return l},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=2097152|this._bitField,this._boundTo=t):this._bitField=-2097153&this._bitField},t.prototype._isBound=function(){return 2097152==(2097152&this._bitField)},t.bind=function(e,r){return t.resolve(r).bind(e)}}},{}],4:[function(t,e,r){"use strict";var n;"undefined"!=typeof Promise&&(n=Promise);var o=t("./promise")();o.noConflict=function(){try{Promise===o&&(Promise=n)}catch(t){}return o},e.exports=o},{"./promise":22}],5:[function(t,e,r){"use strict";var n=Object.create;if(n){var o=n(null),i=n(null);o[" size"]=i[" size"]=0}e.exports=function(e){var r,n=t("./util"),o=n.canEvaluate;n.isIdentifier;function i(t,r){var o;if(null!=t&&(o=t[r]),"function"!=typeof o){var i="Object "+n.classString(t)+" has no method '"+n.toString(r)+"'";throw new e.TypeError(i)}return o}function s(t){return i(t,this.pop()).apply(t,this)}function a(t){return t[this]}function u(t){var e=+this;return e<0&&(e=Math.max(0,e+t.length)),t[e]}e.prototype.call=function(t){var e=[].slice.call(arguments,1);return e.push(t),this._then(s,void 0,void 0,e,void 0)},e.prototype.get=function(t){var e;if("number"==typeof t)e=u;else if(o){var n=r(t);e=null!==n?n:a}else e=a;return this._then(e,void 0,void 0,t,void 0)}}},{"./util":36}],6:[function(t,e,r){"use strict";e.exports=function(e,r,n,o){var i=t("./util"),s=i.tryCatch,a=i.errorObj,u=e._async;e.prototype.break=e.prototype.cancel=function(){if(!o.cancellation())return this._warn("cancellation is disabled");for(var t=this,e=t;t._isCancellable();){if(!t._cancelBy(e)){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}var r=t._cancellationParent;if(null==r||!r._isCancellable()){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}t._isFollowing()&&t._followee().cancel(),t._setWillBeCancelled(),e=t,t=r}},e.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},e.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},e.prototype._cancelBy=function(t){return t===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),!!this._enoughBranchesHaveCancelled()&&(this._invokeOnCancel(),!0))},e.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},e.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),u.invoke(this._cancelPromises,this,void 0))},e.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},e.prototype._unsetOnCancel=function(){this._onCancelField=void 0},e.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},e.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},e.prototype._doInvokeOnCancel=function(t,e){if(i.isArray(t))for(var r=0;r=0)return r[t]}return t.prototype._promiseCreated=function(){},t.prototype._pushContext=function(){},t.prototype._popContext=function(){return null},t._peekContext=t.prototype._peekContext=function(){},n.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,r.push(this._trace))},n.prototype._popContext=function(){if(void 0!==this._trace){var t=r.pop(),e=t._promiseCreated;return t._promiseCreated=null,e}return null},n.CapturedTrace=null,n.create=function(){if(e)return new n},n.deactivateLongStackTraces=function(){},n.activateLongStackTraces=function(){var r=t.prototype._pushContext,i=t.prototype._popContext,s=t._peekContext,a=t.prototype._peekContext,u=t.prototype._promiseCreated;n.deactivateLongStackTraces=function(){t.prototype._pushContext=r,t.prototype._popContext=i,t._peekContext=s,t.prototype._peekContext=a,t.prototype._promiseCreated=u,e=!1},e=!0,t.prototype._pushContext=n.prototype._pushContext,t.prototype._popContext=n.prototype._popContext,t._peekContext=t.prototype._peekContext=o,t.prototype._promiseCreated=function(){var t=this._peekContext();t&&null==t._promiseCreated&&(t._promiseCreated=this)}},n}},{}],9:[function(t,r,n){"use strict";r.exports=function(r,n,o,i){var s,a,u,c,l=r._async,f=t("./errors").Warning,p=t("./util"),h=t("./es5"),d=p.canAttachTrace,_=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,v=/\((?:timers\.js):\d+:\d+\)/,g=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,y=null,m=null,b=!1,w=!(0==p.env("BLUEBIRD_DEBUG")),k=!(0==p.env("BLUEBIRD_WARNINGS")||!w&&!p.env("BLUEBIRD_WARNINGS")),j=!(0==p.env("BLUEBIRD_LONG_STACK_TRACES")||!w&&!p.env("BLUEBIRD_LONG_STACK_TRACES")),C=0!=p.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(k||!!p.env("BLUEBIRD_W_FORGOTTEN_RETURN"));!function(){var t=[];function e(){for(var e=0;e0},r.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},r.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},r.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},r.prototype._warn=function(t,e,r){return W(t,e,r||this)},r.onPossiblyUnhandledRejection=function(t){var e=r._getContext();a=p.contextBind(e,t)},r.onUnhandledRejectionHandled=function(t){var e=r._getContext();s=p.contextBind(e,t)};var x=function(){};r.longStackTraces=function(){if(l.haveItemsQueued()&&!rt.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!rt.longStackTraces&&X()){var t=r.prototype._captureStackTrace,e=r.prototype._attachExtraTrace,o=r.prototype._dereferenceTrace;rt.longStackTraces=!0,x=function(){if(l.haveItemsQueued()&&!rt.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");r.prototype._captureStackTrace=t,r.prototype._attachExtraTrace=e,r.prototype._dereferenceTrace=o,n.deactivateLongStackTraces(),rt.longStackTraces=!1},r.prototype._captureStackTrace=z,r.prototype._attachExtraTrace=G,r.prototype._dereferenceTrace=q,n.activateLongStackTraces()}},r.hasLongStackTraces=function(){return rt.longStackTraces&&X()};var E={unhandledrejection:{before:function(){var t=p.global.onunhandledrejection;return p.global.onunhandledrejection=null,t},after:function(t){p.global.onunhandledrejection=t}},rejectionhandled:{before:function(){var t=p.global.onrejectionhandled;return p.global.onrejectionhandled=null,t},after:function(t){p.global.onrejectionhandled=t}}},T=function(){var t=function(t,e){if(!t)return!p.global.dispatchEvent(e);var r;try{return r=t.before(),!p.global.dispatchEvent(e)}finally{t.after(r)}};try{if("function"==typeof CustomEvent){var e=new CustomEvent("CustomEvent");return p.global.dispatchEvent(e),function(e,r){e=e.toLowerCase();var n=new CustomEvent(e,{detail:r,cancelable:!0});return h.defineProperty(n,"promise",{value:r.promise}),h.defineProperty(n,"reason",{value:r.reason}),t(E[e],n)}}if("function"==typeof Event){e=new Event("CustomEvent");return p.global.dispatchEvent(e),function(e,r){e=e.toLowerCase();var n=new Event(e,{cancelable:!0});return n.detail=r,h.defineProperty(n,"promise",{value:r.promise}),h.defineProperty(n,"reason",{value:r.reason}),t(E[e],n)}}return(e=document.createEvent("CustomEvent")).initCustomEvent("testingtheevent",!1,!0,{}),p.global.dispatchEvent(e),function(e,r){e=e.toLowerCase();var n=document.createEvent("CustomEvent");return n.initCustomEvent(e,!1,!0,r),t(E[e],n)}}catch(t){}return function(){return!1}}(),S=p.isNode?function(){return e.emit.apply(e,arguments)}:p.global?function(t){var e="on"+t.toLowerCase(),r=p.global[e];return!!r&&(r.apply(p.global,[].slice.call(arguments,1)),!0)}:function(){return!1};function P(t,e){return{promise:e}}var F={promiseCreated:P,promiseFulfilled:P,promiseRejected:P,promiseResolved:P,promiseCancelled:P,promiseChained:function(t,e,r){return{promise:e,child:r}},warning:function(t,e){return{warning:e}},unhandledRejection:function(t,e,r){return{reason:e,promise:r}},rejectionHandled:P},A=function(t){var e=!1;try{e=S.apply(null,arguments)}catch(t){l.throwLater(t),e=!0}var r=!1;try{r=T(t,F[t].apply(null,arguments))}catch(t){l.throwLater(t),r=!0}return r||e};function O(){return!1}function R(t,e,r){var n=this;try{t(e,r,function(t){if("function"!=typeof t)throw new TypeError("onCancel must be a function, got: "+p.toString(t));n._attachCancellationCallback(t)})}catch(t){return t}}function U(t){if(!this._isCancellable())return this;var e=this._onCancel();void 0!==e?p.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function I(){return this._onCancelField}function B(t){this._onCancelField=t}function L(){this._cancellationParent=void 0,this._onCancelField=void 0}function M(t,e){if(0!=(1&e)){this._cancellationParent=t;var r=t._branchesRemainingToCancel;void 0===r&&(r=0),t._branchesRemainingToCancel=r+1}0!=(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}r.config=function(t){if("longStackTraces"in(t=Object(t))&&(t.longStackTraces?r.longStackTraces():!t.longStackTraces&&r.hasLongStackTraces()&&x()),"warnings"in t){var e=t.warnings;rt.warnings=!!e,C=rt.warnings,p.isObject(e)&&"wForgottenReturn"in e&&(C=!!e.wForgottenReturn)}if("cancellation"in t&&t.cancellation&&!rt.cancellation){if(l.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");r.prototype._clearCancellationData=L,r.prototype._propagateFrom=M,r.prototype._onCancel=I,r.prototype._setOnCancel=B,r.prototype._attachCancellationCallback=U,r.prototype._execute=R,D=M,rt.cancellation=!0}if("monitoring"in t&&(t.monitoring&&!rt.monitoring?(rt.monitoring=!0,r.prototype._fireEvent=A):!t.monitoring&&rt.monitoring&&(rt.monitoring=!1,r.prototype._fireEvent=O)),"asyncHooks"in t&&p.nodeSupportsAsyncResource){var n=rt.asyncHooks,s=!!t.asyncHooks;n!==s&&(rt.asyncHooks=s,s?o():i())}return r},r.prototype._fireEvent=O,r.prototype._execute=function(t,e,r){try{t(e,r)}catch(t){return t}},r.prototype._onCancel=function(){},r.prototype._setOnCancel=function(t){},r.prototype._attachCancellationCallback=function(t){},r.prototype._captureStackTrace=function(){},r.prototype._attachExtraTrace=function(){},r.prototype._dereferenceTrace=function(){},r.prototype._clearCancellationData=function(){},r.prototype._propagateFrom=function(t,e){};var D=function(t,e){0!=(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)};function N(){var t=this._boundTo;return void 0!==t&&t instanceof r?t.isFulfilled()?t.value():void 0:t}function z(){this._trace=new tt(this._peekContext())}function G(t,e){if(d(t)){var r=this._trace;if(void 0!==r&&e&&(r=r._parent),void 0!==r)r.attachExtraTrace(t);else if(!t.__stackCleaned__){var n=V(t);p.notEnumerableProp(t,"stack",n.message+"\n"+n.stack.join("\n")),p.notEnumerableProp(t,"__stackCleaned__",!0)}}}function q(){this._trace=void 0}function W(t,e,n){if(rt.warnings){var o,i=new f(t);if(e)n._attachExtraTrace(i);else if(rt.longStackTraces&&(o=r._peekContext()))o.attachExtraTrace(i);else{var s=V(i);i.stack=s.message+"\n"+s.stack.join("\n")}A("warning",i)||$(i,"",!0)}}function H(t){for(var e=[],r=0;r0?function(t){for(var e=t.stack.replace(/\s+$/g,"").split("\n"),r=0;r0&&"SyntaxError"!=t.name&&(e=e.slice(r)),e}(t):[" (No stack trace)"],{message:r,stack:"SyntaxError"==t.name?e:H(e)}}function $(t,e,r){if("undefined"!=typeof console){var n;if(p.isObject(t)){var o=t.stack;n=e+m(o,t)}else n=e+String(t);"function"==typeof u?u(n,r):"function"!=typeof console.log&&"object"!=typeof console.log||console.log(n)}}function J(t,e,r,n){var o=!1;try{"function"==typeof e&&(o=!0,"rejectionHandled"===t?e(n):e(r,n))}catch(t){l.throwLater(t)}"unhandledRejection"===t?A(t,r,n)||o||$(r,"Unhandled rejection "):A(t,n)}function Q(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():p.toString(t);if(/\[object [a-zA-Z0-9$_]+\]/.test(e))try{e=JSON.stringify(t)}catch(t){}0===e.length&&(e="(empty array)")}return"(<"+function(t){if(t.length<41)return t;return t.substr(0,38)+"..."}(e)+">, no stack trace)"}function X(){return"function"==typeof et}var K=function(){return!1},Z=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function Y(t){var e=t.match(Z);if(e)return{fileName:e[1],line:parseInt(e[2],10)}}function tt(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);et(this,tt),e>32&&this.uncycle()}p.inherits(tt,Error),n.CapturedTrace=tt,tt.prototype.uncycle=function(){var t=this._length;if(!(t<2)){for(var e=[],r={},n=0,o=this;void 0!==o;++n)e.push(o),o=o._parent;for(n=(t=this._length=n)-1;n>=0;--n){var i=e[n].stack;void 0===r[i]&&(r[i]=n)}for(n=0;n0&&(e[s-1]._parent=void 0,e[s-1]._length=1),e[n]._parent=void 0,e[n]._length=1;var a=n>0?e[n-1]:this;s=0;--c)e[c]._length=u,u++;return}}}},tt.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=V(t),r=e.message,n=[e.stack],o=this;void 0!==o;)n.push(H(o.stack.split("\n"))),o=o._parent;!function(t){for(var e=t[0],r=1;r=0;--a)if(n[a]===i){s=a;break}for(a=s;a>=0;--a){var u=n[a];if(e[o]!==u)break;e.pop(),o--}e=n}}(n),function(t){for(var e=0;e=0)return y=/@/,m=e,b=!0,function(t){t.stack=(new Error).stack};try{throw new Error}catch(t){n="stack"in t}return"stack"in o||!n||"number"!=typeof Error.stackTraceLimit?(m=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?Q(e):e.toString()},null):(y=t,m=e,function(t){Error.stackTraceLimit+=6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit-=6})}();"undefined"!=typeof console&&void 0!==console.warn&&(u=function(t){console.warn(t)},p.isNode&&e.stderr.isTTY?u=function(t,e){var r=e?"":"";console.warn(r+t+"\n")}:p.isNode||"string"!=typeof(new Error).stack||(u=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var rt={warnings:k,longStackTraces:!1,cancellation:!1,monitoring:!1,asyncHooks:!1};return j&&r.longStackTraces(),{asyncHooks:function(){return rt.asyncHooks},longStackTraces:function(){return rt.longStackTraces},warnings:function(){return rt.warnings},cancellation:function(){return rt.cancellation},monitoring:function(){return rt.monitoring},propagateFromFunction:function(){return D},boundValueFunction:function(){return N},checkForgottenReturns:function(t,e,r,n,o){if(void 0===t&&null!==e&&C){if(void 0!==o&&o._returnedNonUndefined())return;if(0==(65535&n._bitField))return;r&&(r+=" ");var i="",s="";if(e._trace){for(var a=e._trace.stack.split("\n"),u=H(a),c=u.length-1;c>=0;--c){var l=u[c];if(!v.test(l)){var f=l.match(g);f&&(i="at "+f[1]+":"+f[2]+":"+f[3]+" ");break}}if(u.length>0){var p=u[0];for(c=0;c0&&(s="\n"+a[c-1]);break}}}var h="a promise was created in a "+r+"handler "+i+"but was not returned from it, see http://goo.gl/rRqMUw"+s;n._warn(h,!0,e)}},setBounds:function(t,e){if(X()){for(var r,n,o=(t.stack||"").split("\n"),i=(e.stack||"").split("\n"),s=-1,a=-1,u=0;u=a||(K=function(t){if(_.test(t))return!0;var e=Y(t);return!!(e&&e.fileName===r&&s<=e.line&&e.line<=a)})}},warn:W,deprecated:function(t,e){var r=t+" is deprecated and will be removed in a future version.";return e&&(r+=" Use "+e+" instead."),W(r)},CapturedTrace:tt,fireDomEvent:T,fireGlobalEvent:S}}},{"./errors":12,"./es5":13,"./util":36}],10:[function(t,e,r){"use strict";e.exports=function(t){function e(){return this.value}function r(){throw this.reason}t.prototype.return=t.prototype.thenReturn=function(r){return r instanceof t&&r.suppressUnhandledRejections(),this._then(e,void 0,void 0,{value:r},void 0)},t.prototype.throw=t.prototype.thenThrow=function(t){return this._then(r,void 0,void 0,{reason:t},void 0)},t.prototype.catchThrow=function(t){if(arguments.length<=1)return this._then(void 0,r,void 0,{reason:t},void 0);var e=arguments[1];return this.caught(t,function(){throw e})},t.prototype.catchReturn=function(r){if(arguments.length<=1)return r instanceof t&&r.suppressUnhandledRejections(),this._then(void 0,e,void 0,{value:r},void 0);var n=arguments[1];n instanceof t&&n.suppressUnhandledRejections();return this.caught(r,function(){return n})}}},{}],11:[function(t,e,r){"use strict";e.exports=function(t,e){var r=t.reduce,n=t.all;function o(){return n(this)}t.prototype.each=function(t){return r(this,t,e,0)._then(o,void 0,void 0,this,void 0)},t.prototype.mapSeries=function(t){return r(this,t,e,e)},t.each=function(t,n){return r(t,n,e,0)._then(o,void 0,void 0,t,void 0)},t.mapSeries=function(t,n){return r(t,n,e,e)}}},{}],12:[function(t,e,r){"use strict";var n,o,i=t("./es5"),s=i.freeze,a=t("./util"),u=a.inherits,c=a.notEnumerableProp;function l(t,e){function r(n){if(!(this instanceof r))return new r(n);c(this,"message","string"==typeof n?n:e),c(this,"name",t),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this)}return u(r,Error),r}var f=l("Warning","warning"),p=l("CancellationError","cancellation error"),h=l("TimeoutError","timeout error"),d=l("AggregateError","aggregate error");try{n=TypeError,o=RangeError}catch(t){n=l("TypeError","type error"),o=l("RangeError","range error")}for(var _="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),v=0;v<_.length;++v)"function"==typeof Array.prototype[_[v]]&&(d.prototype[_[v]]=Array.prototype[_[v]]);i.defineProperty(d.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0}),d.prototype.isOperational=!0;var g=0;function y(t){if(!(this instanceof y))return new y(t);c(this,"name","OperationalError"),c(this,"message",t),this.cause=t,this.isOperational=!0,t instanceof Error?(c(this,"message",t.message),c(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}d.prototype.toString=function(){var t=Array(4*g+1).join(" "),e="\n"+t+"AggregateError of:\n";g++,t=Array(4*g+1).join(" ");for(var r=0;r1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0)}function f(){return h.call(this,this.promise._target()._settledValue())}function p(t){if(!l(this,t))return s.e=t,s}function h(t){var o=this.promise,a=this.handler;if(!this.called){this.called=!0;var u=this.isFinallyHandler()?a.call(o._boundValue()):a.call(o._boundValue(),t);if(u===n)return u;if(void 0!==u){o._setReturnedNonUndefined();var h=r(u,o);if(h instanceof e){if(null!=this.cancelPromise){if(h._isCancelled()){var d=new i("late cancellation observer");return o._attachExtraTrace(d),s.e=d,s}h.isPending()&&h._attachCancellationCallback(new c(this))}return h._then(f,p,void 0,this,void 0)}}}return o.isRejected()?(l(this),s.e=t,s):(l(this),t)}return u.prototype.isFinallyHandler=function(){return 0===this.type},c.prototype._resultCancelled=function(){l(this.finallyHandler)},e.prototype._passThrough=function(t,e,r,n){return"function"!=typeof t?this.then():this._then(r,n,void 0,new u(this,e,t),void 0)},e.prototype.lastly=e.prototype.finally=function(t){return this._passThrough(t,0,h,h)},e.prototype.tap=function(t){return this._passThrough(t,1,h)},e.prototype.tapCatch=function(t){var r=arguments.length;if(1===r)return this._passThrough(t,1,void 0,h);var n,i=new Array(r-1),s=0;for(n=0;n0&&"function"==typeof arguments[e]&&(t=arguments[e]);var n=[].slice.call(arguments);t&&n.pop();var o=new r(n).promise();return void 0!==t?o.spread(t):o}}},{"./util":36}],18:[function(t,e,r){"use strict";e.exports=function(e,r,n,o,i,s){var a=t("./util"),u=a.tryCatch,c=a.errorObj,l=e._async;function f(t,r,n,o){this.constructor$(t),this._promise._captureStackTrace();var s=e._getContext();if(this._callback=a.contextBind(s,r),this._preservedValues=o===i?new Array(this.length()):null,this._limit=n,this._inFlight=0,this._queue=[],l.invoke(this._asyncInit,this,void 0),a.isArray(t))for(var u=0;u=1?s:0,i).promise()}a.inherits(f,r),f.prototype._asyncInit=function(){this._init$(void 0,-2)},f.prototype._init=function(){},f.prototype._promiseFulfilled=function(t,r){var n=this._values,i=this.length(),a=this._preservedValues,l=this._limit;if(r<0){if(n[r=-1*r-1]=t,l>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(l>=1&&this._inFlight>=l)return n[r]=t,this._queue.push(r),!1;null!==a&&(a[r]=t);var f=this._promise,p=this._callback,h=f._boundValue();f._pushContext();var d=u(p).call(h,t,r,i),_=f._popContext();if(s.checkForgottenReturns(d,_,null!==a?"Promise.filter":"Promise.map",f),d===c)return this._reject(d.e),!0;var v=o(d,this._promise);if(v instanceof e){var g=(v=v._target())._bitField;if(0==(50397184&g))return l>=1&&this._inFlight++,n[r]=v,v._proxy(this,-1*(r+1)),!1;if(0==(33554432&g))return 0!=(16777216&g)?(this._reject(v._reason()),!0):(this._cancel(),!0);d=v._value()}n[r]=d}return++this._totalResolved>=i&&(null!==a?this._filter(n,a):this._resolve(n),!0)},f.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,r=this._values;t.length>0&&this._inFlight1){i.deprecated("calling Promise.try with more than 1 argument");var c=arguments[1],l=arguments[2];n=s.isArray(c)?a(t).apply(l,c):a(t).call(l,c)}else n=a(t)();var f=u._popContext();return i.checkForgottenReturns(n,f,"Promise.try",u),u._resolveFromSyncValue(n),u},e.prototype._resolveFromSyncValue=function(t){t===s.errorObj?this._rejectCallback(t.e,!1):this._resolveCallback(t,!0)}}},{"./util":36}],20:[function(t,e,r){"use strict";var n=t("./util"),o=n.maybeWrapAsError,i=t("./errors").OperationalError,s=t("./es5");var a=/^(?:name|message|stack|cause)$/;function u(t){var e,r;if((r=t)instanceof Error&&s.getPrototypeOf(r)===Error.prototype){(e=new i(t)).name=t.name,e.message=t.message,e.stack=t.stack;for(var o=s.keys(t),u=0;u1){var r,n=new Array(e-1),o=0;for(r=0;r0&&"function"!=typeof t&&"function"!=typeof e){var r=".then() only accepts functions but was passed: "+u.classString(t);arguments.length>1&&(r+=", "+u.classString(e)),this._warn(r)}return this._then(t,e,void 0,void 0,void 0)},R.prototype.done=function(t,e){this._then(t,e,void 0,void 0,void 0)._setIsFinal()},R.prototype.spread=function(t){return"function"!=typeof t?i("expecting a function but got "+u.classString(t)):this.all()._then(t,void 0,void 0,w,void 0)},R.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},R.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new C(this).promise()},R.prototype.error=function(t){return this.caught(u.originatesFromRejection,t)},R.getNewLibraryCopy=r.exports,R.is=function(t){return t instanceof R},R.fromNode=R.fromCallback=function(t){var e=new R(b);e._captureStackTrace();var r=arguments.length>1&&!!Object(arguments[1]).multiArgs,n=O(t)(F(e,r));return n===A&&e._rejectCallback(n.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},R.all=function(t){return new C(t).promise()},R.cast=function(t){var e=j(t);return e instanceof R||((e=new R(b))._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},R.resolve=R.fulfilled=R.cast,R.reject=R.rejected=function(t){var e=new R(b);return e._captureStackTrace(),e._rejectCallback(t,!0),e},R.setScheduler=function(t){if("function"!=typeof t)throw new y("expecting a function but got "+u.classString(t));return v.setScheduler(t)},R.prototype._then=function(t,e,r,n,o){var i=void 0!==o,s=i?o:new R(b),a=this._target(),c=a._bitField;i||(s._propagateFrom(this,3),s._captureStackTrace(),void 0===n&&0!=(2097152&this._bitField)&&(n=0!=(50397184&c)?this._boundValue():a===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,s));var l=h();if(0!=(50397184&c)){var f,p,d=a._settlePromiseCtx;0!=(33554432&c)?(p=a._rejectionHandler0,f=t):0!=(16777216&c)?(p=a._fulfillmentHandler0,f=e,a._unsetRejectionIsUnhandled()):(d=a._settlePromiseLateCancellationObserver,p=new m("late cancellation observer"),a._attachExtraTrace(p),f=e),v.invoke(d,a,{handler:u.contextBind(l,f),promise:s,receiver:n,value:p})}else a._addCallbacks(t,e,s,n,l);return s},R.prototype._length=function(){return 65535&this._bitField},R.prototype._isFateSealed=function(){return 0!=(117506048&this._bitField)},R.prototype._isFollowing=function(){return 67108864==(67108864&this._bitField)},R.prototype._setLength=function(t){this._bitField=-65536&this._bitField|65535&t},R.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},R.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},R.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},R.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},R.prototype._isFinal=function(){return(4194304&this._bitField)>0},R.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},R.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},R.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},R.prototype._setAsyncGuaranteed=function(){if(!v.hasCustomScheduler()){var t=this._bitField;this._bitField=t|(536870912&t)>>2^134217728}},R.prototype._setNoAsyncGuarantee=function(){this._bitField=-134217729&(536870912|this._bitField)},R.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];if(e!==a)return void 0===e&&this._isBound()?this._boundValue():e},R.prototype._promiseAt=function(t){return this[4*t-4+2]},R.prototype._fulfillmentHandlerAt=function(t){return this[4*t-4+0]},R.prototype._rejectionHandlerAt=function(t){return this[4*t-4+1]},R.prototype._boundValue=function(){},R.prototype._migrateCallback0=function(t){t._bitField;var e=t._fulfillmentHandler0,r=t._rejectionHandler0,n=t._promise0,o=t._receiverAt(0);void 0===o&&(o=a),this._addCallbacks(e,r,n,o,null)},R.prototype._migrateCallbackAt=function(t,e){var r=t._fulfillmentHandlerAt(e),n=t._rejectionHandlerAt(e),o=t._promiseAt(e),i=t._receiverAt(e);void 0===i&&(i=a),this._addCallbacks(r,n,o,i,null)},R.prototype._addCallbacks=function(t,e,r,n,o){var i=this._length();if(i>=65531&&(i=0,this._setLength(0)),0===i)this._promise0=r,this._receiver0=n,"function"==typeof t&&(this._fulfillmentHandler0=u.contextBind(o,t)),"function"==typeof e&&(this._rejectionHandler0=u.contextBind(o,e));else{var s=4*i-4;this[s+2]=r,this[s+3]=n,"function"==typeof t&&(this[s+0]=u.contextBind(o,t)),"function"==typeof e&&(this[s+1]=u.contextBind(o,e))}return this._setLength(i+1),i},R.prototype._proxy=function(t,e){this._addCallbacks(void 0,void 0,e,t,null)},R.prototype._resolveCallback=function(t,e){if(0==(117506048&this._bitField)){if(t===this)return this._rejectCallback(n(),!1);var r=j(t,this);if(!(r instanceof R))return this._fulfill(t);e&&this._propagateFrom(r,2);var o=r._target();if(o!==this){var i=o._bitField;if(0==(50397184&i)){var s=this._length();s>0&&o._migrateCallback0(this);for(var a=1;a>>16)){if(t===this){var r=n();return this._attachExtraTrace(r),this._reject(r)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!=(134217728&e)?this._settlePromises():v.settlePromises(this),this._dereferenceTrace())}},R.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16)){if(this._setRejected(),this._fulfillmentHandler0=t,this._isFinal())return v.fatalError(t,u.isNode);(65535&e)>0?v.settlePromises(this):this._ensurePossibleRejectionHandled()}},R.prototype._fulfillPromises=function(t,e){for(var r=1;r0){if(0!=(16842752&t)){var r=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,r,t),this._rejectPromises(e,r)}else{var n=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,n,t),this._fulfillPromises(e,n)}this._setLength(0)}this._clearCancellationData()},R.prototype._settledValue=function(){var t=this._bitField;return 0!=(33554432&t)?this._rejectionHandler0:0!=(16777216&t)?this._fulfillmentHandler0:void 0},"undefined"!=typeof Symbol&&Symbol.toStringTag&&d.defineProperty(R.prototype,Symbol.toStringTag,{get:function(){return"Object"}}),R.defer=R.pending=function(){return T.deprecated("Promise.defer","new Promise"),{promise:new R(b),resolve:U,reject:I}},u.notEnumerableProp(R,"_makeSelfResolutionError",n),t("./method")(R,b,j,i,T),t("./bind")(R,b,j,T),t("./cancel")(R,C,i,T),t("./direct_resolve")(R),t("./synchronous_inspection")(R),t("./join")(R,C,j,b,v),R.Promise=R,R.version="3.7.2",t("./call_get.js")(R),t("./generators.js")(R,i,b,j,s,T),t("./map.js")(R,C,i,j,b,T),t("./nodeify.js")(R),t("./promisify.js")(R,b),t("./props.js")(R,C,j,i),t("./race.js")(R,b,j,i),t("./reduce.js")(R,C,i,j,b,T),t("./settle.js")(R,C,T),t("./some.js")(R,C,i),t("./timers.js")(R,b,T),t("./using.js")(R,i,j,E,b,T),t("./any.js")(R),t("./each.js")(R,b),t("./filter.js")(R,b),u.toFastProperties(R),u.toFastProperties(R.prototype),B({a:1}),B({b:2}),B({c:3}),B(1),B(function(){}),B(void 0),B(!1),B(new R(b)),T.setBounds(_.firstLineError,u.lastLineError),R}},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36,async_hooks:void 0}],23:[function(t,e,r){"use strict";e.exports=function(e,r,n,o,i){var s=t("./util");s.isArray;function a(t){var n=this._promise=new e(r);t instanceof e&&(n._propagateFrom(t,3),t.suppressUnhandledRejections()),n._setOnCancel(this),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}return s.inherits(a,i),a.prototype.length=function(){return this._length},a.prototype.promise=function(){return this._promise},a.prototype._init=function t(r,i){var a=n(this._values,this._promise);if(a instanceof e){var u=(a=a._target())._bitField;if(this._values=a,0==(50397184&u))return this._promise._setAsyncGuaranteed(),a._then(t,this._reject,void 0,this,i);if(0==(33554432&u))return 0!=(16777216&u)?this._reject(a._reason()):this._cancel();a=a._value()}if(null!==(a=s.asArray(a)))0!==a.length?this._iterate(a):-5===i?this._resolveEmptyArray():this._resolve(function(t){switch(t){case-2:return[];case-3:return{};case-6:return new Map}}(i));else{var c=o("expecting an array or an iterable object but got "+s.classString(a)).reason();this._promise._rejectCallback(c,!1)}},a.prototype._iterate=function(t){var r=this.getActualLength(t.length);this._length=r,this._values=this.shouldCopyValues()?new Array(r):this._values;for(var o=this._promise,i=!1,s=null,a=0;a=this._length&&(this._resolve(this._values),!0)},a.prototype._promiseCancelled=function(){return this._cancel(),!0},a.prototype._promiseRejected=function(t){return this._totalResolved++,this._reject(t),!0},a.prototype._resultCancelled=function(){if(!this._isResolved()){var t=this._values;if(this._cancel(),t instanceof e)t.cancel();else for(var r=0;r=this._length){var r;if(this._isMap)r=function(t){for(var e=new i,r=t.length/2|0,n=0;n>1},e.prototype.props=function(){return f(this)},e.props=function(t){return f(t)}}},{"./es5":13,"./util":36}],26:[function(t,e,r){"use strict";function n(t){this._capacity=t,this._length=0,this._front=0}n.prototype._willBeOverCapacity=function(t){return this._capacity=this._length&&(this._resolve(this._values),!0)},i.prototype._promiseFulfilled=function(t,e){var r=new o;return r._bitField=33554432,r._settledValueField=t,this._promiseResolved(e,r)},i.prototype._promiseRejected=function(t,e){var r=new o;return r._bitField=16777216,r._settledValueField=t,this._promiseResolved(e,r)},e.settle=function(t){return n.deprecated(".settle()",".reflect()"),new i(t).promise()},e.allSettled=function(t){return new i(t).promise()},e.prototype.settle=function(){return e.settle(this)}}},{"./util":36}],31:[function(t,e,r){"use strict";e.exports=function(e,r,n){var o=t("./util"),i=t("./errors").RangeError,s=t("./errors").AggregateError,a=o.isArray,u={};function c(t){this.constructor$(t),this._howMany=0,this._unwrap=!1,this._initialized=!1}function l(t,e){if((0|e)!==e||e<0)return n("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n");var r=new c(t),o=r.promise();return r.setHowMany(e),r.init(),o}o.inherits(c,r),c.prototype._init=function(){if(this._initialized)if(0!==this._howMany){this._init$(void 0,-5);var t=a(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}else this._resolve([])},c.prototype.init=function(){this._initialized=!0,this._init()},c.prototype.setUnwrap=function(){this._unwrap=!0},c.prototype.howMany=function(){return this._howMany},c.prototype.setHowMany=function(t){this._howMany=t},c.prototype._promiseFulfilled=function(t){return this._addFulfilled(t),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0)},c.prototype._promiseRejected=function(t){return this._addRejected(t),this._checkOutcome()},c.prototype._promiseCancelled=function(){return this._values instanceof e||null==this._values?this._cancel():(this._addRejected(u),this._checkOutcome())},c.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var t=new s,e=this.length();e0?this._reject(t):this._cancel(),!0}return!1},c.prototype._fulfilled=function(){return this._totalResolved},c.prototype._rejected=function(){return this._values.length-this.length()},c.prototype._addRejected=function(t){this._values.push(t)},c.prototype._addFulfilled=function(t){this._values[this._totalResolved++]=t},c.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},c.prototype._getRangeError=function(t){var e="Input array must contain at least "+this._howMany+" items but contains only "+t+" items";return new i(e)},c.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},e.some=function(t,e){return l(t,e)},e.prototype.some=function(t){return l(this,t)},e._SomePromiseArray=c}},{"./errors":12,"./util":36}],32:[function(t,e,r){"use strict";e.exports=function(t){function e(t){void 0!==t?(t=t._target(),this._bitField=t._bitField,this._settledValueField=t._isFateSealed()?t._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}e.prototype._settledValue=function(){return this._settledValueField};var r=e.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},n=e.prototype.error=e.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},o=e.prototype.isFulfilled=function(){return 0!=(33554432&this._bitField)},i=e.prototype.isRejected=function(){return 0!=(16777216&this._bitField)},s=e.prototype.isPending=function(){return 0==(50397184&this._bitField)},a=e.prototype.isResolved=function(){return 0!=(50331648&this._bitField)};e.prototype.isCancelled=function(){return 0!=(8454144&this._bitField)},t.prototype.__isCancelled=function(){return 65536==(65536&this._bitField)},t.prototype._isCancelled=function(){return this._target().__isCancelled()},t.prototype.isCancelled=function(){return 0!=(8454144&this._target()._bitField)},t.prototype.isPending=function(){return s.call(this._target())},t.prototype.isRejected=function(){return i.call(this._target())},t.prototype.isFulfilled=function(){return o.call(this._target())},t.prototype.isResolved=function(){return a.call(this._target())},t.prototype.value=function(){return r.call(this._target())},t.prototype.reason=function(){var t=this._target();return t._unsetRejectionIsUnhandled(),n.call(t)},t.prototype._value=function(){return this._settledValue()},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},t.PromiseInspection=e}},{}],33:[function(t,e,r){"use strict";e.exports=function(e,r){var n=t("./util"),o=n.errorObj,i=n.isObject;var s={}.hasOwnProperty;return function(t,a){if(i(t)){if(t instanceof e)return t;var u=function(t){try{return t.then}catch(t){return o.e=t,o}}(t);if(u===o){a&&a._pushContext();var c=e.reject(u.e);return a&&a._popContext(),c}if("function"==typeof u)return function(t){try{return s.call(t,"_promise0")}catch(t){return!1}}(t)?(c=new e(r),t._then(c._fulfill,c._reject,void 0,c,null),c):function(t,i,s){var a=new e(r),u=a;s&&s._pushContext(),a._captureStackTrace(),s&&s._popContext();var c=!0,l=n.tryCatch(i).call(t,function(t){a&&(a._resolveCallback(t),a=null)},function(t){a&&(a._rejectCallback(t,c,!0),a=null)});return c=!1,a&&l===o&&(a._rejectCallback(l.e,!0,!0),a=null),u}(t,u,a)}return t}}},{"./util":36}],34:[function(t,e,r){"use strict";e.exports=function(e,r,n){var o=t("./util"),i=e.TimeoutError;function s(t){this.handle=t}s.prototype._resultCancelled=function(){clearTimeout(this.handle)};var a=function(t){return u(+this).thenReturn(t)},u=e.delay=function(t,o){var i,u;return void 0!==o?(i=e.resolve(o)._then(a,null,null,t,void 0),n.cancellation()&&o instanceof e&&i._setOnCancel(o)):(i=new e(r),u=setTimeout(function(){i._fulfill()},+t),n.cancellation()&&i._setOnCancel(new s(u)),i._captureStackTrace()),i._setAsyncGuaranteed(),i};e.prototype.delay=function(t){return u(t,this)};function c(t){return clearTimeout(this.handle),t}function l(t){throw clearTimeout(this.handle),t}e.prototype.timeout=function(t,e){var r,a;t=+t;var u=new s(setTimeout(function(){var t,n,s,u;r.isPending()&&(t=r,s=a,u="string"!=typeof(n=e)?n instanceof Error?n:new i("operation timed out"):new i(n),o.markAsOriginatingFromRejection(u),t._attachExtraTrace(u),t._reject(u),null!=s&&s.cancel())},t));return n.cancellation()?(a=this.then(),(r=a._then(c,l,void 0,u,void 0))._setOnCancel(u)):r=this._then(c,l,void 0,u,void 0),r}}},{"./util":36}],35:[function(t,e,r){"use strict";e.exports=function(e,r,n,o,i,s){var a=t("./util"),u=t("./errors").TypeError,c=t("./util").inherits,l=a.errorObj,f=a.tryCatch,p={};function h(t){setTimeout(function(){throw t},0)}function d(t,r){var o=0,s=t.length,a=new e(i);return function i(){if(o>=s)return a._fulfill();var u,c,l=(u=t[o++],(c=n(u))!==u&&"function"==typeof u._isDisposable&&"function"==typeof u._getDisposer&&u._isDisposable()&&c._setDisposable(u._getDisposer()),c);if(l instanceof e&&l._isDisposable()){try{l=n(l._getDisposer().tryDispose(r),t.promise)}catch(t){return h(t)}if(l instanceof e)return l._then(i,h,null,null,null)}i()}(),a}function _(t,e,r){this._data=t,this._promise=e,this._context=r}function v(t,e,r){this.constructor$(t,e,r)}function g(t){return _.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}function y(t){this.length=t,this.promise=null,this[t-1]=null}_.prototype.data=function(){return this._data},_.prototype.promise=function(){return this._promise},_.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():p},_.prototype.tryDispose=function(t){var e=this.resource(),r=this._context;void 0!==r&&r._pushContext();var n=e!==p?this.doDispose(e,t):null;return void 0!==r&&r._popContext(),this._promise._unsetDisposable(),this._data=null,n},_.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},c(v,_),v.prototype.doDispose=function(t,e){return this.data().call(t,t,e)},y.prototype._resultCancelled=function(){for(var t=this.length,r=0;r0},e.prototype._getDisposer=function(){return this._disposer},e.prototype._unsetDisposable=function(){this._bitField=-131073&this._bitField,this._disposer=void 0},e.prototype.disposer=function(t){if("function"==typeof t)return new v(t,this,o());throw new u}}},{"./errors":12,"./util":36}],36:[function(t,r,n){"use strict";var i=t("./es5"),s="undefined"==typeof navigator,a={e:{}},u,c="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==o?o:void 0!==this?this:null;function l(){try{var t=u;return u=null,t.apply(this,arguments)}catch(t){return a.e=t,a}}function f(t){return u=t,l}var p=function(t,e){var r={}.hasOwnProperty;function n(){for(var n in this.constructor=t,this.constructor$=e,e.prototype)r.call(e.prototype,n)&&"$"!==n.charAt(n.length-1)&&(this[n+"$"]=e.prototype[n])}return n.prototype=e.prototype,t.prototype=new n,t.prototype};function h(t){return null==t||!0===t||!1===t||"string"==typeof t||"number"==typeof t}function d(t){return"function"==typeof t||"object"==typeof t&&null!==t}function _(t){return h(t)?new Error(T(t)):t}function v(t,e){var r,n=t.length,o=new Array(n+1);for(r=0;r1,n=e.length>0&&!(1===e.length&&"constructor"===e[0]),o=w.test(t+"")&&i.names(t).length>0;if(r||n||o)return!0}return!1}catch(t){return!1}}function j(t){function e(){}e.prototype=t;var r=new e;function n(){return typeof r.foo}return n(),n(),t}var C=/^[a-z$_][a-z$_0-9]*$/i;function x(t){return C.test(t)}function E(t,e,r){for(var n=new Array(t),o=0;o10||W[0]>0),q.nodeSupportsAsyncResource=q.isNode&&function(){var e=!1;try{var r=t("async_hooks").AsyncResource;e="function"==typeof r.prototype.runInAsyncScope}catch(t){e=!1}return e}(),q.isNode&&q.toFastProperties(e);try{throw new Error}catch(t){q.lastLineError=t}r.exports=q},{"./es5":13,async_hooks:void 0}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("timers").setImmediate)},{_process:91,timers:114}],81:[function(e,r,n){var o,i;o=this,i=function(){var t=XMLHttpRequest;if(!t)throw new Error("missing XMLHttpRequest");e.log={trace:n,debug:n,info:n,warn:n,error:n};function e(i,s){if("function"!=typeof s)throw new Error("Bad callback given: "+s);if(!i)throw new Error("No options given");var a=i.onResponse;if((i="string"==typeof i?{uri:i}:JSON.parse(JSON.stringify(i))).onResponse=a,i.verbose&&(e.log=function(){var t,e,r={},i=["trace","debug","info","warn","error"];for(e=0;e>18&63,i=u>>12&63,s=u>>6&63,a=63&u,h[f++]=c.charAt(o)+c.charAt(i)+c.charAt(s)+c.charAt(a)}while(l299)&&n.error){for(var o in t=new Error("CouchDB error: "+(n.error.reason||n.error.error)),n)t[o]=n[o];return r(t,e,n)}return r(t,e,n)})},e},"function"==typeof t&&t.amd?t([],i):"object"==typeof n?r.exports=i():o.returnExports=i()},{}],82:[function(t,e,r){},{}],83:[function(t,e,r){arguments[4][82][0].apply(r,arguments)},{dup:82}],84:[function(t,e,r){(function(e){"use strict";var n=t("base64-js"),o=t("ieee754");r.Buffer=e,r.SlowBuffer=function(t){+t!=t&&(t=0);return e.alloc(+t)},r.INSPECT_MAX_BYTES=50;var i=2147483647;function s(t){if(t>i)throw new RangeError('The value "'+t+'" is invalid for option "size"');var r=new Uint8Array(t);return r.__proto__=e.prototype,r}function e(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return c(t)}return a(t,e,r)}function a(t,r,n){if("string"==typeof t)return function(t,r){"string"==typeof r&&""!==r||(r="utf8");if(!e.isEncoding(r))throw new TypeError("Unknown encoding: "+r);var n=0|p(t,r),o=s(n),i=o.write(t,r);i!==n&&(o=o.slice(0,i));return o}(t,r);if(ArrayBuffer.isView(t))return l(t);if(null==t)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(I(t,ArrayBuffer)||t&&I(t.buffer,ArrayBuffer))return function(t,r,n){if(r<0||t.byteLength=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|t}function p(t,r){if(e.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||I(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var n=t.length,o=arguments.length>2&&!0===arguments[2];if(!o&&0===n)return 0;for(var i=!1;;)switch(r){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return O(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return R(t).length;default:if(i)return o?-1:O(t).length;r=(""+r).toLowerCase(),i=!0}}function h(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function d(t,r,n,o,i){if(0===t.length)return-1;if("string"==typeof n?(o=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),B(n=+n)&&(n=i?0:t.length-1),n<0&&(n=t.length+n),n>=t.length){if(i)return-1;n=t.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof r&&(r=e.from(r,o)),e.isBuffer(r))return 0===r.length?-1:_(t,r,n,o,i);if("number"==typeof r)return r&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,r,n):Uint8Array.prototype.lastIndexOf.call(t,r,n):_(t,[r],n,o,i);throw new TypeError("val must be string, number or Buffer")}function _(t,e,r,n,o){var i,s=1,a=t.length,u=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,a/=2,u/=2,r/=2}function c(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(o){var l=-1;for(i=r;ia&&(r=a-u),i=r;i>=0;i--){for(var f=!0,p=0;po&&(n=o):n=o;var i=e.length;n>i/2&&(n=i/2);for(var s=0;s239?4:c>223?3:c>191?2:1;if(o+f<=r)switch(f){case 1:c<128&&(l=c);break;case 2:128==(192&(i=t[o+1]))&&(u=(31&c)<<6|63&i)>127&&(l=u);break;case 3:i=t[o+1],s=t[o+2],128==(192&i)&&128==(192&s)&&(u=(15&c)<<12|(63&i)<<6|63&s)>2047&&(u<55296||u>57343)&&(l=u);break;case 4:i=t[o+1],s=t[o+2],a=t[o+3],128==(192&i)&&128==(192&s)&&128==(192&a)&&(u=(15&c)<<18|(63&i)<<12|(63&s)<<6|63&a)>65535&&u<1114112&&(l=u)}null===l?(l=65533,f=1):l>65535&&(l-=65536,n.push(l>>>10&1023|55296),l=56320|1023&l),n.push(l),o+=f}return function(t){var e=t.length;if(e<=b)return String.fromCharCode.apply(String,t);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return j(this,e,r);case"utf8":case"utf-8":return m(this,e,r);case"ascii":return w(this,e,r);case"latin1":case"binary":return k(this,e,r);case"base64":return y(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},e.prototype.toLocaleString=e.prototype.toString,e.prototype.equals=function(t){if(!e.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===e.compare(this,t)},e.prototype.inspect=function(){var t="",e=r.INSPECT_MAX_BYTES;return t=this.toString("hex",0,e).replace(/(.{2})/g,"$1 ").trim(),this.length>e&&(t+=" ... "),""},e.prototype.compare=function(t,r,n,o,i){if(I(t,Uint8Array)&&(t=e.from(t,t.offset,t.byteLength)),!e.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===r&&(r=0),void 0===n&&(n=t?t.length:0),void 0===o&&(o=0),void 0===i&&(i=this.length),r<0||n>t.length||o<0||i>this.length)throw new RangeError("out of range index");if(o>=i&&r>=n)return 0;if(o>=i)return-1;if(r>=n)return 1;if(r>>>=0,n>>>=0,o>>>=0,i>>>=0,this===t)return 0;for(var s=i-o,a=n-r,u=Math.min(s,a),c=this.slice(o,i),l=t.slice(r,n),f=0;f>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var o=this.length-e;if((void 0===r||r>o)&&(r=o),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i,s,a,u,c,l,f,p,h,d=!1;;)switch(n){case"hex":return v(this,t,e,r);case"utf8":case"utf-8":return p=e,h=r,U(O(t,(f=this).length-p),f,p,h);case"ascii":return g(this,t,e,r);case"latin1":case"binary":return g(this,t,e,r);case"base64":return u=this,c=e,l=r,U(R(t),u,c,l);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return s=e,a=r,U(function(t,e){for(var r,n,o,i=[],s=0;s>8,o=r%256,i.push(o),i.push(n);return i}(t,(i=this).length-s),i,s,a);default:if(d)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),d=!0}},e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var b=4096;function w(t,e,r){var n="";r=Math.min(t.length,r);for(var o=e;on)&&(r=n);for(var o="",i=e;ir)throw new RangeError("Trying to access beyond buffer length")}function E(t,r,n,o,i,s){if(!e.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(r>i||rt.length)throw new RangeError("Index out of range")}function T(t,e,r,n,o,i){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function S(t,e,r,n,i){return e=+e,r>>>=0,i||T(t,0,r,4),o.write(t,e,r,n,23,4),r+4}function P(t,e,r,n,i){return e=+e,r>>>=0,i||T(t,0,r,8),o.write(t,e,r,n,52,8),r+8}e.prototype.slice=function(t,r){var n=this.length;t=~~t,r=void 0===r?n:~~r,t<0?(t+=n)<0&&(t=0):t>n&&(t=n),r<0?(r+=n)<0&&(r=0):r>n&&(r=n),r>>=0,e>>>=0,r||x(t,e,this.length);for(var n=this[t],o=1,i=0;++i>>=0,e>>>=0,r||x(t,e,this.length);for(var n=this[t+--e],o=1;e>0&&(o*=256);)n+=this[t+--e]*o;return n},e.prototype.readUInt8=function(t,e){return t>>>=0,e||x(t,1,this.length),this[t]},e.prototype.readUInt16LE=function(t,e){return t>>>=0,e||x(t,2,this.length),this[t]|this[t+1]<<8},e.prototype.readUInt16BE=function(t,e){return t>>>=0,e||x(t,2,this.length),this[t]<<8|this[t+1]},e.prototype.readUInt32LE=function(t,e){return t>>>=0,e||x(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},e.prototype.readUInt32BE=function(t,e){return t>>>=0,e||x(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},e.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||x(t,e,this.length);for(var n=this[t],o=1,i=0;++i=(o*=128)&&(n-=Math.pow(2,8*e)),n},e.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||x(t,e,this.length);for(var n=e,o=1,i=this[t+--n];n>0&&(o*=256);)i+=this[t+--n]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*e)),i},e.prototype.readInt8=function(t,e){return t>>>=0,e||x(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},e.prototype.readInt16LE=function(t,e){t>>>=0,e||x(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},e.prototype.readInt16BE=function(t,e){t>>>=0,e||x(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},e.prototype.readInt32LE=function(t,e){return t>>>=0,e||x(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},e.prototype.readInt32BE=function(t,e){return t>>>=0,e||x(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},e.prototype.readFloatLE=function(t,e){return t>>>=0,e||x(t,4,this.length),o.read(this,t,!0,23,4)},e.prototype.readFloatBE=function(t,e){return t>>>=0,e||x(t,4,this.length),o.read(this,t,!1,23,4)},e.prototype.readDoubleLE=function(t,e){return t>>>=0,e||x(t,8,this.length),o.read(this,t,!0,52,8)},e.prototype.readDoubleBE=function(t,e){return t>>>=0,e||x(t,8,this.length),o.read(this,t,!1,52,8)},e.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e>>>=0,r>>>=0,n)||E(this,t,e,r,Math.pow(2,8*r)-1,0);var o=1,i=0;for(this[e]=255&t;++i>>=0,r>>>=0,n)||E(this,t,e,r,Math.pow(2,8*r)-1,0);var o=r-1,i=1;for(this[e+o]=255&t;--o>=0&&(i*=256);)this[e+o]=t/i&255;return e+r},e.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||E(this,t,e,1,255,0),this[e]=255&t,e+1},e.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||E(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},e.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||E(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},e.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||E(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},e.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||E(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},e.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var o=Math.pow(2,8*r-1);E(this,t,e,r,o-1,-o)}var i=0,s=1,a=0;for(this[e]=255&t;++i>0)-a&255;return e+r},e.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var o=Math.pow(2,8*r-1);E(this,t,e,r,o-1,-o)}var i=r-1,s=1,a=0;for(this[e+i]=255&t;--i>=0&&(s*=256);)t<0&&0===a&&0!==this[e+i+1]&&(a=1),this[e+i]=(t/s>>0)-a&255;return e+r},e.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||E(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},e.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||E(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},e.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||E(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},e.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||E(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},e.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||E(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},e.prototype.writeFloatLE=function(t,e,r){return S(this,t,e,!0,r)},e.prototype.writeFloatBE=function(t,e,r){return S(this,t,e,!1,r)},e.prototype.writeDoubleLE=function(t,e,r){return P(this,t,e,!0,r)},e.prototype.writeDoubleBE=function(t,e,r){return P(this,t,e,!1,r)},e.prototype.copy=function(t,r,n,o){if(!e.isBuffer(t))throw new TypeError("argument should be a Buffer");if(n||(n=0),o||0===o||(o=this.length),r>=t.length&&(r=t.length),r||(r=0),o>0&&o=this.length)throw new RangeError("Index out of range");if(o<0)throw new RangeError("sourceEnd out of bounds");o>this.length&&(o=this.length),t.length-r=0;--s)t[s+r]=this[s+n];else Uint8Array.prototype.set.call(t,this.subarray(n,o),r);return i},e.prototype.fill=function(t,r,n,o){if("string"==typeof t){if("string"==typeof r?(o=r,r=0,n=this.length):"string"==typeof n&&(o=n,n=this.length),void 0!==o&&"string"!=typeof o)throw new TypeError("encoding must be a string");if("string"==typeof o&&!e.isEncoding(o))throw new TypeError("Unknown encoding: "+o);if(1===t.length){var i=t.charCodeAt(0);("utf8"===o&&i<128||"latin1"===o)&&(t=i)}}else"number"==typeof t&&(t&=255);if(r<0||this.length>>=0,n=void 0===n?this.length:n>>>0,t||(t=0),"number"==typeof t)for(s=r;s55295&&r<57344){if(!o){if(r>56319){(e-=3)>-1&&i.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(e-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(e-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((e-=1)<0)break;i.push(r)}else if(r<2048){if((e-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function R(t){return n.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(F,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function U(t,e,r,n){for(var o=0;o=e.length||o>=t.length);++o)e[o+r]=t[o];return o}function I(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function B(t){return t!=t}}).call(this,t("buffer").Buffer)},{"base64-js":79,buffer:84,ieee754:87}],85:[function(t,e,r){(function(t){function e(t){return Object.prototype.toString.call(t)}r.isArray=function(t){return Array.isArray?Array.isArray(t):"[object Array]"===e(t)},r.isBoolean=function(t){return"boolean"==typeof t},r.isNull=function(t){return null===t},r.isNullOrUndefined=function(t){return null==t},r.isNumber=function(t){return"number"==typeof t},r.isString=function(t){return"string"==typeof t},r.isSymbol=function(t){return"symbol"==typeof t},r.isUndefined=function(t){return void 0===t},r.isRegExp=function(t){return"[object RegExp]"===e(t)},r.isObject=function(t){return"object"==typeof t&&null!==t},r.isDate=function(t){return"[object Date]"===e(t)},r.isError=function(t){return"[object Error]"===e(t)||t instanceof Error},r.isFunction=function(t){return"function"==typeof t},r.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t},r.isBuffer=t.isBuffer}).call(this,{isBuffer:t("../../is-buffer/index.js")})},{"../../is-buffer/index.js":89}],86:[function(t,e,r){var n=Object.create||function(t){var e=function(){};return e.prototype=t,new e},o=Object.keys||function(t){var e=[];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.push(r);return r},i=Function.prototype.bind||function(t){var e=this;return function(){return e.apply(t,arguments)}};function s(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=n(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}e.exports=s,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._maxListeners=void 0;var a,u=10;try{var c={};Object.defineProperty&&Object.defineProperty(c,"x",{value:0}),a=0===c.x}catch(t){a=!1}function l(t){return void 0===t._maxListeners?s.defaultMaxListeners:t._maxListeners}function f(t,e,r,o){var i,s,a;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((s=t._events)?(s.newListener&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),a=s[e]):(s=t._events=n(null),t._eventsCount=0),a){if("function"==typeof a?a=s[e]=o?[r,a]:[a,r]:o?a.unshift(r):a.push(r),!a.warned&&(i=l(t))&&i>0&&a.length>i){a.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+a.length+' "'+String(e)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');u.name="MaxListenersExceededWarning",u.emitter=t,u.type=e,u.count=a.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",u.name,u.message)}}else a=s[e]=r,++t._eventsCount;return t}function p(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var t=new Array(arguments.length),e=0;e1&&(e=arguments[1]),e instanceof Error)throw e;var u=new Error('Unhandled "error" event. ('+e+")");throw u.context=e,u}if(!(r=s[t]))return!1;var c="function"==typeof r;switch(n=arguments.length){case 1:!function(t,e,r){if(e)t.call(r);else for(var n=t.length,o=v(t,n),i=0;i=0;s--)if(r[s]===e||r[s].listener===e){a=r[s].listener,i=s;break}if(i<0)return this;0===i?r.shift():function(t,e){for(var r=e,n=r+1,o=t.length;n=0;i--)this.removeListener(t,e[i]);return this},s.prototype.listeners=function(t){return d(this,t,!0)},s.prototype.rawListeners=function(t){return d(this,t,!1)},s.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):_.call(t,e)},s.prototype.listenerCount=_,s.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],87:[function(t,e,r){r.read=function(t,e,r,n,o){var i,s,a=8*o-n-1,u=(1<>1,l=-7,f=r?o-1:0,p=r?-1:1,h=t[e+f];for(f+=p,i=h&(1<<-l)-1,h>>=-l,l+=a;l>0;i=256*i+t[e+f],f+=p,l-=8);for(s=i&(1<<-l)-1,i>>=-l,l+=n;l>0;s=256*s+t[e+f],f+=p,l-=8);if(0===i)i=1-c;else{if(i===u)return s?NaN:1/0*(h?-1:1);s+=Math.pow(2,n),i-=c}return(h?-1:1)*s*Math.pow(2,i-n)},r.write=function(t,e,r,n,o,i){var s,a,u,c=8*i-o-1,l=(1<>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:i-1,d=n?1:-1,_=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=l):(s=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-s))<1&&(s--,u*=2),(e+=s+f>=1?p/u:p*Math.pow(2,1-f))*u>=2&&(s++,u/=2),s+f>=l?(a=0,s=l):s+f>=1?(a=(e*u-1)*Math.pow(2,o),s+=f):(a=e*Math.pow(2,f-1)*Math.pow(2,o),s=0));o>=8;t[r+h]=255&a,h+=d,a/=256,o-=8);for(s=s<0;t[r+h]=255&s,h+=d,s/=256,c-=8);t[r+h-d]|=128*_}},{}],88:[function(t,e,r){"function"==typeof Object.create?e.exports=function(t,e){t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:e.exports=function(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}},{}],89:[function(t,e,r){function n(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}e.exports=function(t){return null!=t&&(n(t)||"function"==typeof(e=t).readFloatLE&&"function"==typeof e.slice&&n(e.slice(0,0))||!!t._isBuffer);var e}},{}],90:[function(e,r,n){(function(e){(function(){var o,i=200,s="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",a="Expected a function",u="__lodash_hash_undefined__",c=500,l="__lodash_placeholder__",f=1,p=2,h=4,d=1,_=2,v=1,g=2,y=4,m=8,b=16,w=32,k=64,j=128,C=256,x=512,E=30,T="...",S=800,P=16,F=1,A=2,O=1/0,R=9007199254740991,U=1.7976931348623157e308,I=NaN,B=4294967295,L=B-1,M=B>>>1,D=[["ary",j],["bind",v],["bindKey",g],["curry",m],["curryRight",b],["flip",x],["partial",w],["partialRight",k],["rearg",C]],N="[object Arguments]",z="[object Array]",G="[object AsyncFunction]",q="[object Boolean]",W="[object Date]",H="[object DOMException]",V="[object Error]",$="[object Function]",J="[object GeneratorFunction]",Q="[object Map]",X="[object Number]",K="[object Null]",Z="[object Object]",Y="[object Promise]",tt="[object Proxy]",et="[object RegExp]",rt="[object Set]",nt="[object String]",ot="[object Symbol]",it="[object Undefined]",st="[object WeakMap]",at="[object WeakSet]",ut="[object ArrayBuffer]",ct="[object DataView]",lt="[object Float32Array]",ft="[object Float64Array]",pt="[object Int8Array]",ht="[object Int16Array]",dt="[object Int32Array]",_t="[object Uint8Array]",vt="[object Uint8ClampedArray]",gt="[object Uint16Array]",yt="[object Uint32Array]",mt=/\b__p \+= '';/g,bt=/\b(__p \+=) '' \+/g,wt=/(__e\(.*?\)|\b__t\)) \+\n'';/g,kt=/&(?:amp|lt|gt|quot|#39);/g,jt=/[&<>"']/g,Ct=RegExp(kt.source),xt=RegExp(jt.source),Et=/<%-([\s\S]+?)%>/g,Tt=/<%([\s\S]+?)%>/g,St=/<%=([\s\S]+?)%>/g,Pt=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ft=/^\w*$/,At=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Ot=/[\\^$.*+?()[\]{}|]/g,Rt=RegExp(Ot.source),Ut=/^\s+|\s+$/g,It=/^\s+/,Bt=/\s+$/,Lt=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Mt=/\{\n\/\* \[wrapped with (.+)\] \*/,Dt=/,? & /,Nt=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,zt=/\\(\\)?/g,Gt=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,qt=/\w*$/,Wt=/^[-+]0x[0-9a-f]+$/i,Ht=/^0b[01]+$/i,Vt=/^\[object .+?Constructor\]$/,$t=/^0o[0-7]+$/i,Jt=/^(?:0|[1-9]\d*)$/,Qt=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Xt=/($^)/,Kt=/['\n\r\u2028\u2029\\]/g,Zt="\\ud800-\\udfff",Yt="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",te="\\u2700-\\u27bf",ee="a-z\\xdf-\\xf6\\xf8-\\xff",re="A-Z\\xc0-\\xd6\\xd8-\\xde",ne="\\ufe0e\\ufe0f",oe="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",ie="["+Zt+"]",se="["+oe+"]",ae="["+Yt+"]",ue="\\d+",ce="["+te+"]",le="["+ee+"]",fe="[^"+Zt+oe+ue+te+ee+re+"]",pe="\\ud83c[\\udffb-\\udfff]",he="[^"+Zt+"]",de="(?:\\ud83c[\\udde6-\\uddff]){2}",_e="[\\ud800-\\udbff][\\udc00-\\udfff]",ve="["+re+"]",ge="(?:"+le+"|"+fe+")",ye="(?:"+ve+"|"+fe+")",me="(?:['’](?:d|ll|m|re|s|t|ve))?",be="(?:['’](?:D|LL|M|RE|S|T|VE))?",we="(?:"+ae+"|"+pe+")"+"?",ke="["+ne+"]?",je=ke+we+("(?:\\u200d(?:"+[he,de,_e].join("|")+")"+ke+we+")*"),Ce="(?:"+[ce,de,_e].join("|")+")"+je,xe="(?:"+[he+ae+"?",ae,de,_e,ie].join("|")+")",Ee=RegExp("['’]","g"),Te=RegExp(ae,"g"),Se=RegExp(pe+"(?="+pe+")|"+xe+je,"g"),Pe=RegExp([ve+"?"+le+"+"+me+"(?="+[se,ve,"$"].join("|")+")",ye+"+"+be+"(?="+[se,ve+ge,"$"].join("|")+")",ve+"?"+ge+"+"+me,ve+"+"+be,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",ue,Ce].join("|"),"g"),Fe=RegExp("[\\u200d"+Zt+Yt+ne+"]"),Ae=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Oe=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Re=-1,Ue={};Ue[lt]=Ue[ft]=Ue[pt]=Ue[ht]=Ue[dt]=Ue[_t]=Ue[vt]=Ue[gt]=Ue[yt]=!0,Ue[N]=Ue[z]=Ue[ut]=Ue[q]=Ue[ct]=Ue[W]=Ue[V]=Ue[$]=Ue[Q]=Ue[X]=Ue[Z]=Ue[et]=Ue[rt]=Ue[nt]=Ue[st]=!1;var Ie={};Ie[N]=Ie[z]=Ie[ut]=Ie[ct]=Ie[q]=Ie[W]=Ie[lt]=Ie[ft]=Ie[pt]=Ie[ht]=Ie[dt]=Ie[Q]=Ie[X]=Ie[Z]=Ie[et]=Ie[rt]=Ie[nt]=Ie[ot]=Ie[_t]=Ie[vt]=Ie[gt]=Ie[yt]=!0,Ie[V]=Ie[$]=Ie[st]=!1;var Be={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Le=parseFloat,Me=parseInt,De="object"==typeof e&&e&&e.Object===Object&&e,Ne="object"==typeof self&&self&&self.Object===Object&&self,ze=De||Ne||Function("return this")(),Ge="object"==typeof n&&n&&!n.nodeType&&n,qe=Ge&&"object"==typeof r&&r&&!r.nodeType&&r,We=qe&&qe.exports===Ge,He=We&&De.process,Ve=function(){try{var t=qe&&qe.require&&qe.require("util").types;return t||He&&He.binding&&He.binding("util")}catch(t){}}(),$e=Ve&&Ve.isArrayBuffer,Je=Ve&&Ve.isDate,Qe=Ve&&Ve.isMap,Xe=Ve&&Ve.isRegExp,Ke=Ve&&Ve.isSet,Ze=Ve&&Ve.isTypedArray;function Ye(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}function tr(t,e,r,n){for(var o=-1,i=null==t?0:t.length;++o-1}function sr(t,e,r){for(var n=-1,o=null==t?0:t.length;++n-1;);return r}function Sr(t,e){for(var r=t.length;r--&&_r(e,t[r],0)>-1;);return r}var Pr=br({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"}),Fr=br({"&":"&","<":"<",">":">",'"':""","'":"'"});function Ar(t){return"\\"+Be[t]}function Or(t){return Fe.test(t)}function Rr(t){var e=-1,r=Array(t.size);return t.forEach(function(t,n){r[++e]=[n,t]}),r}function Ur(t,e){return function(r){return t(e(r))}}function Ir(t,e){for(var r=-1,n=t.length,o=0,i=[];++r",""":'"',"'":"'"});var Nr=function t(e){var r,n=(e=null==e?ze:Nr.defaults(ze.Object(),e,Nr.pick(ze,Oe))).Array,Zt=e.Date,Yt=e.Error,te=e.Function,ee=e.Math,re=e.Object,ne=e.RegExp,oe=e.String,ie=e.TypeError,se=n.prototype,ae=te.prototype,ue=re.prototype,ce=e["__core-js_shared__"],le=ae.toString,fe=ue.hasOwnProperty,pe=0,he=(r=/[^.]+$/.exec(ce&&ce.keys&&ce.keys.IE_PROTO||""))?"Symbol(src)_1."+r:"",de=ue.toString,_e=le.call(re),ve=ze._,ge=ne("^"+le.call(fe).replace(Ot,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ye=We?e.Buffer:o,me=e.Symbol,be=e.Uint8Array,we=ye?ye.allocUnsafe:o,ke=Ur(re.getPrototypeOf,re),je=re.create,Ce=ue.propertyIsEnumerable,xe=se.splice,Se=me?me.isConcatSpreadable:o,Fe=me?me.iterator:o,Be=me?me.toStringTag:o,De=function(){try{var t=Di(re,"defineProperty");return t({},"",{}),t}catch(t){}}(),Ne=e.clearTimeout!==ze.clearTimeout&&e.clearTimeout,Ge=Zt&&Zt.now!==ze.Date.now&&Zt.now,qe=e.setTimeout!==ze.setTimeout&&e.setTimeout,He=ee.ceil,Ve=ee.floor,pr=re.getOwnPropertySymbols,br=ye?ye.isBuffer:o,zr=e.isFinite,Gr=se.join,qr=Ur(re.keys,re),Wr=ee.max,Hr=ee.min,Vr=Zt.now,$r=e.parseInt,Jr=ee.random,Qr=se.reverse,Xr=Di(e,"DataView"),Kr=Di(e,"Map"),Zr=Di(e,"Promise"),Yr=Di(e,"Set"),tn=Di(e,"WeakMap"),en=Di(re,"create"),rn=tn&&new tn,nn={},on=hs(Xr),sn=hs(Kr),an=hs(Zr),un=hs(Yr),cn=hs(tn),ln=me?me.prototype:o,fn=ln?ln.valueOf:o,pn=ln?ln.toString:o;function hn(t){if(Fa(t)&&!ma(t)&&!(t instanceof gn)){if(t instanceof vn)return t;if(fe.call(t,"__wrapped__"))return ds(t)}return new vn(t)}var dn=function(){function t(){}return function(e){if(!Pa(e))return{};if(je)return je(e);t.prototype=e;var r=new t;return t.prototype=o,r}}();function _n(){}function vn(t,e){this.__wrapped__=t,this.__actions__=[],this.__chain__=!!e,this.__index__=0,this.__values__=o}function gn(t){this.__wrapped__=t,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=B,this.__views__=[]}function yn(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e=e?t:e)),t}function In(t,e,r,n,i,s){var a,u=e&f,c=e&p,l=e&h;if(r&&(a=i?r(t,n,i,s):r(t)),a!==o)return a;if(!Pa(t))return t;var d,_,v,g,y,m,b,w,k,j=ma(t);if(j){if(w=(b=t).length,k=new b.constructor(w),w&&"string"==typeof b[0]&&fe.call(b,"index")&&(k.index=b.index,k.input=b.input),a=k,!u)return ni(t,a)}else{var C=Gi(t),x=C==$||C==J;if(ja(t))return Ko(t,u);if(C==Z||C==N||x&&!i){if(a=c||x?{}:Wi(t),!u)return c?(v=t,m=t,g=(y=a)&&oi(m,au(m),y),oi(v,zi(v),g)):(d=t,_=An(a,t),oi(d,Ni(d),_))}else{if(!Ie[C])return i?t:{};a=function(t,e,r){var n,o,i,s,a,u=t.constructor;switch(e){case ut:return Zo(t);case q:case W:return new u(+t);case ct:return s=t,a=r?Zo(s.buffer):s.buffer,new s.constructor(a,s.byteOffset,s.byteLength);case lt:case ft:case pt:case ht:case dt:case _t:case vt:case gt:case yt:return Yo(t,r);case Q:return new u;case X:case nt:return new u(t);case et:return(i=new(o=t).constructor(o.source,qt.exec(o))).lastIndex=o.lastIndex,i;case rt:return new u;case ot:return n=t,fn?re(fn.call(n)):{}}}(t,C,u)}}s||(s=new kn);var E=s.get(t);if(E)return E;s.set(t,a),Ia(t)?t.forEach(function(n){a.add(In(n,e,r,n,t,s))}):Aa(t)&&t.forEach(function(n,o){a.set(o,In(n,e,r,o,t,s))});var T=j?o:(l?c?Oi:Ai:c?au:su)(t);return er(T||t,function(n,o){T&&(n=t[o=n]),Sn(a,o,In(n,e,r,o,t,s))}),a}function Bn(t,e,r){var n=r.length;if(null==t)return!n;for(t=re(t);n--;){var i=r[n],s=e[i],a=t[i];if(a===o&&!(i in t)||!s(a))return!1}return!0}function Ln(t,e,r){if("function"!=typeof t)throw new ie(a);return os(function(){t.apply(o,r)},e)}function Mn(t,e,r,n){var o=-1,s=ir,a=!0,u=t.length,c=[],l=e.length;if(!u)return c;r&&(e=ar(e,Cr(r))),n?(s=sr,a=!1):e.length>=i&&(s=Er,a=!1,e=new wn(e));t:for(;++o-1},mn.prototype.set=function(t,e){var r=this.__data__,n=Pn(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this},bn.prototype.clear=function(){this.size=0,this.__data__={hash:new yn,map:new(Kr||mn),string:new yn}},bn.prototype.delete=function(t){var e=Li(this,t).delete(t);return this.size-=e?1:0,e},bn.prototype.get=function(t){return Li(this,t).get(t)},bn.prototype.has=function(t){return Li(this,t).has(t)},bn.prototype.set=function(t,e){var r=Li(this,t),n=r.size;return r.set(t,e),this.size+=r.size==n?0:1,this},wn.prototype.add=wn.prototype.push=function(t){return this.__data__.set(t,u),this},wn.prototype.has=function(t){return this.__data__.has(t)},kn.prototype.clear=function(){this.__data__=new mn,this.size=0},kn.prototype.delete=function(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r},kn.prototype.get=function(t){return this.__data__.get(t)},kn.prototype.has=function(t){return this.__data__.has(t)},kn.prototype.set=function(t,e){var r=this.__data__;if(r instanceof mn){var n=r.__data__;if(!Kr||n.length0&&r(a)?e>1?Wn(a,e-1,r,n,o):ur(o,a):n||(o[o.length]=a)}return o}var Hn=ui(),Vn=ui(!0);function $n(t,e){return t&&Hn(t,e,su)}function Jn(t,e){return t&&Vn(t,e,su)}function Qn(t,e){return or(e,function(e){return Ea(t[e])})}function Xn(t,e){for(var r=0,n=(e=$o(e,t)).length;null!=t&&re}function to(t,e){return null!=t&&fe.call(t,e)}function eo(t,e){return null!=t&&e in re(t)}function ro(t,e,r){for(var i=r?sr:ir,s=t[0].length,a=t.length,u=a,c=n(a),l=1/0,f=[];u--;){var p=t[u];u&&e&&(p=ar(p,Cr(e))),l=Hr(p.length,l),c[u]=!r&&(e||s>=120&&p.length>=120)?new wn(u&&p):o}p=t[0];var h=-1,d=c[0];t:for(;++h=a)return u;var c=r[n];return u*("desc"==c?-1:1)}}return t.index-e.index}(t,e,r)})}function mo(t,e,r){for(var n=-1,o=e.length,i={};++n-1;)a!==t&&xe.call(a,u,1),xe.call(t,u,1);return t}function wo(t,e){for(var r=t?e.length:0,n=r-1;r--;){var o=e[r];if(r==n||o!==i){var i=o;Vi(o)?xe.call(t,o,1):Do(t,o)}}return t}function ko(t,e){return t+Ve(Jr()*(e-t+1))}function jo(t,e){var r="";if(!t||e<1||e>R)return r;do{e%2&&(r+=t),(e=Ve(e/2))&&(t+=t)}while(e);return r}function Co(t,e){return is(ts(t,e,Ou),t+"")}function xo(t){return Cn(_u(t))}function Eo(t,e){var r=_u(t);return us(r,Un(e,0,r.length))}function To(t,e,r,n){if(!Pa(t))return t;for(var i=-1,s=(e=$o(e,t)).length,a=s-1,u=t;null!=u&&++ii?0:i+e),(r=r>i?i:r)<0&&(r+=i),i=e>r?0:r-e>>>0,e>>>=0;for(var s=n(i);++o>>1,s=t[i];null!==s&&!La(s)&&(r?s<=e:s=i){var l=e?null:ji(t);if(l)return Br(l);a=!1,o=Er,c=new wn}else c=e?[]:u;t:for(;++n=n?t:Ao(t,e,r)}var Xo=Ne||function(t){return ze.clearTimeout(t)};function Ko(t,e){if(e)return t.slice();var r=t.length,n=we?we(r):new t.constructor(r);return t.copy(n),n}function Zo(t){var e=new t.constructor(t.byteLength);return new be(e).set(new be(t)),e}function Yo(t,e){var r=e?Zo(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.length)}function ti(t,e){if(t!==e){var r=t!==o,n=null===t,i=t==t,s=La(t),a=e!==o,u=null===e,c=e==e,l=La(e);if(!u&&!l&&!s&&t>e||s&&a&&c&&!u&&!l||n&&a&&c||!r&&c||!i)return 1;if(!n&&!s&&!l&&t1?r[i-1]:o,a=i>2?r[2]:o;for(s=t.length>3&&"function"==typeof s?(i--,s):o,a&&$i(r[0],r[1],a)&&(s=i<3?o:s,i=1),e=re(e);++n-1?i[s?e[a]:a]:o}}function hi(t){return Fi(function(e){var r=e.length,n=r,i=vn.prototype.thru;for(t&&e.reverse();n--;){var s=e[n];if("function"!=typeof s)throw new ie(a);if(i&&!u&&"wrapper"==Ui(s))var u=new vn([],!0)}for(n=u?n:r;++n1&&m.reverse(),p&&lu))return!1;var l=s.get(t),f=s.get(e);if(l&&f)return l==e&&f==t;var p=-1,h=!0,v=r&_?new wn:o;for(s.set(t,e),s.set(e,t);++p-1&&t%1==0&&t1?"& ":"")+e[n],e=e.join(r>2?", ":" "),t.replace(Lt,"{\n/* [wrapped with "+e+"] */\n")}(s,(i=s.match(Mt),n=i?i[1].split(Dt):[],o=r,er(D,function(t){var e="_."+t[0];o&t[1]&&!ir(n,e)&&n.push(e)}),n.sort())))}function as(t){var e=0,r=0;return function(){var n=Vr(),i=P-(n-r);if(r=n,i>0){if(++e>=S)return arguments[0]}else e=0;return t.apply(o,arguments)}}function us(t,e){var r=-1,n=t.length,i=n-1;for(e=e===o?n:e;++r1?t[e-1]:o;return Us(t,r="function"==typeof r?(t.pop(),r):o)});function zs(t){var e=hn(t);return e.__chain__=!0,e}function Gs(t,e){return e(t)}var qs=Fi(function(t){var e=t.length,r=e?t[0]:0,n=this.__wrapped__,i=function(e){return Rn(e,t)};return!(e>1||this.__actions__.length)&&n instanceof gn&&Vi(r)?((n=n.slice(r,+r+(e?1:0))).__actions__.push({func:Gs,args:[i],thisArg:o}),new vn(n,this.__chain__).thru(function(t){return e&&!t.length&&t.push(o),t})):this.thru(i)});var Ws=ii(function(t,e,r){fe.call(t,r)?++t[r]:On(t,r,1)});var Hs=pi(ys),Vs=pi(ms);function $s(t,e){return(ma(t)?er:Dn)(t,Bi(e,3))}function Js(t,e){return(ma(t)?rr:Nn)(t,Bi(e,3))}var Qs=ii(function(t,e,r){fe.call(t,r)?t[r].push(e):On(t,r,[e])});var Xs=Co(function(t,e,r){var o=-1,i="function"==typeof e,s=wa(t)?n(t.length):[];return Dn(t,function(t){s[++o]=i?Ye(e,t,r):no(t,e,r)}),s}),Ks=ii(function(t,e,r){On(t,r,e)});function Zs(t,e){return(ma(t)?ar:po)(t,Bi(e,3))}var Ys=ii(function(t,e,r){t[r?0:1].push(e)},function(){return[[],[]]});var ta=Co(function(t,e){if(null==t)return[];var r=e.length;return r>1&&$i(t,e[0],e[1])?e=[]:r>2&&$i(e[0],e[1],e[2])&&(e=[e[0]]),yo(t,Wn(e,1),[])}),ea=Ge||function(){return ze.Date.now()};function ra(t,e,r){return e=r?o:e,e=t&&null==e?t.length:e,xi(t,j,o,o,o,o,e)}function na(t,e){var r;if("function"!=typeof e)throw new ie(a);return t=qa(t),function(){return--t>0&&(r=e.apply(this,arguments)),t<=1&&(e=o),r}}var oa=Co(function(t,e,r){var n=v;if(r.length){var o=Ir(r,Ii(oa));n|=w}return xi(t,n,e,r,o)}),ia=Co(function(t,e,r){var n=v|g;if(r.length){var o=Ir(r,Ii(ia));n|=w}return xi(e,n,t,r,o)});function sa(t,e,r){var n,i,s,u,c,l,f=0,p=!1,h=!1,d=!0;if("function"!=typeof t)throw new ie(a);function _(e){var r=n,s=i;return n=i=o,f=e,u=t.apply(s,r)}function v(t){var r=t-l;return l===o||r>=e||r<0||h&&t-f>=s}function g(){var t,r,n=ea();if(v(n))return y(n);c=os(g,(r=e-((t=n)-l),h?Hr(r,s-(t-f)):r))}function y(t){return c=o,d&&n?_(t):(n=i=o,u)}function m(){var t,r=ea(),s=v(r);if(n=arguments,i=this,l=r,s){if(c===o)return f=t=l,c=os(g,e),p?_(t):u;if(h)return Xo(c),c=os(g,e),_(l)}return c===o&&(c=os(g,e)),u}return e=Ha(e)||0,Pa(r)&&(p=!!r.leading,s=(h="maxWait"in r)?Wr(Ha(r.maxWait)||0,e):s,d="trailing"in r?!!r.trailing:d),m.cancel=function(){c!==o&&Xo(c),f=0,n=l=i=c=o},m.flush=function(){return c===o?u:y(ea())},m}var aa=Co(function(t,e){return Ln(t,1,e)}),ua=Co(function(t,e,r){return Ln(t,Ha(e)||0,r)});function ca(t,e){if("function"!=typeof t||null!=e&&"function"!=typeof e)throw new ie(a);var r=function(){var n=arguments,o=e?e.apply(this,n):n[0],i=r.cache;if(i.has(o))return i.get(o);var s=t.apply(this,n);return r.cache=i.set(o,s)||i,s};return r.cache=new(ca.Cache||bn),r}function la(t){if("function"!=typeof t)throw new ie(a);return function(){var e=arguments;switch(e.length){case 0:return!t.call(this);case 1:return!t.call(this,e[0]);case 2:return!t.call(this,e[0],e[1]);case 3:return!t.call(this,e[0],e[1],e[2])}return!t.apply(this,e)}}ca.Cache=bn;var fa=Jo(function(t,e){var r=(e=1==e.length&&ma(e[0])?ar(e[0],Cr(Bi())):ar(Wn(e,1),Cr(Bi()))).length;return Co(function(n){for(var o=-1,i=Hr(n.length,r);++o=e}),ya=oo(function(){return arguments}())?oo:function(t){return Fa(t)&&fe.call(t,"callee")&&!Ce.call(t,"callee")},ma=n.isArray,ba=$e?Cr($e):function(t){return Fa(t)&&Zn(t)==ut};function wa(t){return null!=t&&Sa(t.length)&&!Ea(t)}function ka(t){return Fa(t)&&wa(t)}var ja=br||Hu,Ca=Je?Cr(Je):function(t){return Fa(t)&&Zn(t)==W};function xa(t){if(!Fa(t))return!1;var e=Zn(t);return e==V||e==H||"string"==typeof t.message&&"string"==typeof t.name&&!Ra(t)}function Ea(t){if(!Pa(t))return!1;var e=Zn(t);return e==$||e==J||e==G||e==tt}function Ta(t){return"number"==typeof t&&t==qa(t)}function Sa(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=R}function Pa(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}function Fa(t){return null!=t&&"object"==typeof t}var Aa=Qe?Cr(Qe):function(t){return Fa(t)&&Gi(t)==Q};function Oa(t){return"number"==typeof t||Fa(t)&&Zn(t)==X}function Ra(t){if(!Fa(t)||Zn(t)!=Z)return!1;var e=ke(t);if(null===e)return!0;var r=fe.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&le.call(r)==_e}var Ua=Xe?Cr(Xe):function(t){return Fa(t)&&Zn(t)==et};var Ia=Ke?Cr(Ke):function(t){return Fa(t)&&Gi(t)==rt};function Ba(t){return"string"==typeof t||!ma(t)&&Fa(t)&&Zn(t)==nt}function La(t){return"symbol"==typeof t||Fa(t)&&Zn(t)==ot}var Ma=Ze?Cr(Ze):function(t){return Fa(t)&&Sa(t.length)&&!!Ue[Zn(t)]};var Da=bi(fo),Na=bi(function(t,e){return t<=e});function za(t){if(!t)return[];if(wa(t))return Ba(t)?Mr(t):ni(t);if(Fe&&t[Fe])return function(t){for(var e,r=[];!(e=t.next()).done;)r.push(e.value);return r}(t[Fe]());var e=Gi(t);return(e==Q?Rr:e==rt?Br:_u)(t)}function Ga(t){return t?(t=Ha(t))===O||t===-O?(t<0?-1:1)*U:t==t?t:0:0===t?t:0}function qa(t){var e=Ga(t),r=e%1;return e==e?r?e-r:e:0}function Wa(t){return t?Un(qa(t),0,B):0}function Ha(t){if("number"==typeof t)return t;if(La(t))return I;if(Pa(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=Pa(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=t.replace(Ut,"");var r=Ht.test(t);return r||$t.test(t)?Me(t.slice(2),r?2:8):Wt.test(t)?I:+t}function Va(t){return oi(t,au(t))}function $a(t){return null==t?"":Lo(t)}var Ja=si(function(t,e){if(Ki(e)||wa(e))oi(e,su(e),t);else for(var r in e)fe.call(e,r)&&Sn(t,r,e[r])}),Qa=si(function(t,e){oi(e,au(e),t)}),Xa=si(function(t,e,r,n){oi(e,au(e),t,n)}),Ka=si(function(t,e,r,n){oi(e,su(e),t,n)}),Za=Fi(Rn);var Ya=Co(function(t,e){t=re(t);var r=-1,n=e.length,i=n>2?e[2]:o;for(i&&$i(e[0],e[1],i)&&(n=1);++r1),e}),oi(t,Oi(t),r),n&&(r=In(r,f|p|h,Si));for(var o=e.length;o--;)Do(r,e[o]);return r});var fu=Fi(function(t,e){return null==t?{}:mo(r=t,e,function(t,e){return ru(r,e)});var r});function pu(t,e){if(null==t)return{};var r=ar(Oi(t),function(t){return[t]});return e=Bi(e),mo(t,r,function(t,r){return e(t,r[0])})}var hu=Ci(su),du=Ci(au);function _u(t){return null==t?[]:xr(t,su(t))}var vu=li(function(t,e,r){return e=e.toLowerCase(),t+(r?gu(e):e)});function gu(t){return xu($a(t).toLowerCase())}function yu(t){return(t=$a(t))&&t.replace(Qt,Pr).replace(Te,"")}var mu=li(function(t,e,r){return t+(r?"-":"")+e.toLowerCase()}),bu=li(function(t,e,r){return t+(r?" ":"")+e.toLowerCase()}),wu=ci("toLowerCase");var ku=li(function(t,e,r){return t+(r?"_":"")+e.toLowerCase()});var ju=li(function(t,e,r){return t+(r?" ":"")+xu(e)});var Cu=li(function(t,e,r){return t+(r?" ":"")+e.toUpperCase()}),xu=ci("toUpperCase");function Eu(t,e,r){return t=$a(t),(e=r?o:e)===o?(n=t,Ae.test(n)?t.match(Pe)||[]:t.match(Nt)||[]):t.match(e)||[];var n}var Tu=Co(function(t,e){try{return Ye(t,o,e)}catch(t){return xa(t)?t:new Yt(t)}}),Su=Fi(function(t,e){return er(e,function(e){e=ps(e),On(t,e,oa(t[e],t))}),t});function Pu(t){return function(){return t}}var Fu=hi(),Au=hi(!0);function Ou(t){return t}function Ru(t){return uo("function"==typeof t?t:In(t,f))}var Uu=Co(function(t,e){return function(r){return no(r,t,e)}}),Iu=Co(function(t,e){return function(r){return no(t,r,e)}});function Bu(t,e,r){var n=su(e),o=Qn(e,n);null!=r||Pa(e)&&(o.length||!n.length)||(r=e,e=t,t=this,o=Qn(e,su(e)));var i=!(Pa(r)&&"chain"in r&&!r.chain),s=Ea(t);return er(o,function(r){var n=e[r];t[r]=n,s&&(t.prototype[r]=function(){var e=this.__chain__;if(i||e){var r=t(this.__wrapped__);return(r.__actions__=ni(this.__actions__)).push({func:n,args:arguments,thisArg:t}),r.__chain__=e,r}return n.apply(t,ur([this.value()],arguments))})}),t}function Lu(){}var Mu=gi(ar),Du=gi(nr),Nu=gi(fr);function zu(t){return Ji(t)?mr(ps(t)):(e=t,function(t){return Xn(t,e)});var e}var Gu=mi(),qu=mi(!0);function Wu(){return[]}function Hu(){return!1}var Vu=vi(function(t,e){return t+e},0),$u=ki("ceil"),Ju=vi(function(t,e){return t/e},1),Qu=ki("floor");var Xu,Ku=vi(function(t,e){return t*e},1),Zu=ki("round"),Yu=vi(function(t,e){return t-e},0);return hn.after=function(t,e){if("function"!=typeof e)throw new ie(a);return t=qa(t),function(){if(--t<1)return e.apply(this,arguments)}},hn.ary=ra,hn.assign=Ja,hn.assignIn=Qa,hn.assignInWith=Xa,hn.assignWith=Ka,hn.at=Za,hn.before=na,hn.bind=oa,hn.bindAll=Su,hn.bindKey=ia,hn.castArray=function(){if(!arguments.length)return[];var t=arguments[0];return ma(t)?t:[t]},hn.chain=zs,hn.chunk=function(t,e,r){e=(r?$i(t,e,r):e===o)?1:Wr(qa(e),0);var i=null==t?0:t.length;if(!i||e<1)return[];for(var s=0,a=0,u=n(He(i/e));si?0:i+r),(n=n===o||n>i?i:qa(n))<0&&(n+=i),n=r>n?0:Wa(n);r>>0)?(t=$a(t))&&("string"==typeof e||null!=e&&!Ua(e))&&!(e=Lo(e))&&Or(t)?Qo(Mr(t),0,r):t.split(e,r):[]},hn.spread=function(t,e){if("function"!=typeof t)throw new ie(a);return e=null==e?0:Wr(qa(e),0),Co(function(r){var n=r[e],o=Qo(r,0,e);return n&&ur(o,n),Ye(t,this,o)})},hn.tail=function(t){var e=null==t?0:t.length;return e?Ao(t,1,e):[]},hn.take=function(t,e,r){return t&&t.length?Ao(t,0,(e=r||e===o?1:qa(e))<0?0:e):[]},hn.takeRight=function(t,e,r){var n=null==t?0:t.length;return n?Ao(t,(e=n-(e=r||e===o?1:qa(e)))<0?0:e,n):[]},hn.takeRightWhile=function(t,e){return t&&t.length?zo(t,Bi(e,3),!1,!0):[]},hn.takeWhile=function(t,e){return t&&t.length?zo(t,Bi(e,3)):[]},hn.tap=function(t,e){return e(t),t},hn.throttle=function(t,e,r){var n=!0,o=!0;if("function"!=typeof t)throw new ie(a);return Pa(r)&&(n="leading"in r?!!r.leading:n,o="trailing"in r?!!r.trailing:o),sa(t,e,{leading:n,maxWait:e,trailing:o})},hn.thru=Gs,hn.toArray=za,hn.toPairs=hu,hn.toPairsIn=du,hn.toPath=function(t){return ma(t)?ar(t,ps):La(t)?[t]:ni(fs($a(t)))},hn.toPlainObject=Va,hn.transform=function(t,e,r){var n=ma(t),o=n||ja(t)||Ma(t);if(e=Bi(e,4),null==r){var i=t&&t.constructor;r=o?n?new i:[]:Pa(t)&&Ea(i)?dn(ke(t)):{}}return(o?er:$n)(t,function(t,n,o){return e(r,t,n,o)}),r},hn.unary=function(t){return ra(t,1)},hn.union=Fs,hn.unionBy=As,hn.unionWith=Os,hn.uniq=function(t){return t&&t.length?Mo(t):[]},hn.uniqBy=function(t,e){return t&&t.length?Mo(t,Bi(e,2)):[]},hn.uniqWith=function(t,e){return e="function"==typeof e?e:o,t&&t.length?Mo(t,o,e):[]},hn.unset=function(t,e){return null==t||Do(t,e)},hn.unzip=Rs,hn.unzipWith=Us,hn.update=function(t,e,r){return null==t?t:No(t,e,Vo(r))},hn.updateWith=function(t,e,r,n){return n="function"==typeof n?n:o,null==t?t:No(t,e,Vo(r),n)},hn.values=_u,hn.valuesIn=function(t){return null==t?[]:xr(t,au(t))},hn.without=Is,hn.words=Eu,hn.wrap=function(t,e){return pa(Vo(e),t)},hn.xor=Bs,hn.xorBy=Ls,hn.xorWith=Ms,hn.zip=Ds,hn.zipObject=function(t,e){return Wo(t||[],e||[],Sn)},hn.zipObjectDeep=function(t,e){return Wo(t||[],e||[],To)},hn.zipWith=Ns,hn.entries=hu,hn.entriesIn=du,hn.extend=Qa,hn.extendWith=Xa,Bu(hn,hn),hn.add=Vu,hn.attempt=Tu,hn.camelCase=vu,hn.capitalize=gu,hn.ceil=$u,hn.clamp=function(t,e,r){return r===o&&(r=e,e=o),r!==o&&(r=(r=Ha(r))==r?r:0),e!==o&&(e=(e=Ha(e))==e?e:0),Un(Ha(t),e,r)},hn.clone=function(t){return In(t,h)},hn.cloneDeep=function(t){return In(t,f|h)},hn.cloneDeepWith=function(t,e){return In(t,f|h,e="function"==typeof e?e:o)},hn.cloneWith=function(t,e){return In(t,h,e="function"==typeof e?e:o)},hn.conformsTo=function(t,e){return null==e||Bn(t,e,su(e))},hn.deburr=yu,hn.defaultTo=function(t,e){return null==t||t!=t?e:t},hn.divide=Ju,hn.endsWith=function(t,e,r){t=$a(t),e=Lo(e);var n=t.length,i=r=r===o?n:Un(qa(r),0,n);return(r-=e.length)>=0&&t.slice(r,i)==e},hn.eq=_a,hn.escape=function(t){return(t=$a(t))&&xt.test(t)?t.replace(jt,Fr):t},hn.escapeRegExp=function(t){return(t=$a(t))&&Rt.test(t)?t.replace(Ot,"\\$&"):t},hn.every=function(t,e,r){var n=ma(t)?nr:zn;return r&&$i(t,e,r)&&(e=o),n(t,Bi(e,3))},hn.find=Hs,hn.findIndex=ys,hn.findKey=function(t,e){return hr(t,Bi(e,3),$n)},hn.findLast=Vs,hn.findLastIndex=ms,hn.findLastKey=function(t,e){return hr(t,Bi(e,3),Jn)},hn.floor=Qu,hn.forEach=$s,hn.forEachRight=Js,hn.forIn=function(t,e){return null==t?t:Hn(t,Bi(e,3),au)},hn.forInRight=function(t,e){return null==t?t:Vn(t,Bi(e,3),au)},hn.forOwn=function(t,e){return t&&$n(t,Bi(e,3))},hn.forOwnRight=function(t,e){return t&&Jn(t,Bi(e,3))},hn.get=eu,hn.gt=va,hn.gte=ga,hn.has=function(t,e){return null!=t&&qi(t,e,to)},hn.hasIn=ru,hn.head=ws,hn.identity=Ou,hn.includes=function(t,e,r,n){t=wa(t)?t:_u(t),r=r&&!n?qa(r):0;var o=t.length;return r<0&&(r=Wr(o+r,0)),Ba(t)?r<=o&&t.indexOf(e,r)>-1:!!o&&_r(t,e,r)>-1},hn.indexOf=function(t,e,r){var n=null==t?0:t.length;if(!n)return-1;var o=null==r?0:qa(r);return o<0&&(o=Wr(n+o,0)),_r(t,e,o)},hn.inRange=function(t,e,r){return e=Ga(e),r===o?(r=e,e=0):r=Ga(r),t=Ha(t),(n=t)>=Hr(i=e,s=r)&&n=-R&&t<=R},hn.isSet=Ia,hn.isString=Ba,hn.isSymbol=La,hn.isTypedArray=Ma,hn.isUndefined=function(t){return t===o},hn.isWeakMap=function(t){return Fa(t)&&Gi(t)==st},hn.isWeakSet=function(t){return Fa(t)&&Zn(t)==at},hn.join=function(t,e){return null==t?"":Gr.call(t,e)},hn.kebabCase=mu,hn.last=xs,hn.lastIndexOf=function(t,e,r){var n=null==t?0:t.length;if(!n)return-1;var i=n;return r!==o&&(i=(i=qa(r))<0?Wr(n+i,0):Hr(i,n-1)),e==e?function(t,e,r){for(var n=r+1;n--;)if(t[n]===e)return n;return n}(t,e,i):dr(t,gr,i,!0)},hn.lowerCase=bu,hn.lowerFirst=wu,hn.lt=Da,hn.lte=Na,hn.max=function(t){return t&&t.length?Gn(t,Ou,Yn):o},hn.maxBy=function(t,e){return t&&t.length?Gn(t,Bi(e,2),Yn):o},hn.mean=function(t){return yr(t,Ou)},hn.meanBy=function(t,e){return yr(t,Bi(e,2))},hn.min=function(t){return t&&t.length?Gn(t,Ou,fo):o},hn.minBy=function(t,e){return t&&t.length?Gn(t,Bi(e,2),fo):o},hn.stubArray=Wu,hn.stubFalse=Hu,hn.stubObject=function(){return{}},hn.stubString=function(){return""},hn.stubTrue=function(){return!0},hn.multiply=Ku,hn.nth=function(t,e){return t&&t.length?go(t,qa(e)):o},hn.noConflict=function(){return ze._===this&&(ze._=ve),this},hn.noop=Lu,hn.now=ea,hn.pad=function(t,e,r){t=$a(t);var n=(e=qa(e))?Lr(t):0;if(!e||n>=e)return t;var o=(e-n)/2;return yi(Ve(o),r)+t+yi(He(o),r)},hn.padEnd=function(t,e,r){t=$a(t);var n=(e=qa(e))?Lr(t):0;return e&&ne){var n=t;t=e,e=n}if(r||t%1||e%1){var i=Jr();return Hr(t+i*(e-t+Le("1e-"+((i+"").length-1))),e)}return ko(t,e)},hn.reduce=function(t,e,r){var n=ma(t)?cr:wr,o=arguments.length<3;return n(t,Bi(e,4),r,o,Dn)},hn.reduceRight=function(t,e,r){var n=ma(t)?lr:wr,o=arguments.length<3;return n(t,Bi(e,4),r,o,Nn)},hn.repeat=function(t,e,r){return e=(r?$i(t,e,r):e===o)?1:qa(e),jo($a(t),e)},hn.replace=function(){var t=arguments,e=$a(t[0]);return t.length<3?e:e.replace(t[1],t[2])},hn.result=function(t,e,r){var n=-1,i=(e=$o(e,t)).length;for(i||(i=1,t=o);++nR)return[];var r=B,n=Hr(t,B);e=Bi(e),t-=B;for(var o=jr(n,e);++r=s)return t;var u=r-Lr(n);if(u<1)return n;var c=a?Qo(a,0,u).join(""):t.slice(0,u);if(i===o)return c+n;if(a&&(u+=c.length-u),Ua(i)){if(t.slice(u).search(i)){var l,f=c;for(i.global||(i=ne(i.source,$a(qt.exec(i))+"g")),i.lastIndex=0;l=i.exec(f);)var p=l.index;c=c.slice(0,p===o?u:p)}}else if(t.indexOf(Lo(i),u)!=u){var h=c.lastIndexOf(i);h>-1&&(c=c.slice(0,h))}return c+n},hn.unescape=function(t){return(t=$a(t))&&Ct.test(t)?t.replace(kt,Dr):t},hn.uniqueId=function(t){var e=++pe;return $a(t)+e},hn.upperCase=Cu,hn.upperFirst=xu,hn.each=$s,hn.eachRight=Js,hn.first=ws,Bu(hn,(Xu={},$n(hn,function(t,e){fe.call(hn.prototype,e)||(Xu[e]=t)}),Xu),{chain:!1}),hn.VERSION="4.17.20",er(["bind","bindKey","curry","curryRight","partial","partialRight"],function(t){hn[t].placeholder=hn}),er(["drop","take"],function(t,e){gn.prototype[t]=function(r){r=r===o?1:Wr(qa(r),0);var n=this.__filtered__&&!e?new gn(this):this.clone();return n.__filtered__?n.__takeCount__=Hr(r,n.__takeCount__):n.__views__.push({size:Hr(r,B),type:t+(n.__dir__<0?"Right":"")}),n},gn.prototype[t+"Right"]=function(e){return this.reverse()[t](e).reverse()}}),er(["filter","map","takeWhile"],function(t,e){var r=e+1,n=r==F||3==r;gn.prototype[t]=function(t){var e=this.clone();return e.__iteratees__.push({iteratee:Bi(t,3),type:r}),e.__filtered__=e.__filtered__||n,e}}),er(["head","last"],function(t,e){var r="take"+(e?"Right":"");gn.prototype[t]=function(){return this[r](1).value()[0]}}),er(["initial","tail"],function(t,e){var r="drop"+(e?"":"Right");gn.prototype[t]=function(){return this.__filtered__?new gn(this):this[r](1)}}),gn.prototype.compact=function(){return this.filter(Ou)},gn.prototype.find=function(t){return this.filter(t).head()},gn.prototype.findLast=function(t){return this.reverse().find(t)},gn.prototype.invokeMap=Co(function(t,e){return"function"==typeof t?new gn(this):this.map(function(r){return no(r,t,e)})}),gn.prototype.reject=function(t){return this.filter(la(Bi(t)))},gn.prototype.slice=function(t,e){t=qa(t);var r=this;return r.__filtered__&&(t>0||e<0)?new gn(r):(t<0?r=r.takeRight(-t):t&&(r=r.drop(t)),e!==o&&(r=(e=qa(e))<0?r.dropRight(-e):r.take(e-t)),r)},gn.prototype.takeRightWhile=function(t){return this.reverse().takeWhile(t).reverse()},gn.prototype.toArray=function(){return this.take(B)},$n(gn.prototype,function(t,e){var r=/^(?:filter|find|map|reject)|While$/.test(e),n=/^(?:head|last)$/.test(e),i=hn[n?"take"+("last"==e?"Right":""):e],s=n||/^find/.test(e);i&&(hn.prototype[e]=function(){var e=this.__wrapped__,a=n?[1]:arguments,u=e instanceof gn,c=a[0],l=u||ma(e),f=function(t){var e=i.apply(hn,ur([t],a));return n&&p?e[0]:e};l&&r&&"function"==typeof c&&1!=c.length&&(u=l=!1);var p=this.__chain__,h=!!this.__actions__.length,d=s&&!p,_=u&&!h;if(!s&&l){e=_?e:new gn(this);var v=t.apply(e,a);return v.__actions__.push({func:Gs,args:[f],thisArg:o}),new vn(v,p)}return d&&_?t.apply(this,a):(v=this.thru(f),d?n?v.value()[0]:v.value():v)})}),er(["pop","push","shift","sort","splice","unshift"],function(t){var e=se[t],r=/^(?:push|sort|unshift)$/.test(t)?"tap":"thru",n=/^(?:pop|shift)$/.test(t);hn.prototype[t]=function(){var t=arguments;if(n&&!this.__chain__){var o=this.value();return e.apply(ma(o)?o:[],t)}return this[r](function(r){return e.apply(ma(r)?r:[],t)})}}),$n(gn.prototype,function(t,e){var r=hn[e];if(r){var n=r.name+"";fe.call(nn,n)||(nn[n]=[]),nn[n].push({name:e,func:r})}}),nn[di(o,g).name]=[{name:"wrapper",func:o}],gn.prototype.clone=function(){var t=new gn(this.__wrapped__);return t.__actions__=ni(this.__actions__),t.__dir__=this.__dir__,t.__filtered__=this.__filtered__,t.__iteratees__=ni(this.__iteratees__),t.__takeCount__=this.__takeCount__,t.__views__=ni(this.__views__),t},gn.prototype.reverse=function(){if(this.__filtered__){var t=new gn(this);t.__dir__=-1,t.__filtered__=!0}else(t=this.clone()).__dir__*=-1;return t},gn.prototype.value=function(){var t=this.__wrapped__.value(),e=this.__dir__,r=ma(t),n=e<0,o=r?t.length:0,i=function(t,e,r){for(var n=-1,o=r.length;++n=this.__values__.length;return{done:t,value:t?o:this.__values__[this.__index__++]}},hn.prototype.plant=function(t){for(var e,r=this;r instanceof _n;){var n=ds(r);n.__index__=0,n.__values__=o,e?i.__wrapped__=n:e=n;var i=n;r=r.__wrapped__}return i.__wrapped__=t,e},hn.prototype.reverse=function(){var t=this.__wrapped__;if(t instanceof gn){var e=t;return this.__actions__.length&&(e=new gn(this)),(e=e.reverse()).__actions__.push({func:Gs,args:[Ps],thisArg:o}),new vn(e,this.__chain__)}return this.thru(Ps)},hn.prototype.toJSON=hn.prototype.valueOf=hn.prototype.value=function(){return Go(this.__wrapped__,this.__actions__)},hn.prototype.first=hn.prototype.head,Fe&&(hn.prototype[Fe]=function(){return this}),hn}();"function"==typeof t&&"object"==typeof t.amd&&t.amd?(ze._=Nr,t(function(){return Nr})):qe?((qe.exports=Nr)._=Nr,Ge._=Nr):ze._=Nr}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],91:[function(t,e,r){var n,o,i=e.exports={};function s(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function u(t){if(n===setTimeout)return setTimeout(t,0);if((n===s||!n)&&setTimeout)return n=setTimeout,setTimeout(t,0);try{return n(t,0)}catch(e){try{return n.call(null,t,0)}catch(e){return n.call(this,t,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:s}catch(t){n=s}try{o="function"==typeof clearTimeout?clearTimeout:a}catch(t){o=a}}();var c,l=[],f=!1,p=-1;function h(){f&&c&&(f=!1,c.length?l=c.concat(l):p=-1,l.length&&d())}function d(){if(!f){var t=u(h);f=!0;for(var e=l.length;e;){for(c=l,l=[];++p1)for(var r=1;r= 0x80 (not a basic code point)","invalid-input":"Invalid input"},j=f-p,C=Math.floor,x=String.fromCharCode;function E(t){throw new RangeError(k[t])}function T(t,e){for(var r=t.length,n=[];r--;)n[r]=e(t[r]);return n}function S(t,e){var r=t.split("@"),n="";return r.length>1&&(n=r[0]+"@",t=r[1]),n+T((t=t.replace(w,".")).split("."),e).join(".")}function P(t){for(var e,r,n=[],o=0,i=t.length;o=55296&&e<=56319&&o65535&&(e+=x((t-=65536)>>>10&1023|55296),t=56320|1023&t),e+=x(t)}).join("")}function A(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function O(t,e,r){var n=0;for(t=r?C(t/_):t>>1,t+=C(t/e);t>j*h>>1;n+=f)t=C(t/j);return C(n+(j+1)*t/(t+d))}function R(t){var e,r,n,o,i,s,a,u,c,d,_,m=[],b=t.length,w=0,k=g,j=v;for((r=t.lastIndexOf(y))<0&&(r=0),n=0;n=128&&E("not-basic"),m.push(t.charCodeAt(n));for(o=r>0?r+1:0;o=b&&E("invalid-input"),((u=(_=t.charCodeAt(o++))-48<10?_-22:_-65<26?_-65:_-97<26?_-97:f)>=f||u>C((l-w)/s))&&E("overflow"),w+=u*s,!(u<(c=a<=j?p:a>=j+h?h:a-j));a+=f)s>C(l/(d=f-c))&&E("overflow"),s*=d;j=O(w-i,e=m.length+1,0==i),C(w/e)>l-k&&E("overflow"),k+=C(w/e),w%=e,m.splice(w++,0,k)}return F(m)}function U(t){var e,r,n,o,i,s,a,u,c,d,_,m,b,w,k,j=[];for(m=(t=P(t)).length,e=g,r=0,i=v,s=0;s=e&&_C((l-r)/(b=n+1))&&E("overflow"),r+=(a-e)*b,e=a,s=0;sl&&E("overflow"),_==e){for(u=r,c=f;!(u<(d=c<=i?p:c>=i+h?h:c-i));c+=f)k=u-d,w=f-d,j.push(x(A(d+k%w,0))),u=C(k/w);j.push(x(A(u,0))),i=O(r,b,n==o),r=0,++n}++r,++e}return j.join("")}if(u={version:"1.4.1",ucs2:{decode:P,encode:F},decode:R,encode:U,toASCII:function(t){return S(t,function(t){return b.test(t)?"xn--"+U(t):t})},toUnicode:function(t){return S(t,function(t){return m.test(t)?R(t.slice(4).toLowerCase()):t})}},"function"==typeof t&&"object"==typeof t.amd&&t.amd)t("punycode",function(){return u});else if(i&&s)if(r.exports==i)s.exports=u;else for(c in u)u.hasOwnProperty(c)&&(i[c]=u[c]);else o.punycode=u}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],93:[function(t,e,r){"use strict";e.exports=function(t,e,r,o){e=e||"&",r=r||"=";var i={};if("string"!=typeof t||0===t.length)return i;var s=/\+/g;t=t.split(e);var a=1e3;o&&"number"==typeof o.maxKeys&&(a=o.maxKeys);var u,c,l=t.length;a>0&&l>a&&(l=a);for(var f=0;f=0?(p=v.substr(0,g),h=v.substr(g+1)):(p=v,h=""),d=decodeURIComponent(p),_=decodeURIComponent(h),u=i,c=d,Object.prototype.hasOwnProperty.call(u,c)?n(i[d])?i[d].push(_):i[d]=[i[d],_]:i[d]=_}return i};var n=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},{}],94:[function(t,e,r){"use strict";var n=function(t){switch(typeof t){case"string":return t;case"boolean":return t?"true":"false";case"number":return isFinite(t)?t:"";default:return""}};e.exports=function(t,e,r,a){return e=e||"&",r=r||"=",null===t&&(t=void 0),"object"==typeof t?i(s(t),function(s){var a=encodeURIComponent(n(s))+r;return o(t[s])?i(t[s],function(t){return a+encodeURIComponent(n(t))}).join(e):a+encodeURIComponent(n(t[s]))}).join(e):a?encodeURIComponent(n(a))+r+encodeURIComponent(n(t)):""};var o=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)};function i(t,e){if(t.map)return t.map(e);for(var r=[],n=0;n0?("string"==typeof e||u.objectMode||Object.getPrototypeOf(e)===c.prototype||(s=e,e=c.from(s)),n?u.endEmitted?t.emit("error",new Error("stream.unshift() after end event")):w(t,u,e,!0):u.ended?t.emit("error",new Error("stream.push() after EOF")):(u.reading=!1,u.decoder&&!r?(e=u.decoder.write(e),u.objectMode||0!==e.length?w(t,u,e,!1):E(t,u)):w(t,u,e,!1))):n||(u.reading=!1));return!(a=u).ended&&(a.needReadable||a.lengthe.highWaterMark&&(e.highWaterMark=((r=t)>=k?r=k:(r--,r|=r>>>1,r|=r>>>2,r|=r>>>4,r|=r>>>8,r|=r>>>16,r++),r)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0));var r}function C(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(h("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?o.nextTick(x,t):x(t))}function x(t){h("emit readable"),t.emit("readable"),F(t)}function E(t,e){e.readingMore||(e.readingMore=!0,o.nextTick(T,t,e))}function T(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):r=function(t,e,r){var n;ti.length?i.length:t;if(s===i.length?o+=i:o+=i.slice(0,t),0===(t-=s)){s===i.length?(++n,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=i.slice(s));break}++n}return e.length-=n,o}(t,e):function(t,e){var r=c.allocUnsafe(t),n=e.head,o=1;n.data.copy(r),t-=n.data.length;for(;n=n.next;){var i=n.data,s=t>i.length?i.length:t;if(i.copy(r,r.length-t,0,s),0===(t-=s)){s===i.length?(++o,n.next?e.head=n.next:e.head=e.tail=null):(e.head=n,n.data=i.slice(s));break}++o}return e.length-=o,r}(t,e);return n}(t,e.buffer,e.decoder),r);var r}function O(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,o.nextTick(R,e,t))}function R(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function U(t,e){for(var r=0,n=t.length;r=e.highWaterMark||e.ended))return h("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?O(this):C(this),null;if(0===(t=j(t,e))&&e.ended)return 0===e.length&&O(this),null;var n,o=e.needReadable;return h("need readable",o),(0===e.length||e.length-t0?A(t,e):null)?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&O(this)),null!==n&&this.emit("data",n),n},m.prototype._read=function(t){this.emit("error",new Error("_read() is not implemented"))},m.prototype.pipe=function(t,e){var n=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=t;break;case 1:i.pipes=[i.pipes,t];break;default:i.pipes.push(t)}i.pipesCount+=1,h("pipe count=%d opts=%j",i.pipesCount,e);var u=(!e||!1!==e.end)&&t!==r.stdout&&t!==r.stderr?l:b;function c(e,r){h("onunpipe"),e===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,h("cleanup"),t.removeListener("close",y),t.removeListener("finish",m),t.removeListener("drain",p),t.removeListener("error",g),t.removeListener("unpipe",c),n.removeListener("end",l),n.removeListener("end",b),n.removeListener("data",v),d=!0,!i.awaitDrain||t._writableState&&!t._writableState.needDrain||p())}function l(){h("onend"),t.end()}i.endEmitted?o.nextTick(u):n.once("end",u),t.on("unpipe",c);var f,p=(f=n,function(){var t=f._readableState;h("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&a(f,"data")&&(t.flowing=!0,F(f))});t.on("drain",p);var d=!1;var _=!1;function v(e){h("ondata"),_=!1,!1!==t.write(e)||_||((1===i.pipesCount&&i.pipes===t||i.pipesCount>1&&-1!==U(i.pipes,t))&&!d&&(h("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,_=!0),n.pause())}function g(e){h("onerror",e),b(),t.removeListener("error",g),0===a(t,"error")&&t.emit("error",e)}function y(){t.removeListener("finish",m),b()}function m(){h("onfinish"),t.removeListener("close",y),b()}function b(){h("unpipe"),n.unpipe(t)}return n.on("data",v),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?s(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",g),t.once("close",y),t.once("finish",m),t.emit("pipe",n),i.flowing||(h("pipe resume"),n.resume()),t},m.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes?this:(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r),this);if(!t){var n=e.pipes,o=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var i=0;i-1?o:i.nextTick;y.WritableState=g;var c=Object.create(t("core-util-is"));c.inherits=t("inherits");var l={deprecate:t("util-deprecate")},f=t("./internal/streams/stream"),p=t("safe-buffer").Buffer,h=n.Uint8Array||function(){};var d,_=t("./internal/streams/destroy");function v(){}function g(e,r){a=a||t("./_stream_duplex"),e=e||{};var n=r instanceof a;this.objectMode=!!e.objectMode,n&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var o=e.highWaterMark,c=e.writableHighWaterMark,l=this.objectMode?16:16384;this.highWaterMark=o||0===o?o:n&&(c||0===c)?c:l,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var f=!1===e.decodeStrings;this.decodeStrings=!f,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){!function(t,e){var r=t._writableState,n=r.sync,o=r.writecb;if(h=r,h.writing=!1,h.writecb=null,h.length-=h.writelen,h.writelen=0,e)a=t,c=r,l=n,f=e,p=o,--c.pendingcb,l?(i.nextTick(p,f),i.nextTick(C,a,c),a._writableState.errorEmitted=!0,a.emit("error",f)):(p(f),a._writableState.errorEmitted=!0,a.emit("error",f),C(a,c));else{var s=k(r);s||r.corked||r.bufferProcessing||!r.bufferedRequest||w(t,r),n?u(b,t,r,s,o):b(t,r,s,o)}var a,c,l,f,p;var h}(r,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new s(this)}function y(e){if(a=a||t("./_stream_duplex"),!(d.call(y,this)||this instanceof a))return new y(e);this._writableState=new g(e,this),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),f.call(this)}function m(t,e,r,n,o,i,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,r?t._writev(o,e.onwrite):t._write(o,i,e.onwrite),e.sync=!1}function b(t,e,r,n){var o,i;r||(o=t,0===(i=e).length&&i.needDrain&&(i.needDrain=!1,o.emit("drain"))),e.pendingcb--,n(),C(t,e)}function w(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var n=e.bufferedRequestCount,o=new Array(n),i=e.corkedRequestsFree;i.entry=r;for(var a=0,u=!0;r;)o[a]=r,r.isBuf||(u=!1),r=r.next,a+=1;o.allBuffers=u,m(t,e,!0,e.length,o,"",i.finish),e.pendingcb++,e.lastBufferedRequest=null,i.next?(e.corkedRequestsFree=i.next,i.next=null):e.corkedRequestsFree=new s(e),e.bufferedRequestCount=0}else{for(;r;){var c=r.chunk,l=r.encoding,f=r.callback;if(m(t,e,!1,e.objectMode?1:c.length,c,l,f),r=r.next,e.bufferedRequestCount--,e.writing)break}null===r&&(e.lastBufferedRequest=null)}e.bufferedRequest=r,e.bufferProcessing=!1}function k(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function j(t,e){t._final(function(r){e.pendingcb--,r&&t.emit("error",r),e.prefinished=!0,t.emit("prefinish"),C(t,e)})}function C(t,e){var r,n,o=k(e);return o&&(r=t,(n=e).prefinished||n.finalCalled||("function"==typeof r._final?(n.pendingcb++,n.finalCalled=!0,i.nextTick(j,r,n)):(n.prefinished=!0,r.emit("prefinish"))),0===e.pendingcb&&(e.finished=!0,t.emit("finish"))),o}c.inherits(y,f),g.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(g.prototype,"buffer",{get:l.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(d=Function.prototype[Symbol.hasInstance],Object.defineProperty(y,Symbol.hasInstance,{value:function(t){return!!d.call(this,t)||this===y&&(t&&t._writableState instanceof g)}})):d=function(t){return t instanceof this},y.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},y.prototype.write=function(t,e,r){var n,o,s,a,u,c,l,f,d,_,g,y=this._writableState,b=!1,w=!y.objectMode&&(n=t,p.isBuffer(n)||n instanceof h);return w&&!p.isBuffer(t)&&(o=t,t=p.from(o)),"function"==typeof e&&(r=e,e=null),w?e="buffer":e||(e=y.defaultEncoding),"function"!=typeof r&&(r=v),y.ended?(d=this,_=r,g=new Error("write after end"),d.emit("error",g),i.nextTick(_,g)):(w||(s=this,a=y,c=r,l=!0,f=!1,null===(u=t)?f=new TypeError("May not write null values to stream"):"string"==typeof u||void 0===u||a.objectMode||(f=new TypeError("Invalid non-string/buffer chunk")),f&&(s.emit("error",f),i.nextTick(c,f),l=!1),l))&&(y.pendingcb++,b=function(t,e,r,n,o,i){if(!r){var s=function(t,e,r){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=p.from(e,r));return e}(e,n,o);n!==s&&(r=!0,o="buffer",n=s)}var a=e.objectMode?1:n.length;e.length+=a;var u=e.length-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},Object.defineProperty(y.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),y.prototype._write=function(t,e,r){r(new Error("_write() is not implemented"))},y.prototype._writev=null,y.prototype.end=function(t,e,r){var n=this._writableState;"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!==t&&void 0!==t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(t,e,r){e.ending=!0,C(t,e),r&&(e.finished?i.nextTick(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r)},Object.defineProperty(y.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),y.prototype.destroy=_.destroy,y.prototype._undestroy=_.undestroy,y.prototype._destroy=function(t,e){this.end(),e(t)}}).call(this,t("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},t("timers").setImmediate)},{"./_stream_duplex":101,"./internal/streams/destroy":107,"./internal/streams/stream":108,_process:91,"core-util-is":85,inherits:88,"process-nextick-args":99,"safe-buffer":96,timers:114,"util-deprecate":117}],106:[function(t,e,r){"use strict";var n=t("safe-buffer").Buffer,o=t("util");e.exports=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.head=null,this.tail=null,this.length=0}return t.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},t.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},t.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},t.prototype.clear=function(){this.head=this.tail=null,this.length=0},t.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r},t.prototype.concat=function(t){if(0===this.length)return n.alloc(0);if(1===this.length)return this.head.data;for(var e,r,o,i=n.allocUnsafe(t>>>0),s=this.head,a=0;s;)e=s.data,r=i,o=a,e.copy(r,o),a+=s.data.length,s=s.next;return i},t}(),o&&o.inspect&&o.inspect.custom&&(e.exports.prototype[o.inspect.custom]=function(){var t=o.inspect({length:this.length});return this.constructor.name+" "+t})},{"safe-buffer":96,util:82}],107:[function(t,e,r){"use strict";var n=t("process-nextick-args");function o(t,e){t.emit("error",e)}e.exports={destroy:function(t,e){var r=this,i=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return i||s?(e?e(t):!t||this._writableState&&this._writableState.errorEmitted||n.nextTick(o,this,t),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(t){!e&&t?(n.nextTick(o,r,t),r._writableState&&(r._writableState.errorEmitted=!0)):e&&e(t)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}}},{"process-nextick-args":99}],108:[function(t,e,r){e.exports=t("events").EventEmitter},{events:86}],109:[function(t,e,r){e.exports=t("./readable").PassThrough},{"./readable":110}],110:[function(t,e,r){(r=e.exports=t("./lib/_stream_readable.js")).Stream=r,r.Readable=r,r.Writable=t("./lib/_stream_writable.js"),r.Duplex=t("./lib/_stream_duplex.js"),r.Transform=t("./lib/_stream_transform.js"),r.PassThrough=t("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":101,"./lib/_stream_passthrough.js":102,"./lib/_stream_readable.js":103,"./lib/_stream_transform.js":104,"./lib/_stream_writable.js":105}],111:[function(t,e,r){e.exports=t("./readable").Transform},{"./readable":110}],112:[function(t,e,r){e.exports=t("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":105}],113:[function(t,e,r){"use strict";var n=t("safe-buffer").Buffer,o=n.isEncoding||function(t){switch((t=""+t)&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function i(t){var e;switch(this.encoding=function(t){var e=function(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}(t);if("string"!=typeof e&&(n.isEncoding===o||!o(t)))throw new Error("Unknown encoding: "+t);return e||t}(t),this.encoding){case"utf16le":this.text=u,this.end=c,e=4;break;case"utf8":this.fillLast=a,e=4;break;case"base64":this.text=l,this.end=f,e=3;break;default:return this.write=p,void(this.end=h)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(e)}function s(t){return t<=127?0:t>>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function a(t){var e=this.lastTotal-this.lastNeed,r=function(t,e,r){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}(this,t);return void 0!==r?r:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function u(t,e){if((t.length-e)%2==0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function c(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function l(t,e){var r=(t.length-e)%3;return 0===r?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function f(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function p(t){return t.toString(this.encoding)}function h(t){return t&&t.length?this.write(t):""}r.StringDecoder=i,i.prototype.write=function(t){if(0===t.length)return"";var e,r;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return o>0&&(t.lastNeed=o-1),o;if(--n=0)return o>0&&(t.lastNeed=o-2),o;if(--n=0)return o>0&&(2===o?o=0:t.lastNeed=o-3),o;return 0}(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)},i.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length}},{"safe-buffer":96}],114:[function(t,e,r){(function(e,n){var o=t("process/browser.js").nextTick,i=Function.prototype.apply,s=Array.prototype.slice,a={},u=0;function c(t,e){this._id=t,this._clearFn=e}r.setTimeout=function(){return new c(i.call(setTimeout,window,arguments),clearTimeout)},r.setInterval=function(){return new c(i.call(setInterval,window,arguments),clearInterval)},r.clearTimeout=r.clearInterval=function(t){t.close()},c.prototype.unref=c.prototype.ref=function(){},c.prototype.close=function(){this._clearFn.call(window,this._id)},r.enroll=function(t,e){clearTimeout(t._idleTimeoutId),t._idleTimeout=e},r.unenroll=function(t){clearTimeout(t._idleTimeoutId),t._idleTimeout=-1},r._unrefActive=r.active=function(t){clearTimeout(t._idleTimeoutId);var e=t._idleTimeout;e>=0&&(t._idleTimeoutId=setTimeout(function(){t._onTimeout&&t._onTimeout()},e))},r.setImmediate="function"==typeof e?e:function(t){var e=u++,n=!(arguments.length<2)&&s.call(arguments,1);return a[e]=!0,o(function(){a[e]&&(n?t.apply(null,n):t.call(null),r.clearImmediate(e))}),e},r.clearImmediate="function"==typeof n?n:function(t){delete a[t]}}).call(this,t("timers").setImmediate,t("timers").clearImmediate)},{"process/browser.js":91,timers:114}],115:[function(t,e,r){"use strict";var n=t("punycode"),o=t("./util");function i(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}r.parse=m,r.resolve=function(t,e){return m(t,!1,!0).resolve(e)},r.resolveObject=function(t,e){return t?m(t,!1,!0).resolveObject(e):e},r.format=function(t){o.isString(t)&&(t=m(t));return t instanceof i?t.format():i.prototype.format.call(t)},r.Url=i;var s=/^([a-z0-9.+-]+:)/i,a=/:[0-9]*$/,u=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,c=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),l=["'"].concat(c),f=["%","/","?",";","#"].concat(l),p=["/","?","#"],h=/^[+a-z0-9A-Z_-]{0,63}$/,d=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,_={javascript:!0,"javascript:":!0},v={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},y=t("querystring");function m(t,e,r){if(t&&o.isObject(t)&&t instanceof i)return t;var n=new i;return n.parse(t,e,r),n}i.prototype.parse=function(t,e,r){if(!o.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var i=t.indexOf("?"),a=-1!==i&&i127?R+="x":R+=O[U];if(!R.match(h)){var B=F.slice(0,T),L=F.slice(T+1),M=O.match(d);M&&(B.push(M[1]),L.unshift(M[2])),L.length&&(m="/"+L.join(".")+m),this.hostname=B.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),P||(this.hostname=n.toASCII(this.hostname));var D=this.port?":"+this.port:"",N=this.hostname||"";this.host=N+D,this.href+=this.host,P&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==m[0]&&(m="/"+m))}if(!_[k])for(T=0,A=l.length;T0)&&r.host.split("@"))&&(r.auth=P.shift(),r.host=r.hostname=P.shift());return r.search=t.search,r.query=t.query,o.isNull(r.pathname)&&o.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!j.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var x=j.slice(-1)[0],E=(r.host||t.host||j.length>1)&&("."===x||".."===x)||""===x,T=0,S=j.length;S>=0;S--)"."===(x=j[S])?j.splice(S,1):".."===x?(j.splice(S,1),T++):T&&(j.splice(S,1),T--);if(!w&&!k)for(;T--;T)j.unshift("..");!w||""===j[0]||j[0]&&"/"===j[0].charAt(0)||j.unshift(""),E&&"/"!==j.join("/").substr(-1)&&j.push("");var P,F=""===j[0]||j[0]&&"/"===j[0].charAt(0);C&&(r.hostname=r.host=F?"":j.length?j.shift():"",(P=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@"))&&(r.auth=P.shift(),r.host=r.hostname=P.shift()));return(w=w||r.host&&j.length)&&!F&&j.unshift(""),j.length?r.pathname=j.join("/"):(r.pathname=null,r.path=null),o.isNull(r.pathname)&&o.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},i.prototype.parseHost=function(){var t=this.host,e=a.exec(t);e&&(":"!==(e=e[0])&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},{"./util":116,punycode:92,querystring:95}],116:[function(t,e,r){"use strict";e.exports={isString:function(t){return"string"==typeof t},isObject:function(t){return"object"==typeof t&&null!==t},isNull:function(t){return null===t},isNullOrUndefined:function(t){return null==t}}},{}],117:[function(t,e,r){(function(t){function r(e){try{if(!t.localStorage)return!1}catch(t){return!1}var r=t.localStorage[e];return null!=r&&"true"===String(r).toLowerCase()}e.exports=function(t,e){if(r("noDeprecation"))return t;var n=!1;return function(){if(!n){if(r("throwDeprecation"))throw new Error(e);r("traceDeprecation")?console.trace(e):console.warn(e),n=!0}return t.apply(this,arguments)}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],118:[function(t,e,r){e.exports=function(t){return t&&"object"==typeof t&&"function"==typeof t.copy&&"function"==typeof t.fill&&"function"==typeof t.readUInt8}},{}],119:[function(t,e,r){(function(e,n){var o=/%[sdj%]/g;r.format=function(t){if(!g(t)){for(var e=[],r=0;r=i)return t;switch(t){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return t}}),u=n[r];r=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),d(e)?n.showHidden=e:e&&r._extend(n,e),y(n.showHidden)&&(n.showHidden=!1),y(n.depth)&&(n.depth=2),y(n.colors)&&(n.colors=!1),y(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=u),l(n,t,n.depth)}function u(t,e){var r=a.styles[e];return r?"["+a.colors[r][0]+"m"+t+"["+a.colors[r][1]+"m":t}function c(t,e){return t}function l(t,e,n){if(t.customInspect&&e&&j(e.inspect)&&e.inspect!==r.inspect&&(!e.constructor||e.constructor.prototype!==e)){var o=e.inspect(n,t);return g(o)||(o=l(t,o,n)),o}var i=function(t,e){if(y(e))return t.stylize("undefined","undefined");if(g(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(v(e))return t.stylize(""+e,"number");if(d(e))return t.stylize(""+e,"boolean");if(_(e))return t.stylize("null","null")}(t,e);if(i)return i;var s,a=Object.keys(e),u=(s={},a.forEach(function(t,e){s[t]=!0}),s);if(t.showHidden&&(a=Object.getOwnPropertyNames(e)),k(e)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return f(e);if(0===a.length){if(j(e)){var c=e.name?": "+e.name:"";return t.stylize("[Function"+c+"]","special")}if(m(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(w(e))return t.stylize(Date.prototype.toString.call(e),"date");if(k(e))return f(e)}var b,C="",x=!1,E=["{","}"];(h(e)&&(x=!0,E=["[","]"]),j(e))&&(C=" [Function"+(e.name?": "+e.name:"")+"]");return m(e)&&(C=" "+RegExp.prototype.toString.call(e)),w(e)&&(C=" "+Date.prototype.toUTCString.call(e)),k(e)&&(C=" "+f(e)),0!==a.length||x&&0!=e.length?n<0?m(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),b=x?function(t,e,r,n,o){for(var i=[],s=0,a=e.length;s=0&&0,t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(b,C,E)):E[0]+C+E[1]}function f(t){return"["+Error.prototype.toString.call(t)+"]"}function p(t,e,r,n,o,i){var s,a,u;if((u=Object.getOwnPropertyDescriptor(e,o)||{value:e[o]}).get?a=u.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):u.set&&(a=t.stylize("[Setter]","special")),T(n,o)||(s="["+o+"]"),a||(t.seen.indexOf(u.value)<0?(a=_(r)?l(t,u.value,null):l(t,u.value,r-1)).indexOf("\n")>-1&&(a=i?a.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+a.split("\n").map(function(t){return" "+t}).join("\n")):a=t.stylize("[Circular]","special")),y(s)){if(i&&o.match(/^\d+$/))return a;(s=JSON.stringify(""+o)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=t.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=t.stylize(s,"string"))}return s+": "+a}function h(t){return Array.isArray(t)}function d(t){return"boolean"==typeof t}function _(t){return null===t}function v(t){return"number"==typeof t}function g(t){return"string"==typeof t}function y(t){return void 0===t}function m(t){return b(t)&&"[object RegExp]"===C(t)}function b(t){return"object"==typeof t&&null!==t}function w(t){return b(t)&&"[object Date]"===C(t)}function k(t){return b(t)&&("[object Error]"===C(t)||t instanceof Error)}function j(t){return"function"==typeof t}function C(t){return Object.prototype.toString.call(t)}function x(t){return t<10?"0"+t.toString(10):t.toString(10)}r.debuglog=function(t){if(y(i)&&(i=e.env.NODE_DEBUG||""),t=t.toUpperCase(),!s[t])if(new RegExp("\\b"+t+"\\b","i").test(i)){var n=e.pid;s[t]=function(){var e=r.format.apply(r,arguments);console.error("%s %d: %s",t,n,e)}}else s[t]=function(){};return s[t]},r.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},r.isArray=h,r.isBoolean=d,r.isNull=_,r.isNullOrUndefined=function(t){return null==t},r.isNumber=v,r.isString=g,r.isSymbol=function(t){return"symbol"==typeof t},r.isUndefined=y,r.isRegExp=m,r.isObject=b,r.isDate=w,r.isError=k,r.isFunction=j,r.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t},r.isBuffer=t("./support/isBuffer");var E=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function T(t,e){return Object.prototype.hasOwnProperty.call(t,e)}r.log=function(){var t,e;console.log("%s - %s",(t=new Date,e=[x(t.getHours()),x(t.getMinutes()),x(t.getSeconds())].join(":"),[t.getDate(),E[t.getMonth()],e].join(" ")),r.format.apply(r,arguments))},r.inherits=t("inherits"),r._extend=function(t,e){if(!e||!b(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t}}).call(this,t("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":118,_process:91,inherits:88}],120:[function(t,e,r){e.exports={name:"asana",version:"0.18.5",description:"Official NodeJS and BrowserJS client for the Asana API",main:"index.js",scripts:{test:"node_modules/.bin/gulp test"},repository:{type:"git",url:"git://github.com/Asana/node-asana.git"},keywords:["asana","api","oauth"],author:"Phips Peter",license:"MIT",bugs:{url:"https://github.com/Asana/node-asana/issues"},homepage:"https://github.com/Asana/node-asana",dependencies:{bluebird:"^3.7.2","browser-request":"^0.3.2",lodash:"^4.17.20",readline:"^1.3.0",request:"^2.88.2"},devDependencies:{browserify:"^16.5.1",gulp:"^4.0.2","gulp-bump":"^3.0.0","gulp-filter":"^5.1.0","gulp-git":"^2.5.1","gulp-istanbul":"^1.1.3","gulp-jshint":"^2.1.0","gulp-mocha":"^7.0.2","gulp-shell":"^0.7.1","gulp-tag-version":"^1.2.1","gulp-uglify":"^3.0.0",jshint:"^2.11.0","jshint-stylish":"^2.2.1",rewire:"^4.0.1",sinon:"^7.3.2",through:"^2.3.6","vinyl-buffer":"^1.0.0","vinyl-source-stream":"^2.0.0"},browser:{request:"browser-request"}}},{}]},{},[1])(1)}); \ No newline at end of file diff --git a/node_modules/asana/dist/asana.js b/node_modules/asana/dist/asana.js deleted file mode 100644 index 8b659d108..000000000 --- a/node_modules/asana/dist/asana.js +++ /dev/null @@ -1,39710 +0,0 @@ -(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.Asana = 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} The token, which will include the `access_token` - * used for API access, as well as a `refresh_token` which can be stored - * to get a new access token without going through the flow again. - */ -App.prototype.accessTokenFromCode = function(code, options) { - options = options || {}; - var params = { - method: 'POST', - url: this.asanaTokenUrl(options), - formData: { - 'grant_type': 'authorization_code', - 'client_id': this.clientId, - 'client_secret': this.clientSecret, - 'redirect_uri': options.redirectUri || this.redirectUri, - 'code': code - } - }; - return doRequest(params); -}; - -/** - * @param {String} refreshToken A refresh token obtained via Oauth. - * @param {Object} options Overrides to the app's defaults - * @option {String} asanaBaseUrl - * @option {String} redirectUri - * @return {Promise} The token, which will include the `access_token` - * used for API access. - */ -App.prototype.accessTokenFromRefreshToken = function(refreshToken, options) { - options = options || {}; - var params = { - method: 'POST', - url: this.asanaTokenUrl(options), - formData: { - 'grant_type': 'refresh_token', - 'client_id': this.clientId, - 'client_secret': this.clientSecret, - 'redirect_uri': options.redirectUri || this.redirectUri, - 'refresh_token': refreshToken - } - }; - return doRequest(params); -}; - - -module.exports = App; - -},{"./oauth_error":11,"bluebird":80,"request":81,"url":115}],3:[function(require,module,exports){ -/** - * A layer to abstract the differences between using different types of - * authentication (Oauth vs. Basic). The Authenticator is responsible for - * establishing credentials and applying them to outgoing requests. - * @constructor - */ -function Authenticator() { -} - -/** - * @param {Object} request The request to modify, for the `request` library. - * @return {Object} The `request` parameter, modified to include authentication - * information using the stored credentials. - */ -Authenticator.prototype.authenticateRequest = function(request) { - throw new Error('not implemented', request); -}; - -/** - * Establishes credentials. - * - * @return {Promise} Resolves when initial credentials have been - * completed and `authenticateRequest` calls can expect to succeed. - */ -Authenticator.prototype.establishCredentials = function() { - throw new Error('not implemented'); -}; - -/** - * Attempts to refresh credentials, if possible, given the current credentials. - * - * @return {Promise} Resolves to `true` if credentials have been successfully - * established and `authenticateRequests` can expect to succeed, else - * resolves to `false`. - */ -Authenticator.prototype.refreshCredentials = function() { - throw new Error('not implemented'); -}; - - -module.exports = Authenticator; - -},{}],4:[function(require,module,exports){ -/* jshint browser: true */ -var NativeFlow = require('./native_flow'); -var RedirectFlow = require('./redirect_flow'); -var ChromeExtensionFlow = require('./chrome_extension_flow'); -var defaultEnvironment = require('../default_environment'); - -/** - * Auto-detects the type of Oauth flow to use that's appropriate to the - * environment. - * - * @returns {Function|null} The type of Oauth flow to use, or null if no - * appropriate type could be determined. - */ -function autoDetect(env) { - env = env || defaultEnvironment(); - if (typeof(env.chrome) !== 'undefined' && - env.chrome.runtime && env.chrome.runtime.id) { - if (env.chrome.tabs && env.chrome.tabs.create) { - return ChromeExtensionFlow; - } else { - // Chrome packaged app, not supported yet. - return null; - } - } - if (typeof(env.window) !== 'undefined' && env.window.navigator) { - // Browser - return RedirectFlow; - } - if (typeof(env.process) !== 'undefined' && env.process.env) { - // NodeJS script - return NativeFlow; - } - return null; -} - -module.exports = autoDetect; - -},{"../default_environment":16,"./chrome_extension_flow":7,"./native_flow":9,"./redirect_flow":14}],5:[function(require,module,exports){ -/* jshint browser:true */ -var url = require('url'); -var oauthUtil = require('./oauth_util'); - -// TODO: options.storage, for an interface to load/save/delete credentials -// e.g. in cookies or in localStorage maybe -// TODO: options.remember, to store in storage (true by default?) -// TODO: testing across browsers -// TODO: standardize logging with option (add logger? 3rd party something?) -// TODO: tests - -/** - * A base class for any flow that runs in the browser. All subclasses use the - * "implicit grant" flow to authenticate via the browser. - * @param {Object} options - * @option {App} app The app this flow is for - * @option {String} [redirectUri] The URL that Asana should redirect to once - * user authorization is complete. Defaults to the URL configured in - * the app, and if none then the current page URL. - * @constructor - */ -function BaseBrowserFlow(options) { - this.options = options; -} - -/** - * @param {String} authUrl The URL the user should be navigated to in order - * to authorize the app. - * @param {String} state The unique state generated for this auth request. - * @return {Promise} Resolved when authorization has successfully started, - * i.e. the user has been navigated to a page requesting authorization. - */ -BaseBrowserFlow.prototype.startAuthorization = function(authUrl, state) { - throw new Error('Not implemented', authUrl, state); -}; - -/** - * @return {Promise} Credentials returned from Oauth. - */ -BaseBrowserFlow.prototype.finishAuthorization = function(state) { - throw new Error('Not implemented', state); -}; - -/** - * @return {String} The URL to redirect to that will receive the - */ -BaseBrowserFlow.prototype.receiverUrl = function() { - var relativeUrl = - this.options.redirectUri || this.options.app.redirectUri || ''; - return url.resolve(window.location.href, relativeUrl); -}; - -/** - * @return {String} The URL to redirect to that will receive the - */ -BaseBrowserFlow.prototype.asanaBaseUrl = function() { - return this.options.app.asanaBaseUrl; -}; - -/** - * @returns {String} Generate a new unique state parameter for a request. - */ -BaseBrowserFlow.prototype.getStateParam = function() { - return oauthUtil.randomState(); -}; - -/** - * @returns {String} The URL used to authorize the user for the app. - */ -BaseBrowserFlow.prototype.authorizeUrl = function() { - // All browser flows should use the implicit grant (`token`) flow. - return url.resolve(this.asanaBaseUrl(), url.format({ - pathname: '/-/oauth_authorize', - query: { - 'client_id': this.options.app.clientId, - 'response_type': 'token', - 'redirect_uri': this.receiverUrl(), - 'scope': this.options.app.scope, - 'state': this.state - } - })); -}; - -/** - * Run the appropriate parts of the Oauth flow, attempting to establish user - * authorization. - * @returns {Promise} A promise that resolves to the Oauth credentials. - */ -BaseBrowserFlow.prototype.run = function() { - var me = this; - me.state = me.getStateParam(me.options); - return me.startAuthorization(me.authorizeUrl(), me.state).then(function() { - return me.finishAuthorization(me.state); - }); -}; - -module.exports = BaseBrowserFlow; -},{"./oauth_util":12,"url":115}],6:[function(require,module,exports){ -var util = require('util'); -var Bluebird = require('bluebird'); -var Authenticator = require('./authenticator'); - -/** - * @param {String} apiKey The key to use to access the API. - * @constructor - */ -function BasicAuthenticator(apiKey) { - this.apiKey = apiKey; -} - -util.inherits(BasicAuthenticator, Authenticator); - -BasicAuthenticator.prototype.authenticateRequest = function(request) { - request.auth = { - username: this.apiKey, - password: '' - }; - return request; -}; - -BasicAuthenticator.prototype.establishCredentials = function() { - // Credentials are already built-in. - return Bluebird.resolve(); -}; - -BasicAuthenticator.prototype.refreshCredentials = function() { - // We have no way of refreshing credentials. - return Bluebird.resolve(false); -}; - -module.exports = BasicAuthenticator; -},{"./authenticator":3,"bluebird":80,"util":119}],7:[function(require,module,exports){ -/* jshint browser: true */ -/* global chrome */ -var util = require('util'); -var oauthUtil = require('./oauth_util'); -var BaseBrowserFlow = require('./base_browser_flow'); -var OauthError = require('./oauth_error'); -var Bluebird = require('bluebird'); - -/** - * An Oauth flow that runs in a Chrome browser extension and requests user - * authorization by opening a temporary tab to prompt the user. - * @param {Object} options See `BaseBrowserFlow` for options, plus the below: - * @options {String} [receiverPath] Full path and filename from the base - * directory of the extension to the receiver page. This is an HTML file - * that has been made web-accessible, and that calls the receiver method - * `Asana.auth.ChromeExtensionFlow.runReceiver();`. - * @constructor - */ -function ChromeExtensionFlow(options) { - BaseBrowserFlow.call(this, options); - this._authorizationPromise = null; - this._receiverUrl = chrome.runtime.getURL( - options.receiverPath || 'asana_oauth_receiver.html'); -} - -util.inherits(ChromeExtensionFlow, BaseBrowserFlow); - -ChromeExtensionFlow.prototype.receiverUrl = function() { - return this._receiverUrl; -}; - -ChromeExtensionFlow.prototype.startAuthorization = function(authUrl, state) { - var me = this; - var receiverTabId = null; - me._authorizationPromise = new Bluebird(function(resolve, reject) { - var listener = function(message, sender) { - // The message must come from our receiver window, which would have a URL - // that is our receiver URL, plus a hash with some oauth results in it. - if (!sender || !sender.tab || sender.tab.id !== receiverTabId || - sender.tab.url.substring(0, me._receiverUrl.length) !== - me._receiverUrl) { - return; - } - var receivedUrl = message.receivedUrl; - if (receivedUrl) { - // Every request should have a unique `state` parameter. - // We can key off of that to determine whether this request was - // intended for this window. - var params = oauthUtil.parseOauthResultFromUrl(receivedUrl); - if (params.state === state) { - state = null; // don't ever respond to again - var dummyError; - chrome.tabs.remove(receiverTabId, function() { - // Calling the `lastError` getter will silence a warning we get - // in case the tab has already closed. - dummyError = chrome.runtime.lastError; - }); - chrome.runtime.onMessage.removeListener(listener); - if (params.error) { - reject(new OauthError(params)); - } else { - resolve(params); - } - } - } - }; - chrome.runtime.onMessage.addListener(listener); - chrome.tabs.create({ - url: authUrl, - active: true - }, function(tab) { - receiverTabId = tab.id; - }); - }); - return Bluebird.resolve(); -}; - -ChromeExtensionFlow.prototype.finishAuthorization = function() { - return this._authorizationPromise; -}; - -/** - * Runs the receiver code to send the Oauth result to the requesting tab. - */ -ChromeExtensionFlow.runReceiver = function() { - window.addEventListener('load', function() { - var currentUrl = window.location.href; - oauthUtil.removeOauthResultFromCurrentUrl(); - chrome.runtime.sendMessage({ receivedUrl: currentUrl }); - window.close(); - }, false); -}; - -module.exports = ChromeExtensionFlow; - -},{"./base_browser_flow":5,"./oauth_error":11,"./oauth_util":12,"bluebird":80,"util":119}],8:[function(require,module,exports){ -exports.BaseBrowserFlow = require('./base_browser_flow'); -exports.ChromeExtensionFlow = require('./chrome_extension_flow'); -exports.NativeFlow = require('./native_flow'); -exports.PopupFlow = require('./popup_flow'); -exports.RedirectFlow = require('./redirect_flow'); - -exports.autoDetect = require('./auto_detect'); -exports.OauthError = require('./oauth_error'); -exports.App = require('./app'); - -},{"./app":2,"./auto_detect":4,"./base_browser_flow":5,"./chrome_extension_flow":7,"./native_flow":9,"./oauth_error":11,"./popup_flow":13,"./redirect_flow":14}],9:[function(require,module,exports){ -(function (process){ -var readline = require('readline'); -var Bluebird = require('bluebird'); -var oauthUtil = require('./oauth_util'); - -/** - * Default function to return instructions for the user to authorize the app. - * Written to stdout during `run`. - * @param {String} url The authorization URL - * @returns {String} Instructions for the user - */ -function defaultInstructions(url) { - return [ - '* * * * * * * * * * * * * * * * * * * * * * * * * * *', - 'Please open a browser to the url:', - '', - url, - '', - 'and follow the prompts to authorize this application.', - '* * * * * * * * * * * * * * * * * * * * * * * * * * *' - ].join('\n'); -} - -/** - * Default function to return the prompt for the user to enter the - * authorization code. Written to stdout immediately preceding keyboard input - * during `run`. - * @returns {String} A message to prompt the user to enter the code. - */ -function defaultPrompt() { - return 'Enter the code here: '; -} - -/** - * An Oauth flow that can be run from the console or an app that does - * not have the ability to open and manage a browser on its own. - * @param {Object} options - * @option {App} app App to authenticate for - * @option {String function(String)} [instructions] Function returning the - * instructions to output to the user. Passed the authorize url. - * @option {String function()} [prompt] String to output immediately before - * waiting for a line from stdin. - * @constructor - */ -function NativeFlow(options) { - this.app = options.app; - this.instructions = options.instructions || defaultInstructions; - this.prompt = options.prompt || defaultPrompt; - this.redirectUri = oauthUtil.NATIVE_REDIRECT_URI; -} - -/** - * Run the Oauth flow, prompting the user to go to the authorization URL - * and enter the code it displays when finished. - * - * @return {Promise} The access token object, which will include - * `access_token` and `refresh_token`. - */ -NativeFlow.prototype.run = function() { - var me = this; - return me.promptForCode(me.authorizeUrl()).then(function(code) { - return me.accessToken(code); - }); -}; - -/** - * @returns {String} The URL used to authorize the user for the app. - */ -NativeFlow.prototype.authorizeUrl = function() { - return this.app.asanaAuthorizeUrl({ - redirectUri: this.redirectUri - }); -}; - -/** - * @param {String} code An authorization code obtained via `asanaAuthorizeUrl`. - * @return {Promise} The token, which will include the `access_token` - * used for API access, as well as a `refresh_token` which can be stored - * to get a new access token without going through the flow again. - */ -NativeFlow.prototype.accessToken = function(code) { - return this.app.accessTokenFromCode(code, { - redirectUri: this.redirectUri - }); -}; - -/** - * @return {Promise} The access token, which will include a refresh token - * that can be stored in the future to create a client without going - * through the Oauth flow. - */ -NativeFlow.prototype.promptForCode = function(url) { - var me = this; - var rl = readline.createInterface({ - input: process.stdin, - output: process.stdout - }); - return new Bluebird(function(resolve) { - console.log(me.instructions(url)); - rl.question(me.prompt(), function(code) { - rl.close(); - return resolve(code); - }); - }); -}; - -module.exports = NativeFlow; - -}).call(this,require('_process')) -},{"./oauth_util":12,"_process":91,"bluebird":80,"readline":83}],10:[function(require,module,exports){ -var util = require('util'); -var Bluebird = require('bluebird'); -var Authenticator = require('./authenticator'); - -/** - * Creates an authenticator that uses Oauth for authentication. - * - * @param {Object} options Configure the authenticator; must specify one - * of `flow` or `credentials`. - * @option {App} app The app being authenticated for. - * @option {OauthFlow} [flow] The flow to use to get credentials - * when needed. - * @option {String|Object} [credentials] Initial credentials to use. This can - * be either the object returned from an access token request (which - * contains the token and some other metadata) or just the `access_token` - * field. - * @constructor - */ -function OauthAuthenticator(options) { - Authenticator.call(this); - if (typeof(options.credentials) === 'string') { - this.credentials = { - 'access_token': options.credentials - }; - } else { - this.credentials = options.credentials || null; - } - this.flow = options.flow || null; - this.app = options.app; - this.refreshCredentialsCallback = options.refreshCredentialsCallback || null; -} - -util.inherits(OauthAuthenticator, Authenticator); - -/** - * @param {Object} request The request to modify, for the `request` library. - * @return {Object} The `request` parameter, modified to include authentication - * information using the stored credentials. - */ -OauthAuthenticator.prototype.authenticateRequest = function(request) { - /* jshint camelcase: false */ - if (this.credentials === null) { - throw new Error( - 'Cannot authenticate a request without first obtaining credentials'); - } - // When browserify-d, the `auth` component of the `request` library - // doesn't work so well, so we just manually set the bearer token instead. - request.headers = request.headers || {}; - request.headers.Authorization = 'Bearer ' + this.credentials.access_token; - return request; -}; - -/** - * Requests new credentials, discarding any that it may already have. - * @return {Promise} Resolves when credentials have been successfully - * established and `authenticateRequests` can expect to succeed. - */ -OauthAuthenticator.prototype.establishCredentials = function() { - /* jshint camelcase: false */ - var me = this; - if (me.flow) { - // Request new credentials - me.credentials = null; - return me.flow.run().then(function(credentials) { - me.credentials = credentials; - }); - } else { - if (me.credentials.access_token) { - // Assume what we have is ok. - return Bluebird.resolve(); - } else if (me.credentials.refresh_token) { - // We were given a refresh token but NOT an access token. Get access. - return me.refreshCredentials(); - } else { - // What kind of credentials did we get anyway? - return Bluebird.reject(new Error('Invalid credentials')); - } - } -}; - -/** - * Attempts to refresh credentials, if possible, given the current credentials. - * @return {Promise} Resolves to `true` if credentials have been successfully - * established and `authenticateRequests` can expect to succeed, else - * resolves to `false`. - */ -OauthAuthenticator.prototype.refreshCredentials = function() { - /* jshint camelcase: false */ - var me = this; - if (me.credentials && me.credentials.refresh_token) { - // We have a refresh token. Use it to get a new access token. - // Only have one outstanding request, any simultaneous requests waiting on - // refresh should gate on this promise. - if (!me.refreshPromise) { - var refreshToken = me.credentials.refresh_token; - me.refreshPromise = me.app.accessTokenFromRefreshToken(refreshToken).then( - function(credentials) { - - // Update credentials, but hang on to refresh token. - if (!credentials.refresh_token) { - credentials.refresh_token = refreshToken; - } - me.credentials = credentials; - me.refreshPromise = null; - - if (me.refreshCredentialsCallback !== null) { - me.refreshCredentialsCallback(me.credentials); - } - - return true; - }); - } - return me.refreshPromise; - } else if (me.flow) { - // Try running the flow again to get credentials. - return this.establishCredentials().then(function(credentials) { - return credentials !== null; - }); - } else { - // We are unable to refresh credentials automatically. - return Bluebird.resolve(false); - } -}; - -module.exports = OauthAuthenticator; - -},{"./authenticator":3,"bluebird":80,"util":119}],11:[function(require,module,exports){ -var util = require('util'); - -/** - * @param options {Object} A data blob parsed from a query string or JSON - * response from the Asana API - * @option {String} error The string code identifying the error. - * @option {String} [error_uri] A link to help and information about the error. - * @option {String} [error_description] A description of the error. - * @constructor - */ -function OauthError(options) { - /* jshint camelcase:false */ - Error.call(this); - if (typeof(options) !== 'object' || !options.error) { - throw new Error('Invalid Oauth error: ' + options); - } - this.code = options.error; - this.description = options.error_description || null; - this.uri = options.error_uri || null; -} - -util.inherits(OauthError, Error); - -module.exports = OauthError; -},{"util":119}],12:[function(require,module,exports){ -/* jshint browser:true */ -var querystring = require('querystring'); -var url = require('url'); - -var NATIVE_REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'; -var NATIVE_AUTO_REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob:auto'; - -/** - * @returns {String} A unique parameter to use as a CSRF token to pass in - * the `state` parameter of an Oauth request. - */ -function randomState() { - return 'asana_' + - Math.random().toString(36) + - Date.now().toString(36); -} - -/** - * Parses a URL and returns any Oauth result that may be encoded therein. - * @param currentUrl {String} Complete URL of a page. - * @returns {Object|null} Oauth fields found in the hash of the URL, or null - * if the URL does not contain a valid hash. - */ -function parseOauthResultFromUrl(currentUrl) { - var oauthUrl = url.parse(currentUrl); - return oauthUrl.hash ? querystring.parse(oauthUrl.hash.substr(1)) : null; -} - -/** - * Clean Oauth results out of the current browser URL, for security and - * cleanliness purposes. - * @returns {Object|null} Oauth fields found in the hash of the URL, or null - * if the URL does not contain a valid hash. - */ -function removeOauthResultFromCurrentUrl() { - if (window.history && window.history.replaceState) { - var url = window.location.href; - var hashIndex = url.indexOf('#'); - window.history.replaceState({}, - document.title, url.substring(0, hashIndex)); - } else { - window.location.hash = ''; - } -} - -module.exports = { - NATIVE_REDIRECT_URI: NATIVE_REDIRECT_URI, - NATIVE_AUTO_REDIRECT_URI: NATIVE_AUTO_REDIRECT_URI, - randomState: randomState, - parseOauthResultFromUrl: parseOauthResultFromUrl, - removeOauthResultFromCurrentUrl: removeOauthResultFromCurrentUrl -}; -},{"querystring":95,"url":115}],13:[function(require,module,exports){ -/* jshint browser:true */ -var util = require('util'); -var oauthUtil = require('./oauth_util'); -var Bluebird = require('bluebird'); -var BaseBrowserFlow = require('./base_browser_flow'); -var OauthError = require('./oauth_error'); - -/** - * An Oauth flow that runs in the browser and requests user authorization by - * popping up a window and prompting the user. - * @param {Object} options See `BaseBrowserFlow` for options. - * @constructor - */ -function PopupFlow(options) { - BaseBrowserFlow.call(this, options); - this._authorizationPromise = null; -} - -util.inherits(PopupFlow, BaseBrowserFlow); - -PopupFlow.prototype.startAuthorization = function(authUrl, state) { - var me = this; - - var popup, popupTimer, listener; - function cleanup() { - if (popup && popupTimer) { - clearInterval(popupTimer); - popupTimer = null; - } - if (listener) { - window.removeEventListener('message', listener, false); - listener = null; - } - } - - me._authorizationPromise = new Bluebird(function(resolve, reject) { - listener = function(event) { - var receivedUrl; - try { - receivedUrl = event.data.receivedUrl; - } catch (e) {} - if (receivedUrl) { - // Every request should have a unique `state` parameter. - // We can key off of that to determine whether this request was - // intended for this window. - var params = oauthUtil.parseOauthResultFromUrl(receivedUrl); - if (params.state === state) { - state = null; // don't ever respond to again - cleanup(); - if (params.error) { - reject(new OauthError(params)); - } else { - resolve(params); - } - } - } - }; - window.addEventListener('message', listener, false); - popup = window.open(authUrl, 'asana_oauth', me._popupParams(800, 600)); - - // Detect popup blocking and fail. - if (!popup) { - cleanup(); - reject(new OauthError({ - 'error': 'access_denied', - 'error_description': 'The popup window containing the ' + - 'authorization UI was blocked by the browser.' - })); - return; - } - - // Detect popup closure (which may not be handled by the content, because - // it may never load) and fail. If the popup posts a message to us, we - // SHOULD get that message before it closes and this interval fires, - // but just in case we wait for two successive intervals. - var seenClosed = false; - popupTimer = setInterval(function() { - if (popup.closed) { - if (seenClosed) { - cleanup(); - reject(new OauthError({ - 'error': 'access_denied', - 'error_description': 'The popup window containing the ' + - 'authorization UI was closed by the user.' - })); - } else { - seenClosed = true; - } - } - }, 500); - }); - return Bluebird.resolve(); -}; - -PopupFlow.prototype.finishAuthorization = function() { - return this._authorizationPromise; -}; - -PopupFlow.prototype._popupParams = function(popupWidth, popupHeight) { - var left = window.screenX || window.screenLeft || 0; - var top = window.screenY || window.screenTop || 0; - var width = window.outerWidth || document.documentElement.clientWidth; - var height = window.outerHeight || document.documentElement.clientHeight; - - var popupLeft = Math.max(left, Math.round(left + (width - popupWidth) / 2)); - var popupTop = Math.max(top, Math.round(top + (height - popupHeight) / 2.5)); - - return util.format( - 'left=%d,top=%d,' + - 'width=%d,height=%d,' + - 'dialog=yes,dependent=yes,scrollbars=yes,location=yes', - popupLeft, popupTop, popupWidth, popupHeight); -}; - -PopupFlow.runReceiver = function() { - window.addEventListener('load', function() { - var currentUrl = window.location.href; - oauthUtil.removeOauthResultFromCurrentUrl(); - var opener = window.opener; - if (window.parent !== window.top) { - opener = opener || window.parent; - } - if (window.opener) { - console.log('Posting message', currentUrl, window.location.origin); - opener.postMessage({ - receivedUrl: currentUrl - }, window.location.origin); - window.close(); - } else { - console.log('No opener found for this window, not sending message'); - } - }, false); -}; - -module.exports = PopupFlow; -},{"./base_browser_flow":5,"./oauth_error":11,"./oauth_util":12,"bluebird":80,"util":119}],14:[function(require,module,exports){ -/* jshint browser:true */ -var util = require('util'); -var oauthUtil = require('./oauth_util'); -var BaseBrowserFlow = require('./base_browser_flow'); -var OauthError = require('./oauth_error'); -var Bluebird = require('bluebird'); - -/** - * An Oauth flow that runs in the browser and requests user authorization by - * redirecting to an authorization page on Asana, and redirecting back with - * the credentials. - * @param {Object} options See `BaseBrowserFlow` for options. - * @constructor - */ -function RedirectFlow(options) { - BaseBrowserFlow.call(this, options); -} - -util.inherits(RedirectFlow, BaseBrowserFlow); - -RedirectFlow.prototype.getStateParam = function() { - // If we're coming off the redirect, then we should use the state passed - // back from the URL. - var oauthResult = oauthUtil.parseOauthResultFromUrl(window.location.href); - if (oauthResult !== null && oauthResult.state) { - return oauthResult.state; - } - return BaseBrowserFlow.prototype.getStateParam.call(this); -}; - -RedirectFlow.prototype.startAuthorization = function(authUrl) { - // If we're coming off the redirect, then move directly to finish auth - var result = oauthUtil.parseOauthResultFromUrl(window.location.href); - if (result !== null) { - return Bluebird.resolve(); - } - window.location.href = authUrl; - return new Bluebird(function() { - // This promise will never resolve - we should leave the page first. - }); -}; - -RedirectFlow.prototype.finishAuthorization = function() { - var currentUrl = window.location.href; - oauthUtil.removeOauthResultFromCurrentUrl(); - var result = oauthUtil.parseOauthResultFromUrl(currentUrl); - if (result.error) { - return Bluebird.reject(new OauthError(result)); - } else { - return Bluebird.resolve(result); - } -}; - -module.exports = RedirectFlow; - -},{"./base_browser_flow":5,"./oauth_error":11,"./oauth_util":12,"bluebird":80,"util":119}],15:[function(require,module,exports){ -var Dispatcher = require('./dispatcher'); -var resources = require('./resources'); -var BasicAuthenticator = require('./auth/basic_authenticator'); -var OauthAuthenticator = require('./auth/oauth_authenticator'); -var App = require('./auth/app'); -var autoDetect = require('./auth/auto_detect'); - -/** - * Constructs a Client with instances of all the resources using the dispatcher. - * It also keeps a reference to the dispatcher so that way the end user can have - * access to it. - * @class - * @classdesc A wrapper for the Asana API which is authenticated for one user - * @param {Dispatcher} dispatcher The request dispatcher to use - * @param {Object} options Options to configure the client - * @param {String} [clientId] ID of the client, required for Oauth - * @param {String} [clientSecret] Secret key, for some Oauth flows - * @param {String} [redirectUri] Default redirect URI for this client - * @param {String} [asanaBaseUrl] Base URL for Asana, for debugging - */ -function Client(dispatcher, options) { - options = options || {}; - /** - * The internal dispatcher. This is mostly used by the resources but provided - * for custom requests to the API or API features that have not yet been added - * to the client. - * @type {Dispatcher} - */ - this.dispatcher = dispatcher; - /** - * An instance of the Attachments resource. - * @type {Attachments} - */ - this.attachments = new resources.Attachments(this.dispatcher); - /** - * An instance of the BatchAPI resource. - * @type {BatchAPI} - */ - this.batchAPI = new resources.BatchAPI(this.dispatcher); - /** - * An instance of the CustomFieldSettings resource. - * @type {CustomFieldSettings} - */ - this.customFieldSettings = new resources.CustomFieldSettings(this.dispatcher); - /** - * An instance of the CustomFields resource. - * @type {CustomFields} - */ - this.customFields = new resources.CustomFields(this.dispatcher); - /** - * An instance of the Events resource. - * @type {Events} - */ - this.events = new resources.Events(this.dispatcher); - /** - * An instance of the Jobs resource. - * @type {Jobs} - */ - this.jobs = new resources.Jobs(this.dispatcher); - /** - * An instance of the OrganizationExports resource. - * @type {Events} - */ - this.organizationExports = new resources.OrganizationExports(this.dispatcher); - /** - * An instance of the Portfolios resource. - * @type {Portfolios} - */ - this.portfolios = new resources.Portfolios(this.dispatcher); - /** - * An instance of the PortfolioMemberships resource. - * @type {PortfolioMemberships} - */ - this.portfolioMemberships = - new resources.PortfolioMemberships(this.dispatcher); - /** - * An instance of the Projects resource. - * @type {Projects} - */ - this.projects = new resources.Projects(this.dispatcher); - /** - * An instance of the ProjectMemberships resource. - * @type {ProjectMemberships} - */ - this.projectMemberships = new resources.ProjectMemberships(this.dispatcher); - /** - * An instance of the ProjectStatuses resource. - * @type {ProjectStatuses} - */ - this.projectStatuses = new resources.ProjectStatuses(this.dispatcher); - /** - * An instance of the Sections resource. - * @type {Sections} - */ - this.sections = new resources.Sections(this.dispatcher); - /** - * An instance of the Stories resource. - * @type {Stories} - */ - this.stories = new resources.Stories(this.dispatcher); - /** - * An instance of the Tags resource. - * @type {Tags} - */ - this.tags = new resources.Tags(this.dispatcher); - /** - * An instance of the Tasks resource. - * @type {Tasks} - */ - this.tasks = new resources.Tasks(this.dispatcher); - /** - * An instance of the Teams resource. - * @type {Teams} - */ - this.teams = new resources.Teams(this.dispatcher); - /** - * An instance of the Typeahead resource. - * @type {Teams} - */ - this.typeahead = new resources.Typeahead(this.dispatcher); - /** - * An instance of the Users resource. - * @type {Users} - */ - this.users = new resources.Users(this.dispatcher); - /** - * An instance of the UserTaskLists resource. - * @type {UserTaskLists} - */ - this.userTaskLists = new resources.UserTaskLists(this.dispatcher); - /** - * An instance of the Workspaces resource. - * @type {Workspaces} - */ - this.workspaces = new resources.Workspaces(this.dispatcher); - /** - * An instance of the WorkspaceMemberships resource. - * @type {Workspaces} - */ - this.workspaceMemberships = - new resources.WorkspaceMemberships(this.dispatcher); - /** - * An instance of the Webhooks resource. - * @type {Webhooks} - */ - this.webhooks = new resources.Webhooks(this.dispatcher); - - // Store off Oauth info. - this.app = new App(options); -} - -/** - * Ensures the client is authorized to make requests. Kicks off the - * configured Oauth flow, if any. - * - * @returns {Promise} A promise that resolves to this client when - * authorization is complete. - */ -Client.prototype.authorize = function() { - var me = this; - return me.dispatcher.authorize().then(function() { - return me; - }); -}; - -/** - * DEPRECATED: this only exists for backwards compatibility and - * will be removed in a future version of the client library. - * Configure the Client to use a user's PAT and then authenticate - * through HTTP Basic Authentication. - * @param {String} accessToken The Asana PAT of the user - * @return {Client} this - */ -Client.prototype.useBasicAuth = function(accessToken) { - this.dispatcher.setAuthenticator(new BasicAuthenticator(accessToken)); - return this; -}; - -/** - * Configure the client to authenticate using a Personal Access Token. - * @param {String} accessToken The Personal Access Token to use for - * authenticating requests. - * @return {Client} this - */ -Client.prototype.useAccessToken = function(accessToken) { - var authenticator = new OauthAuthenticator({ - credentials: accessToken - }); - - this.dispatcher.setAuthenticator(authenticator); - return this; -}; - -/** - * Configure the client to authenticate via Oauth. Credentials can be - * supplied, or they can be obtained by running an Oauth flow. - * @param {Object} options Options for Oauth. Includes any options for - * the selected flow. - * @option {Function} [flowType] Type of OauthFlow to use to obtain user - * authorization. Defaults to autodetect based on environment. - * @option {Object} [credentials] Credentials to use; no flow required to - * obtain authorization. This object should at a minimum contain an - * `access_token` string field. - * @option {Function} [refreshCredentialsCallback] An optional callback - * function to execute once the authenticator auto refreshes - * access credentials. - * For Example: - * function(credentials){ - * console.log("Your new credentials are:"+credentials) - * } - * @return {Client} this - */ -Client.prototype.useOauth = function(options) { - options = options || {}; - options.app = this.app; - - var FlowType = options.flowType || autoDetect(); - // If there are no credentials, then we can't proceed without a flow. - if (!options.credentials && FlowType === null) { - throw new Error('Could not autodetect Oauth flow type'); - } - var flow = new FlowType(options); - var authenticator = new OauthAuthenticator({ - app: this.app, - credentials: options.credentials, - flow: flow, - refreshCredentialsCallback: options.refreshCredentialsCallback || null - }); - - this.dispatcher.setAuthenticator(authenticator); - return this; -}; - -/** - * Creates a new client. - * @param {Object} options Options for specifying the client, see constructor. - */ -Client.create = function(options) { - options = options || {}; - return new Client( - new Dispatcher({ - asanaBaseUrl: options.asanaBaseUrl, - timeout: options.requestTimeout, - defaultHeaders: options.defaultHeaders, - defaultProxy: options.defaultProxy, - logAsanaChangeWarnings: options.logAsanaChangeWarnings - }), - options); -}; - -module.exports = Client; - -},{"./auth/app":2,"./auth/auto_detect":4,"./auth/basic_authenticator":6,"./auth/oauth_authenticator":10,"./dispatcher":17,"./resources":55}],16:[function(require,module,exports){ -(function (process){ -/* jshint browser: true */ -/* global chrome */ - -function defaultEnvironment() { - var env = {}; - if (typeof(window) !== 'undefined') { - // Browser - env.window = window; - } - if (typeof(chrome) !== 'undefined') { - // Chrome Extension - env.chrome = chrome; - } - if (typeof(process) !== 'undefined') { - // NodeJS script - env.process = process; - } - return env; -} - -module.exports = defaultEnvironment; - -}).call(this,require('_process')) -},{"_process":91}],17:[function(require,module,exports){ -(function (process){ -var errors = require('./errors'); -var Bluebird = require('bluebird'); -var request = require('request'); -var _ = require('lodash'); -var querystring = require('querystring'); - -var VERSION = require('../package.json').version; - -var STATUS_MAP = Object.keys(errors).reduce(function(map, key) { - var error = new errors[key](null); - if (error.status) { - map[error.status] = errors[key]; - } - return map; -}, {}); - -// TODO: Provide same set of options for each request as for configuration, -// so the config at construction time is just the "defaults" - -/** - * Creates a dispatcher which will act as a basic wrapper for making HTTP - * requests to the API, and handle authentication. - * @class - * @classdesc A HTTP wrapper for the Asana API - * @param {Object} options for default behavior of the Dispatcher - * @option {Authenticator} [authenticator] Object to use for authentication. - * Can also be set later with `setAuthenticator`. - * @option {String} [retryOnRateLimit] Automatically handle `RateLimitEnforced` - * errors by sleeping and retrying after the waiting period. - * @option {Function} [handleUnauthorized] Automatically handle - * `NoAuthorization` with the callback. If the callback returns `true` - * (or a promise resolving to `true), will retry the request. - * @option {String} [asanaBaseUrl] Base URL for Asana, for debugging - * @option {Number} [requestTimeout] Timeout (in milliseconds) to wait for the - * request to finish. - */ -function Dispatcher(options) { - options = options || {}; - /** - * The object to use to handle authentication. - * @type {Authenticator} - */ - this.authenticator = options.authenticator || null; - /** - * The base URL for Asana - * @type {String} - */ - this.asanaBaseUrl = options.asanaBaseUrl || 'https://app.asana.com/'; - /** - * Whether requests should be automatically retried if rate limited. - * @type {Boolean} - */ - this.retryOnRateLimit = options.retryOnRateLimit || false; - /** - * What headers should be included by default in all requests, if any. - * Can be overridden by individual requests. - * @type {Object} - */ - this.defaultHeaders = options.defaultHeaders || {}; - /** - * Handler for unauthorized requests which may seek reauthorization. - * Default behavior is available if configured with an Oauth authenticator - * that has a refresh token, and will refresh the current access token. - * @type {Function} - */ - this.handleUnauthorized = (options.handleUnauthorized !== undefined) ? - options.handleUnauthorized : Dispatcher.maybeReauthorize; - /** - * Version info gathered from the system, to send with the request. - * @type {Object} - */ - this._cachedVersionInfo = null; - - /** - * The amount of time in milliseconds to wait for a request to finish. - * @type {Number} - */ - this.requestTimeout = options.requestTimeout || null; - - /** - * What proxy should be used by default in all requests, if any. - * Can be overridden by individual requests. - * @type {String} - */ - this.defaultProxy = options.defaultProxy || null; - /** - * Whether the dispatcher logs the AsanaChange header or not. - * @type {boolean} - */ - this.logAsanaChangeWarnings = options.logAsanaChangeWarnings !== false; -} - -/** - * The relative API path for the current version of the Asana API. - * @type {String} - */ -Dispatcher.API_PATH = 'api/1.0'; - -/** - * Default handler for requests that are considered unauthorized. - * Requests that the authenticator try to refresh its credentials if - * possible. - * @return {Promise} True iff refresh was successful, false if not. - */ -Dispatcher.maybeReauthorize = function() { - if (!this.authenticator) { - return false; - } - return this.authenticator.refreshCredentials(); -}; - -/** - * Whether the request library should show debug logs - */ -Dispatcher.prototype.debug = function(flag) { - request.debug = flag; -}; - -/** - * Creates an Asana API Url by concatenating the ROOT_URL with path provided. - * @param {String} path The path - * @return {String} The url - */ -Dispatcher.prototype.url = function(path) { - return this.asanaBaseUrl + Dispatcher.API_PATH + path; -}; - -/** - * Configure the authentication mechanism to use. - * @returns {Dispatcher} this - */ -Dispatcher.prototype.setAuthenticator = function(authenticator) { - this.authenticator = authenticator; - return this; -}; - -/** - * Ensure the dispatcher is authorized to make requests. Call this before - * making any API requests. - * - * @returns {Promise} Resolves when the dispatcher is authorized, rejected if - * there was a problem authorizing. - */ -Dispatcher.prototype.authorize = function() { - if (this.authenticator === null) { - throw new Error('No authenticator configured for dispatcher'); - } - return this.authenticator.establishCredentials(); -}; - -/** - * Logs the Asana-Change header if the request is affected and - * has not Asana-Enabled the flag. - * @param {Object} reqHeaders headers in the request - * @param {Object} resHeaders headers in the response - */ -Dispatcher.prototype.logAsanaChangeHeader = function(reqHeaders, resHeaders) { - var changeHeaderKey = null; - - for (var key in resHeaders) { - if (key.toLowerCase() === 'asana-change') { - changeHeaderKey = key; - } - } - - if (changeHeaderKey !== null) { - var accountedForFlags = []; - - var addFlag = function(flag) { - accountedForFlags.push(flag.trim()); - }; - - // Grab the request's asana-enable flags - for (var reqHeader in reqHeaders) { - if (!reqHeaders.hasOwnProperty(reqHeader)) { - continue; - } - - if (reqHeader.toLowerCase() === 'asana-enable') { - reqHeaders[reqHeader].split(',').forEach(addFlag); - } else if (reqHeader.toLowerCase() === 'asana-disable') { - reqHeaders[reqHeader].split(',').forEach(addFlag); - } - } - - var changes = resHeaders[changeHeaderKey].split(','); - changes.forEach(function(unsplitChange) { - var change = unsplitChange.split(';'); - - var name = null; - var info = null; - var affected = null; - - for (var j = 0; j < change.length; j++) { - var field = change[j].split('='); - - field[0] = field[0].trim(); - if (field[0].trim() === 'name') { - name = field[1].trim(); - } - else if (field[0].trim() === 'info') { - info = field[1].trim(); - } - else if (field[0].trim() === 'affected') { - affected = field[1].trim(); - } - } - - // Only show the error if the flag was not in the request's - // asana-enable header - if (accountedForFlags.indexOf(name) === -1 && affected === 'true') { - var message = 'This request is affected by the "' + name + - '" deprecation. Please visit this url for more info: ' + info + - '\n' + 'Adding "' + name + '" to your "Asana-Enable" or ' + - '"Asana-Disable" header will opt in/out to this deprecation ' + - 'and suppress this warning.'; - - console.error(message); - } - }); - } -}; - -/** - * Dispatches a request to the Asana API. The request parameters are passed to - * the request module. - * @param {Object} params The params for request - * @param {Object} [dispatchOptions] Options for handling request/response - * @return {Promise} The response for the request - */ -Dispatcher.prototype.dispatch = function(params, dispatchOptions) { - var me = this; - // TODO: actually honor these options as overriding defaults - dispatchOptions = dispatchOptions || {}; - - if (this.requestTimeout) { - params.timeout = this.requestTimeout; - } - - if (this.defaultProxy) { - params.proxy = this.defaultProxy; - } - - return new Bluebird(function(resolve, reject) { - function doRequest() { - if (me.authenticator !== null) { - me.authenticator.authenticateRequest(params); - } - params.headers = _.extend( - {}, params.headers, me.defaultHeaders, dispatchOptions.headers || {}); - me._addVersionInfo(params); - request(params, function(err, res, payload) { - if (err) { - return reject(err); - } - - // Handle Asana-Change header logging - if (me.logAsanaChangeWarnings) { - me.logAsanaChangeHeader(params.headers, res.headers); - } - - if (STATUS_MAP[res.statusCode]) { - var error = new STATUS_MAP[res.statusCode](payload, res); - - if (me.retryOnRateLimit && - error instanceof (errors.RateLimitEnforced)) { - // Maybe attempt retry for rate limiting. - // Delay a half-second more in case of rounding error. - // TODO: verify Asana is always being conservative with duration - setTimeout(doRequest, error.retryAfterSeconds * 1000 + 500); - - } else if (me.handleUnauthorized && - error instanceof (errors.NoAuthorization)) { - // Maybe attempt to retry unauthorized requests after getting - // a new access token. - Bluebird.resolve(me.handleUnauthorized()).then(function(reauth) { - if (reauth) { - doRequest(); - } else { - reject(error); - } - }) - .catch(function() { - reject(error); - }); - } else { - // Not an error we can handle. - return reject(error); - } - } else { - return resolve(payload); - } - }); - } - doRequest(); - }); -}; - -/** - * Dispatches a GET request to the Asana API. - * @param {String} path The path of the API - * @param {Object} [query] The query params - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `dispatch`. - * @return {Promise} The response for the request - */ -Dispatcher.prototype.get = function(path, query, dispatchOptions) { - var params = { - method: 'GET', - url: this.url(path), - json: true - }; - var options = this._parseApiOptions(query); - if (options) { - params.qs = options; - } - - if (query) { - params.qs = Object.assign(query, params.qs); - } - return this.dispatch(params, dispatchOptions); -}; - -/** - * Dispatches a POST request to the Asana API. - * @param {String} path The path of the API - * @param {Object} data The data to be sent - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `dispatch`. - * @return {Promise} The response for the request - */ -Dispatcher.prototype.post = function(path, data, dispatchOptions) { - var params = { - method: 'POST', - url: this.url(path), - json: { - data: data - } - }; - var options = this._parseApiOptions(data); - if (options) { - params.qs = options; - } - - return this.dispatch(params, dispatchOptions); -}; - -/** - * Dispatches a PUT request to the Asana API. - * @param {String} path The path of the API - * @param {Object} data The data to be sent - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `dispatch`. - * @return {Promise} The response for the request - */ -Dispatcher.prototype.put = function(path, data, dispatchOptions) { - var params = { - method: 'PUT', - url: this.url(path), - json: { - data: data - } - }; - var options = this._parseApiOptions(data); - if (options) { - params.qs = options; - } - - return this.dispatch(params, dispatchOptions); -}; - -/** - * Dispatches a DELETE request to the Asana API. - * @param {String} path The path of the API - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `dispatch`. - * @return {Promise} The response for the request - */ -Dispatcher.prototype.delete = function(path, dispatchOptions) { - var params = { - method: 'DELETE', - url: this.url(path) - }; - - return this.dispatch(params, dispatchOptions); -}; - -/** - * @param request {Object} Request to add version header to. - * @private - */ -Dispatcher.prototype._addVersionInfo = function(request) { - if (!this._cachedVersionInfo) { - this._cachedVersionInfo = this._generateVersionInfo(); - } - request.headers = request.headers || {}; - request.headers['X-Asana-Client-Lib'] = - querystring.stringify(this._cachedVersionInfo); -}; - -/** - * @return {Object} Dictionary of key-value pairs indicating library version - * @private - */ -Dispatcher.prototype._generateVersionInfo = function() { - if (typeof(navigator) === 'undefined' || typeof(window) === 'undefined') { - return { - 'version': VERSION, - 'language': 'NodeJS', - 'language_version': process.version, - 'os': process.platform - }; - } else { - return { - 'version': VERSION, - 'language': 'BrowserJS' - }; - } -}; - -Dispatcher.prototype._parseApiOptions = function(params) { - if (!params) { - return null; - } - - var optionKeys = ['pretty', 'fields', 'expand']; - var options = {}; - - for (var i = 0; i < optionKeys.length; i++) { - if (params.hasOwnProperty(optionKeys[i])) { - options['opt_' + optionKeys[i]] = params[optionKeys[i]]; - } - } - - return options; -}; - -module.exports = Dispatcher; - -}).call(this,require('_process')) -},{"../package.json":120,"./errors":20,"_process":91,"bluebird":80,"lodash":90,"querystring":95,"request":81}],18:[function(require,module,exports){ -function AsanaError(message) { - this.message = message; - try { - throw new Error(message); - } catch (e) { - this.stack = e.stack; - } -} - -AsanaError.prototype = Object.create(Error.prototype); - -module.exports = AsanaError; -},{}],19:[function(require,module,exports){ -var util = require('util'); -var AsanaError = require('./error'); - -function Forbidden(value) { - AsanaError.call(this, 'Forbidden'); - this.status = 403; - this.value = value; -} - -util.inherits(Forbidden, Error); - -module.exports = Forbidden; -},{"./error":18,"util":119}],20:[function(require,module,exports){ -exports.Forbidden = require('./forbidden'); -exports.InvalidRequest = require('./invalid_request'); -exports.NoAuthorization = require('./no_authorization'); -exports.NotFound = require('./not_found'); -exports.PremiumOnly = require('./premium_only'); -exports.RateLimitEnforced = require('./rate_limit_enforced'); -exports.ServerError = require('./server_error'); - -},{"./forbidden":19,"./invalid_request":21,"./no_authorization":22,"./not_found":23,"./premium_only":24,"./rate_limit_enforced":25,"./server_error":26}],21:[function(require,module,exports){ -var util = require('util'); -var AsanaError = require('./error'); - -function InvalidRequest(value) { - AsanaError.call(this, 'Invalid Request'); - this.status = 400; - this.value = value; -} - -util.inherits(InvalidRequest, Error); - -module.exports = InvalidRequest; -},{"./error":18,"util":119}],22:[function(require,module,exports){ -var util = require('util'); -var AsanaError = require('./error'); - -function NoAuthorization(value) { - AsanaError.call(this, 'No Authorization'); - this.status = 401; - this.value = value; -} - -util.inherits(NoAuthorization, Error); - -module.exports = NoAuthorization; -},{"./error":18,"util":119}],23:[function(require,module,exports){ -var util = require('util'); -var AsanaError = require('./error'); - -function NotFound(value) { - AsanaError.call(this, 'Not Found'); - this.status = 404; - this.value = value; -} - -util.inherits(NotFound, Error); - -module.exports = NotFound; -},{"./error":18,"util":119}],24:[function(require,module,exports){ -var util = require('util'); -var AsanaError = require('./error'); - -function PremiumOnly(value) { - AsanaError.call(this, 'Payment Required'); - this.status = 402; - this.value = value; -} - -util.inherits(PremiumOnly, Error); - -module.exports = PremiumOnly; - -},{"./error":18,"util":119}],25:[function(require,module,exports){ -var util = require('util'); -var AsanaError = require('./error'); - -function RateLimitEnforced(value, res) { - /* jshint camelcase:false */ - AsanaError.call(this, 'Rate Limit Enforced'); - this.status = 429; - this.value = value; - this.retryAfterSeconds = value && parseInt( - value.retry_after || res.headers['retry-after'], - 10 - ); -} - -util.inherits(RateLimitEnforced, Error); - -module.exports = RateLimitEnforced; -},{"./error":18,"util":119}],26:[function(require,module,exports){ -var util = require('util'); -var AsanaError = require('./error'); - -function ServerError(value) { - AsanaError.call(this, 'Server Error'); - this.status = 500; - this.value = value; -} - -util.inherits(ServerError, Error); - -module.exports = ServerError; -},{"./error":18,"util":119}],27:[function(require,module,exports){ -var Attachments = require('./gen/attachments'); -/* jshint ignore:start */ -var util = require('util'); - -/** - * Returns the full record for a single attachment. - * @param {String} attachment Globally unique identifier for the attachment. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher - * for the request - * @return {Promise} The requested resource - */ -Attachments.prototype.findById = function( - attachment, - params, - dispatchOptions -) { - var path = util.format('/attachments/%s', attachment); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * Returns the compact records for all attachments on the task. - * @param {String} task Globally unique identifier for the task. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher - * for the request - * @return {Promise} The response from the API - */ -Attachments.prototype.findByTask = function( - task, - params, - dispatchOptions -) { - var path = util.format('/tasks/%s/attachments', task); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - - -/* jshint ignore:end */ -module.exports = Attachments; - -},{"./gen/attachments":32,"util":119}],28:[function(require,module,exports){ -var BatchAPI = require('./gen/batch_api'); - -module.exports = BatchAPI; - -},{"./gen/batch_api":33}],29:[function(require,module,exports){ -var CustomFieldSettings = require('./gen/custom_field_settings'); -/* jshint ignore:start */ -var util = require('util'); - -/** - * Returns a list of all of the custom fields settings on a project. - * @param {String} project The ID of the project for which to list custom field settings - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -CustomFieldSettings.prototype.findByProject = function( - project, - params, - dispatchOptions -) { - var path = util.format('/projects/%s/custom_field_settings', project); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Returns a list of all of the custom fields settings on a portfolio. - * @param {String} portfolio The ID of the portfolio for which to list custom field settings - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -CustomFieldSettings.prototype.findByPortfolio = function( - portfolio, - params, - dispatchOptions -) { - var path = util.format('/portfolios/%s/custom_field_settings', portfolio); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - - -/* jshint ignore:end */ -module.exports = CustomFieldSettings; - -},{"./gen/custom_field_settings":34,"util":119}],30:[function(require,module,exports){ -var CustomFields = require('./gen/custom_fields'); -/* jshint ignore:start */ -var util = require('util'); - -/** - * Creates a new custom field in a workspace. Every custom field is required to be created in a specific workspace, and this workspace cannot be changed once set. - * - * A custom field's `name` must be unique within a workspace and not conflict with names of existing task properties such as 'Due Date' or 'Assignee'. A custom field's `type` must be one of 'text', 'enum', or 'number'. - * - * Returns the full record of the newly created custom field. - * @param {Object} data Data for the request - * @param {String} data.workspace The workspace to create a custom field in. - * @param {String} data.resource_subtype The type of the custom field. Must be one of the given values. - * @param {String} [data.type] **Deprecated: New integrations should prefer the `resource_subtype` parameter.** - * @param {String} data.name The name of the custom field. - * @param {String} [data.description] The description of the custom field. - * @param {Integer} [data.precision] The number of decimal places for the numerical values. Required if the custom field is of type 'number'. - * @param {String} [data.enum_options] The discrete values the custom field can assume. Required if the custom field is of type 'enum'. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -CustomFields.prototype.create = function( - data, - dispatchOptions -) { - var path = util.format('/custom_fields'); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Returns the complete definition of a custom field's metadata. - * @param {String} custom_field Globally unique identifier for the custom field. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -CustomFields.prototype.findById = function( - customField, - params, - dispatchOptions -) { - var path = util.format('/custom_fields/%s', customField); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * Returns a list of the compact representation of all of the custom fields in a workspace. - * @param {String} workspace The workspace or organization to find custom field definitions in. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -CustomFields.prototype.findByWorkspace = function( - workspace, - params, - dispatchOptions -) { - var path = util.format('/workspaces/%s/custom_fields', workspace); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * A specific, existing custom field can be updated by making a PUT request on the URL for that custom field. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged - * - * When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the custom field. - * - * An enum custom field's `enum_options` cannot be updated with this endpoint. Instead see "Work With Enum Options" for information on how to update `enum_options`. - * - * Locked custom fields can only be updated by the user who locked the field. - * - * Returns the complete updated custom field record. - * @param {String} custom_field Globally unique identifier for the custom field. - * @param {Object} data Data for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -CustomFields.prototype.update = function( - customField, - data, - dispatchOptions -) { - var path = util.format('/custom_fields/%s', customField); - - return this.dispatchPut(path, data, dispatchOptions); -}; - -/** - * A specific, existing custom field can be deleted by making a DELETE request on the URL for that custom field. - * - * Locked custom fields can only be deleted by the user who locked the field. - * - * Returns an empty data record. - * @param {String} custom_field Globally unique identifier for the custom field. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -CustomFields.prototype.delete = function( - customField, - dispatchOptions -) { - var path = util.format('/custom_fields/%s', customField); - - return this.dispatchDelete(path, dispatchOptions); -}; - -/** - * Creates an enum option and adds it to this custom field's list of enum options. A custom field can have at most 50 enum options (including disabled options). By default new enum options are inserted at the end of a custom field's list. - * - * Locked custom fields can only have enum options added by the user who locked the field. - * - * Returns the full record of the newly created enum option. - * @param {String} custom_field Globally unique identifier for the custom field. - * @param {Object} data Data for the request - * @param {String} data.name The name of the enum option. - * @param {String} [data.color] The color of the enum option. Defaults to 'none'. - * @param {String} [data.insert_before] An existing enum option within this custom field before which the new enum option should be inserted. Cannot be provided together with after_enum_option. - * @param {String} [data.insert_after] An existing enum option within this custom field after which the new enum option should be inserted. Cannot be provided together with before_enum_option. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -CustomFields.prototype.createEnumOption = function( - customField, - data, - dispatchOptions -) { - var path = util.format('/custom_fields/%s/enum_options', customField); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Updates an existing enum option. Enum custom fields require at least one enabled enum option. - * - * Locked custom fields can only be updated by the user who locked the field. - * - * Returns the full record of the updated enum option. - * @param {String} enum_option Globally unique identifier for the enum option. - * @param {Object} data Data for the request - * @param {String} data.name The name of the enum option. - * @param {String} [data.color] The color of the enum option. Defaults to 'none'. - * @param {Boolean} [data.enabled] Whether or not the enum option is a selectable value for the custom field. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -CustomFields.prototype.updateEnumOption = function( - enumOption, - data, - dispatchOptions -) { - var path = util.format('/enum_options/%s', enumOption); - - return this.dispatchPut(path, data, dispatchOptions); -}; - -/** - * Moves a particular enum option to be either before or after another specified enum option in the custom field. - * - * Locked custom fields can only be reordered by the user who locked the field. - * @param {String} custom_field Globally unique identifier for the custom field. - * @param {Object} data Data for the request - * @param {String} data.enum_option The ID of the enum option to relocate. - * @param {String} data.name The name of the enum option. - * @param {String} [data.color] The color of the enum option. Defaults to 'none'. - * @param {String} [data.before_enum_option] An existing enum option within this custom field before which the new enum option should be inserted. Cannot be provided together with after_enum_option. - * @param {String} [data.after_enum_option] An existing enum option within this custom field after which the new enum option should be inserted. Cannot be provided together with before_enum_option. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -CustomFields.prototype.insertEnumOption = function( - customField, - data, - dispatchOptions -) { - var path = util.format('/custom_fields/%s/enum_options/insert', customField); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * This is for compatibility reasons. Please use createEnumOption. - */ -CustomFields.prototype.addEnumOption = CustomFields.prototype.createEnumOption; - -/** - * This is for compatibility reasons. Please use createEnumOption. - */ -CustomFields.prototype.reorderEnumOption = - CustomFields.prototype.insertEnumOption; - - -/* jshint ignore:end */ -module.exports = CustomFields; - -},{"./gen/custom_fields":35,"util":119}],31:[function(require,module,exports){ -var EventStream = require('../util/event_stream'); -var Events = require('./gen/events'); -/* jshint ignore:start */ -var util = require('util'); - -/** - * Dispatches a GET request to /events of the API to get a set of recent - * changes to a resource. - * @param {Number} resourceId The id of the resource to get events for - * @param {String} [syncToken] Token from a previous sync, if any - * @param {Object} [params] Parameters for the request - * @return {Promise} The result of the API call: - * {String} sync The new sync token to use for the next request - * {Object[]} [data] The changes on the resource since the last sync, - * may not exist if sync token is new. - */ -Events.prototype.get = function(resourceId, syncToken, params) { - var requestParams = params || {}; - requestParams.resource = resourceId; - if (syncToken) { - requestParams.sync = syncToken; - } - return this.dispatcher.get('/events', requestParams); -}; - -/** - * Begins polling the /events endpoint of the API to listen to changes - * to a resource. - * @param {Number} resourceId The id of the resource to get events for - * @param {Object} [options] Additional options to pass the stream. - * {Number} periodSeconds - * @return {EventStream} An EventEmitter that emits notifications - * about changes. - */ -Events.prototype.stream = function(resourceId, options) { - return new EventStream(this, resourceId, options); -}; - -/* jshint ignore:end */ -Events.EventStream = EventStream; -module.exports = Events; - -},{"../util/event_stream":77,"./gen/events":36,"util":119}],32:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function Attachments(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(Attachments, Resource); - - -/** - * Delete an attachment - * @param {String} attachmentGid: (required) Globally unique identifier for the attachment. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Attachments.prototype.deleteAttachment = function( - attachmentGid, - data, - dispatchOptions -) { - var path = "/attachments/{attachment_gid}".replace("{attachment_gid}", attachmentGid); - - return this.dispatchDelete(path, data, dispatchOptions) -}; - - -/** - * Get an attachment - * @param {String} attachmentGid: (required) Globally unique identifier for the attachment. - * @param {Object} params: Parameters for the request - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Attachments.prototype.getAttachment = function( - attachmentGid, - params, - dispatchOptions -) { - var path = "/attachments/{attachment_gid}".replace("{attachment_gid}", attachmentGid); - - return this.dispatchGet(path, params, dispatchOptions) -}; - - -/** - * Get attachments for a task - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Attachments.prototype.getAttachmentsForTask = function( - taskGid, - params, - dispatchOptions -) { - var path = "/tasks/{task_gid}/attachments".replace("{task_gid}", taskGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - -module.exports = Attachments; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],33:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function BatchAPI(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(BatchAPI, Resource); - - -/** - * Submit parallel requests - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -BatchAPI.prototype.createBatchRequest = function( - data, - dispatchOptions -) { - var path = "/batch"; - - return this.dispatchPost(path, data, dispatchOptions) -}; - -module.exports = BatchAPI; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],34:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function CustomFieldSettings(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(CustomFieldSettings, Resource); - - -/** - * Get a portfolio's custom fields - * @param {String} portfolioGid: (required) Globally unique identifier for the portfolio. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -CustomFieldSettings.prototype.getCustomFieldSettingsForPortfolio = function( - portfolioGid, - params, - dispatchOptions -) { - var path = "/portfolios/{portfolio_gid}/custom_field_settings".replace("{portfolio_gid}", portfolioGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get a project's custom fields - * @param {String} projectGid: (required) Globally unique identifier for the project. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -CustomFieldSettings.prototype.getCustomFieldSettingsForProject = function( - projectGid, - params, - dispatchOptions -) { - var path = "/projects/{project_gid}/custom_field_settings".replace("{project_gid}", projectGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - -module.exports = CustomFieldSettings; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],35:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function CustomFields(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(CustomFields, Resource); - - -/** - * Create a custom field - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -CustomFields.prototype.createCustomField = function( - data, - dispatchOptions -) { - var path = "/custom_fields"; - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Create an enum option - * @param {String} customFieldGid: (required) Globally unique identifier for the custom field. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -CustomFields.prototype.createEnumOptionForCustomField = function( - customFieldGid, - data, - dispatchOptions -) { - var path = "/custom_fields/{custom_field_gid}/enum_options".replace("{custom_field_gid}", customFieldGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Delete a custom field - * @param {String} customFieldGid: (required) Globally unique identifier for the custom field. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -CustomFields.prototype.deleteCustomField = function( - customFieldGid, - data, - dispatchOptions -) { - var path = "/custom_fields/{custom_field_gid}".replace("{custom_field_gid}", customFieldGid); - - return this.dispatchDelete(path, data, dispatchOptions) -}; - - -/** - * Get a custom field - * @param {String} customFieldGid: (required) Globally unique identifier for the custom field. - * @param {Object} params: Parameters for the request - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -CustomFields.prototype.getCustomField = function( - customFieldGid, - params, - dispatchOptions -) { - var path = "/custom_fields/{custom_field_gid}".replace("{custom_field_gid}", customFieldGid); - - return this.dispatchGet(path, params, dispatchOptions) -}; - - -/** - * Get a workspace's custom fields - * @param {String} workspaceGid: (required) Globally unique identifier for the workspace or organization. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -CustomFields.prototype.getCustomFieldsForWorkspace = function( - workspaceGid, - params, - dispatchOptions -) { - var path = "/workspaces/{workspace_gid}/custom_fields".replace("{workspace_gid}", workspaceGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Reorder a custom field's enum - * @param {String} customFieldGid: (required) Globally unique identifier for the custom field. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -CustomFields.prototype.insertEnumOptionForCustomField = function( - customFieldGid, - data, - dispatchOptions -) { - var path = "/custom_fields/{custom_field_gid}/enum_options/insert".replace("{custom_field_gid}", customFieldGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Update a custom field - * @param {String} customFieldGid: (required) Globally unique identifier for the custom field. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -CustomFields.prototype.updateCustomField = function( - customFieldGid, - data, - dispatchOptions -) { - var path = "/custom_fields/{custom_field_gid}".replace("{custom_field_gid}", customFieldGid); - - return this.dispatchPut(path, data, dispatchOptions) -}; - - -/** - * Update an enum option - * @param {String} enumOptionGid: (required) Globally unique identifier for the enum option. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -CustomFields.prototype.updateEnumOption = function( - enumOptionGid, - data, - dispatchOptions -) { - var path = "/enum_options/{enum_option_gid}".replace("{enum_option_gid}", enumOptionGid); - - return this.dispatchPut(path, data, dispatchOptions) -}; - -module.exports = CustomFields; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],36:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function Events(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(Events, Resource); - - -/** - * Get events on a resource - * @param {Object} params: Parameters for the request - - resource {String}: (required) A resource ID to subscribe to. The resource can be a task or project. - - sync {String}: A sync token received from the last request, or none on first sync. Events will be returned from the point in time that the sync token was generated. *Note: On your first request, omit the sync token. The response will be the same as for an expired sync token, and will include a new valid sync token.If the sync token is too old (which may happen from time to time) the API will return a `412 Precondition Failed` error, and include a fresh sync token in the response.* - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Events.prototype.getEvents = function( - params, - dispatchOptions -) { - var path = "/events"; - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - -module.exports = Events; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],37:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function Jobs(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(Jobs, Resource); - - -/** - * Get a job by id - * @param {String} jobGid: (required) Globally unique identifier for the job. - * @param {Object} params: Parameters for the request - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Jobs.prototype.getJob = function( - jobGid, - params, - dispatchOptions -) { - var path = "/jobs/{job_gid}".replace("{job_gid}", jobGid); - - return this.dispatchGet(path, params, dispatchOptions) -}; - -module.exports = Jobs; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],38:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function OrganizationExports(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(OrganizationExports, Resource); - - -/** - * Create an organization export request - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -OrganizationExports.prototype.createOrganizationExport = function( - data, - dispatchOptions -) { - var path = "/organization_exports"; - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Get details on an org export request - * @param {String} organizationExportGid: (required) Globally unique identifier for the organization export. - * @param {Object} params: Parameters for the request - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -OrganizationExports.prototype.getOrganizationExport = function( - organizationExportGid, - params, - dispatchOptions -) { - var path = "/organization_exports/{organization_export_gid}".replace("{organization_export_gid}", organizationExportGid); - - return this.dispatchGet(path, params, dispatchOptions) -}; - -module.exports = OrganizationExports; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],39:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function PortfolioMemberships(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(PortfolioMemberships, Resource); - - -/** - * Get a portfolio membership - * @param {String} portfolioMembershipGid: (required) - * @param {Object} params: Parameters for the request - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -PortfolioMemberships.prototype.getPortfolioMembership = function( - portfolioMembershipGid, - params, - dispatchOptions -) { - var path = "/portfolio_memberships/{portfolio_membership_gid}".replace("{portfolio_membership_gid}", portfolioMembershipGid); - - return this.dispatchGet(path, params, dispatchOptions) -}; - - -/** - * Get multiple portfolio memberships - * @param {Object} params: Parameters for the request - - portfolio {String}: The portfolio to filter results on. - - workspace {String}: The workspace to filter results on. - - user {String}: A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -PortfolioMemberships.prototype.getPortfolioMemberships = function( - params, - dispatchOptions -) { - var path = "/portfolio_memberships"; - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get memberships from a portfolio - * @param {String} portfolioGid: (required) Globally unique identifier for the portfolio. - * @param {Object} params: Parameters for the request - - user {String}: A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -PortfolioMemberships.prototype.getPortfolioMembershipsForPortfolio = function( - portfolioGid, - params, - dispatchOptions -) { - var path = "/portfolios/{portfolio_gid}/portfolio_memberships".replace("{portfolio_gid}", portfolioGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - -module.exports = PortfolioMemberships; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],40:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function Portfolios(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(Portfolios, Resource); - - -/** - * Add a custom field to a portfolio - * @param {String} portfolioGid: (required) Globally unique identifier for the portfolio. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Portfolios.prototype.addCustomFieldSettingForPortfolio = function( - portfolioGid, - data, - dispatchOptions -) { - var path = "/portfolios/{portfolio_gid}/addCustomFieldSetting".replace("{portfolio_gid}", portfolioGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Add a portfolio item - * @param {String} portfolioGid: (required) Globally unique identifier for the portfolio. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Portfolios.prototype.addItemForPortfolio = function( - portfolioGid, - data, - dispatchOptions -) { - var path = "/portfolios/{portfolio_gid}/addItem".replace("{portfolio_gid}", portfolioGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Add users to a portfolio - * @param {String} portfolioGid: (required) Globally unique identifier for the portfolio. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Portfolios.prototype.addMembersForPortfolio = function( - portfolioGid, - data, - dispatchOptions -) { - var path = "/portfolios/{portfolio_gid}/addMembers".replace("{portfolio_gid}", portfolioGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Create a portfolio - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Portfolios.prototype.createPortfolio = function( - data, - dispatchOptions -) { - var path = "/portfolios"; - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Delete a portfolio - * @param {String} portfolioGid: (required) Globally unique identifier for the portfolio. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Portfolios.prototype.deletePortfolio = function( - portfolioGid, - data, - dispatchOptions -) { - var path = "/portfolios/{portfolio_gid}".replace("{portfolio_gid}", portfolioGid); - - return this.dispatchDelete(path, data, dispatchOptions) -}; - - -/** - * Get portfolio items - * @param {String} portfolioGid: (required) Globally unique identifier for the portfolio. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Portfolios.prototype.getItemsForPortfolio = function( - portfolioGid, - params, - dispatchOptions -) { - var path = "/portfolios/{portfolio_gid}/items".replace("{portfolio_gid}", portfolioGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get a portfolio - * @param {String} portfolioGid: (required) Globally unique identifier for the portfolio. - * @param {Object} params: Parameters for the request - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Portfolios.prototype.getPortfolio = function( - portfolioGid, - params, - dispatchOptions -) { - var path = "/portfolios/{portfolio_gid}".replace("{portfolio_gid}", portfolioGid); - - return this.dispatchGet(path, params, dispatchOptions) -}; - - -/** - * Get multiple portfolios - * @param {Object} params: Parameters for the request - - workspace {String}: The workspace or organization to filter portfolios on. - - owner {String}: (required) The user who owns the portfolio. Currently, API users can only get a list of portfolios that they themselves own. - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Portfolios.prototype.getPortfolios = function( - params, - dispatchOptions -) { - var path = "/portfolios"; - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Remove a custom field from a portfolio - * @param {String} portfolioGid: (required) Globally unique identifier for the portfolio. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Portfolios.prototype.removeCustomFieldSettingForPortfolio = function( - portfolioGid, - data, - dispatchOptions -) { - var path = "/portfolios/{portfolio_gid}/removeCustomFieldSetting".replace("{portfolio_gid}", portfolioGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Remove a portfolio item - * @param {String} portfolioGid: (required) Globally unique identifier for the portfolio. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Portfolios.prototype.removeItemForPortfolio = function( - portfolioGid, - data, - dispatchOptions -) { - var path = "/portfolios/{portfolio_gid}/removeItem".replace("{portfolio_gid}", portfolioGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Remove users from a portfolio - * @param {String} portfolioGid: (required) Globally unique identifier for the portfolio. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Portfolios.prototype.removeMembersForPortfolio = function( - portfolioGid, - data, - dispatchOptions -) { - var path = "/portfolios/{portfolio_gid}/removeMembers".replace("{portfolio_gid}", portfolioGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Update a portfolio - * @param {String} portfolioGid: (required) Globally unique identifier for the portfolio. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Portfolios.prototype.updatePortfolio = function( - portfolioGid, - data, - dispatchOptions -) { - var path = "/portfolios/{portfolio_gid}".replace("{portfolio_gid}", portfolioGid); - - return this.dispatchPut(path, data, dispatchOptions) -}; - -module.exports = Portfolios; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],41:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function ProjectMemberships(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(ProjectMemberships, Resource); - - -/** - * Get a project membership - * @param {String} projectMembershipGid: (required) - * @param {Object} params: Parameters for the request - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -ProjectMemberships.prototype.getProjectMembership = function( - projectMembershipGid, - params, - dispatchOptions -) { - var path = "/project_memberships/{project_membership_gid}".replace("{project_membership_gid}", projectMembershipGid); - - return this.dispatchGet(path, params, dispatchOptions) -}; - - -/** - * Get memberships from a project - * @param {String} projectGid: (required) Globally unique identifier for the project. - * @param {Object} params: Parameters for the request - - user {String}: A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -ProjectMemberships.prototype.getProjectMembershipsForProject = function( - projectGid, - params, - dispatchOptions -) { - var path = "/projects/{project_gid}/project_memberships".replace("{project_gid}", projectGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - -module.exports = ProjectMemberships; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],42:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function ProjectStatuses(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(ProjectStatuses, Resource); - - -/** - * Create a project status - * @param {String} projectGid: (required) Globally unique identifier for the project. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -ProjectStatuses.prototype.createProjectStatusForProject = function( - projectGid, - data, - dispatchOptions -) { - var path = "/projects/{project_gid}/project_statuses".replace("{project_gid}", projectGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Delete a project status - * @param {String} projectStatusGid: (required) The project status update to get. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -ProjectStatuses.prototype.deleteProjectStatus = function( - projectStatusGid, - data, - dispatchOptions -) { - var path = "/project_statuses/{project_status_gid}".replace("{project_status_gid}", projectStatusGid); - - return this.dispatchDelete(path, data, dispatchOptions) -}; - - -/** - * Get a project status - * @param {String} projectStatusGid: (required) The project status update to get. - * @param {Object} params: Parameters for the request - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -ProjectStatuses.prototype.getProjectStatus = function( - projectStatusGid, - params, - dispatchOptions -) { - var path = "/project_statuses/{project_status_gid}".replace("{project_status_gid}", projectStatusGid); - - return this.dispatchGet(path, params, dispatchOptions) -}; - - -/** - * Get statuses from a project - * @param {String} projectGid: (required) Globally unique identifier for the project. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -ProjectStatuses.prototype.getProjectStatusesForProject = function( - projectGid, - params, - dispatchOptions -) { - var path = "/projects/{project_gid}/project_statuses".replace("{project_gid}", projectGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - -module.exports = ProjectStatuses; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],43:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function Projects(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(Projects, Resource); - - -/** - * Add a custom field to a project - * @param {String} projectGid: (required) Globally unique identifier for the project. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Projects.prototype.addCustomFieldSettingForProject = function( - projectGid, - data, - dispatchOptions -) { - var path = "/projects/{project_gid}/addCustomFieldSetting".replace("{project_gid}", projectGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Add followers to a project - * @param {String} projectGid: (required) Globally unique identifier for the project. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Projects.prototype.addFollowersForProject = function( - projectGid, - data, - dispatchOptions -) { - var path = "/projects/{project_gid}/addFollowers".replace("{project_gid}", projectGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Add users to a project - * @param {String} projectGid: (required) Globally unique identifier for the project. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Projects.prototype.addMembersForProject = function( - projectGid, - data, - dispatchOptions -) { - var path = "/projects/{project_gid}/addMembers".replace("{project_gid}", projectGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Create a project - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Projects.prototype.createProject = function( - data, - dispatchOptions -) { - var path = "/projects"; - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Create a project in a team - * @param {String} teamGid: (required) Globally unique identifier for the team. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Projects.prototype.createProjectForTeam = function( - teamGid, - data, - dispatchOptions -) { - var path = "/teams/{team_gid}/projects".replace("{team_gid}", teamGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Create a project in a workspace - * @param {String} workspaceGid: (required) Globally unique identifier for the workspace or organization. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Projects.prototype.createProjectForWorkspace = function( - workspaceGid, - data, - dispatchOptions -) { - var path = "/workspaces/{workspace_gid}/projects".replace("{workspace_gid}", workspaceGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Delete a project - * @param {String} projectGid: (required) Globally unique identifier for the project. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Projects.prototype.deleteProject = function( - projectGid, - data, - dispatchOptions -) { - var path = "/projects/{project_gid}".replace("{project_gid}", projectGid); - - return this.dispatchDelete(path, data, dispatchOptions) -}; - - -/** - * Duplicate a project - * @param {String} projectGid: (required) Globally unique identifier for the project. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Projects.prototype.duplicateProject = function( - projectGid, - data, - dispatchOptions -) { - var path = "/projects/{project_gid}/duplicate".replace("{project_gid}", projectGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Get a project - * @param {String} projectGid: (required) Globally unique identifier for the project. - * @param {Object} params: Parameters for the request - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Projects.prototype.getProject = function( - projectGid, - params, - dispatchOptions -) { - var path = "/projects/{project_gid}".replace("{project_gid}", projectGid); - - return this.dispatchGet(path, params, dispatchOptions) -}; - - -/** - * Get multiple projects - * @param {Object} params: Parameters for the request - - workspace {String}: The workspace or organization to filter projects on. - - team {String}: The team to filter projects on. - - archived {Boolean}: Only return projects whose `archived` field takes on the value of this parameter. - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Projects.prototype.getProjects = function( - params, - dispatchOptions -) { - var path = "/projects"; - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get projects a task is in - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Projects.prototype.getProjectsForTask = function( - taskGid, - params, - dispatchOptions -) { - var path = "/tasks/{task_gid}/projects".replace("{task_gid}", taskGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get a team's projects - * @param {String} teamGid: (required) Globally unique identifier for the team. - * @param {Object} params: Parameters for the request - - archived {Boolean}: Only return projects whose `archived` field takes on the value of this parameter. - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Projects.prototype.getProjectsForTeam = function( - teamGid, - params, - dispatchOptions -) { - var path = "/teams/{team_gid}/projects".replace("{team_gid}", teamGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get all projects in a workspace - * @param {String} workspaceGid: (required) Globally unique identifier for the workspace or organization. - * @param {Object} params: Parameters for the request - - archived {Boolean}: Only return projects whose `archived` field takes on the value of this parameter. - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Projects.prototype.getProjectsForWorkspace = function( - workspaceGid, - params, - dispatchOptions -) { - var path = "/workspaces/{workspace_gid}/projects".replace("{workspace_gid}", workspaceGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get task count of a project - * @param {String} projectGid: (required) Globally unique identifier for the project. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Projects.prototype.getTaskCountsForProject = function( - projectGid, - params, - dispatchOptions -) { - var path = "/projects/{project_gid}/task_counts".replace("{project_gid}", projectGid); - - return this.dispatchGet(path, params, dispatchOptions) -}; - - -/** - * Remove a custom field from a project - * @param {String} projectGid: (required) Globally unique identifier for the project. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Projects.prototype.removeCustomFieldSettingForProject = function( - projectGid, - data, - dispatchOptions -) { - var path = "/projects/{project_gid}/removeCustomFieldSetting".replace("{project_gid}", projectGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Remove followers from a project - * @param {String} projectGid: (required) Globally unique identifier for the project. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Projects.prototype.removeFollowersForProject = function( - projectGid, - data, - dispatchOptions -) { - var path = "/projects/{project_gid}/removeFollowers".replace("{project_gid}", projectGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Remove users from a project - * @param {String} projectGid: (required) Globally unique identifier for the project. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Projects.prototype.removeMembersForProject = function( - projectGid, - data, - dispatchOptions -) { - var path = "/projects/{project_gid}/removeMembers".replace("{project_gid}", projectGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Update a project - * @param {String} projectGid: (required) Globally unique identifier for the project. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Projects.prototype.updateProject = function( - projectGid, - data, - dispatchOptions -) { - var path = "/projects/{project_gid}".replace("{project_gid}", projectGid); - - return this.dispatchPut(path, data, dispatchOptions) -}; - -module.exports = Projects; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],44:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function Sections(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(Sections, Resource); - - -/** - * Add task to section - * @param {String} sectionGid: (required) The globally unique identifier for the section. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Sections.prototype.addTaskForSection = function( - sectionGid, - data, - dispatchOptions -) { - var path = "/sections/{section_gid}/addTask".replace("{section_gid}", sectionGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Create a section in a project - * @param {String} projectGid: (required) Globally unique identifier for the project. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Sections.prototype.createSectionForProject = function( - projectGid, - data, - dispatchOptions -) { - var path = "/projects/{project_gid}/sections".replace("{project_gid}", projectGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Delete a section - * @param {String} sectionGid: (required) The globally unique identifier for the section. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Sections.prototype.deleteSection = function( - sectionGid, - data, - dispatchOptions -) { - var path = "/sections/{section_gid}".replace("{section_gid}", sectionGid); - - return this.dispatchDelete(path, data, dispatchOptions) -}; - - -/** - * Get a section - * @param {String} sectionGid: (required) The globally unique identifier for the section. - * @param {Object} params: Parameters for the request - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Sections.prototype.getSection = function( - sectionGid, - params, - dispatchOptions -) { - var path = "/sections/{section_gid}".replace("{section_gid}", sectionGid); - - return this.dispatchGet(path, params, dispatchOptions) -}; - - -/** - * Get sections in a project - * @param {String} projectGid: (required) Globally unique identifier for the project. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Sections.prototype.getSectionsForProject = function( - projectGid, - params, - dispatchOptions -) { - var path = "/projects/{project_gid}/sections".replace("{project_gid}", projectGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Move or Insert sections - * @param {String} projectGid: (required) Globally unique identifier for the project. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Sections.prototype.insertSectionForProject = function( - projectGid, - data, - dispatchOptions -) { - var path = "/projects/{project_gid}/sections/insert".replace("{project_gid}", projectGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Update a section - * @param {String} sectionGid: (required) The globally unique identifier for the section. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Sections.prototype.updateSection = function( - sectionGid, - data, - dispatchOptions -) { - var path = "/sections/{section_gid}".replace("{section_gid}", sectionGid); - - return this.dispatchPut(path, data, dispatchOptions) -}; - -module.exports = Sections; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],45:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function Stories(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(Stories, Resource); - - -/** - * Create a story on a task - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Stories.prototype.createStoryForTask = function( - taskGid, - data, - dispatchOptions -) { - var path = "/tasks/{task_gid}/stories".replace("{task_gid}", taskGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Delete a story - * @param {String} storyGid: (required) Globally unique identifier for the story. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Stories.prototype.deleteStory = function( - storyGid, - data, - dispatchOptions -) { - var path = "/stories/{story_gid}".replace("{story_gid}", storyGid); - - return this.dispatchDelete(path, data, dispatchOptions) -}; - - -/** - * Get stories from a task - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Stories.prototype.getStoriesForTask = function( - taskGid, - params, - dispatchOptions -) { - var path = "/tasks/{task_gid}/stories".replace("{task_gid}", taskGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get a story - * @param {String} storyGid: (required) Globally unique identifier for the story. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Stories.prototype.getStory = function( - storyGid, - params, - dispatchOptions -) { - var path = "/stories/{story_gid}".replace("{story_gid}", storyGid); - - return this.dispatchGet(path, params, dispatchOptions) -}; - - -/** - * Update a story - * @param {String} storyGid: (required) Globally unique identifier for the story. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Stories.prototype.updateStory = function( - storyGid, - data, - dispatchOptions -) { - var path = "/stories/{story_gid}".replace("{story_gid}", storyGid); - - return this.dispatchPut(path, data, dispatchOptions) -}; - -module.exports = Stories; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],46:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function Tags(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(Tags, Resource); - - -/** - * Create a tag - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tags.prototype.createTag = function( - data, - dispatchOptions -) { - var path = "/tags"; - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Create a tag in a workspace - * @param {String} workspaceGid: (required) Globally unique identifier for the workspace or organization. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tags.prototype.createTagForWorkspace = function( - workspaceGid, - data, - dispatchOptions -) { - var path = "/workspaces/{workspace_gid}/tags".replace("{workspace_gid}", workspaceGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Delete a tag - * @param {String} tagGid: (required) Globally unique identifier for the tag. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tags.prototype.deleteTag = function( - tagGid, - data, - dispatchOptions -) { - var path = "/tags/{tag_gid}".replace("{tag_gid}", tagGid); - - return this.dispatchDelete(path, data, dispatchOptions) -}; - - -/** - * Get a tag - * @param {String} tagGid: (required) Globally unique identifier for the tag. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tags.prototype.getTag = function( - tagGid, - params, - dispatchOptions -) { - var path = "/tags/{tag_gid}".replace("{tag_gid}", tagGid); - - return this.dispatchGet(path, params, dispatchOptions) -}; - - -/** - * Get multiple tags - * @param {Object} params: Parameters for the request - - workspace {String}: The workspace to filter tags on. - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tags.prototype.getTags = function( - params, - dispatchOptions -) { - var path = "/tags"; - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get a task's tags - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tags.prototype.getTagsForTask = function( - taskGid, - params, - dispatchOptions -) { - var path = "/tasks/{task_gid}/tags".replace("{task_gid}", taskGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get tags in a workspace - * @param {String} workspaceGid: (required) Globally unique identifier for the workspace or organization. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tags.prototype.getTagsForWorkspace = function( - workspaceGid, - params, - dispatchOptions -) { - var path = "/workspaces/{workspace_gid}/tags".replace("{workspace_gid}", workspaceGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Update a tag - * @param {String} tagGid: (required) Globally unique identifier for the tag. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tags.prototype.updateTag = function( - tagGid, - data, - dispatchOptions -) { - var path = "/tags/{tag_gid}".replace("{tag_gid}", tagGid); - - return this.dispatchPut(path, data, dispatchOptions) -}; - -module.exports = Tags; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],47:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function Tasks(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(Tasks, Resource); - - -/** - * Set dependencies for a task - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.addDependenciesForTask = function( - taskGid, - data, - dispatchOptions -) { - var path = "/tasks/{task_gid}/addDependencies".replace("{task_gid}", taskGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Set dependents for a task - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.addDependentsForTask = function( - taskGid, - data, - dispatchOptions -) { - var path = "/tasks/{task_gid}/addDependents".replace("{task_gid}", taskGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Add followers to a task - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.addFollowersForTask = function( - taskGid, - data, - dispatchOptions -) { - var path = "/tasks/{task_gid}/addFollowers".replace("{task_gid}", taskGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Add a project to a task - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.addProjectForTask = function( - taskGid, - data, - dispatchOptions -) { - var path = "/tasks/{task_gid}/addProject".replace("{task_gid}", taskGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Add a tag to a task - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.addTagForTask = function( - taskGid, - data, - dispatchOptions -) { - var path = "/tasks/{task_gid}/addTag".replace("{task_gid}", taskGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Create a subtask - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.createSubtaskForTask = function( - taskGid, - data, - dispatchOptions -) { - var path = "/tasks/{task_gid}/subtasks".replace("{task_gid}", taskGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Create a task - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.createTask = function( - data, - dispatchOptions -) { - var path = "/tasks"; - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Delete a task - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.deleteTask = function( - taskGid, - data, - dispatchOptions -) { - var path = "/tasks/{task_gid}".replace("{task_gid}", taskGid); - - return this.dispatchDelete(path, data, dispatchOptions) -}; - - -/** - * Duplicate a task - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.duplicateTask = function( - taskGid, - data, - dispatchOptions -) { - var path = "/tasks/{task_gid}/duplicate".replace("{task_gid}", taskGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Get dependencies from a task - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.getDependenciesForTask = function( - taskGid, - params, - dispatchOptions -) { - var path = "/tasks/{task_gid}/dependencies".replace("{task_gid}", taskGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get dependents from a task - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.getDependentsForTask = function( - taskGid, - params, - dispatchOptions -) { - var path = "/tasks/{task_gid}/dependents".replace("{task_gid}", taskGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get subtasks from a task - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.getSubtasksForTask = function( - taskGid, - params, - dispatchOptions -) { - var path = "/tasks/{task_gid}/subtasks".replace("{task_gid}", taskGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get a task - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} params: Parameters for the request - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.getTask = function( - taskGid, - params, - dispatchOptions -) { - var path = "/tasks/{task_gid}".replace("{task_gid}", taskGid); - - return this.dispatchGet(path, params, dispatchOptions) -}; - - -/** - * Get multiple tasks - * @param {Object} params: Parameters for the request - - assignee {String}: The assignee to filter tasks on. *Note: If you specify `assignee`, you must also specify the `workspace` to filter on.* - - project {String}: The project to filter tasks on. - - section {String}: The section to filter tasks on. *Note: Currently, this is only supported in board views.* - - workspace {String}: The workspace to filter tasks on. *Note: If you specify `workspace`, you must also specify the `assignee` to filter on.* - - completedSince {Date}: Only return tasks that are either incomplete or that have been completed since this time. - - modifiedSince {Date}: Only return tasks that have been modified since the given time. *Note: A task is considered “modified” if any of its properties change, or associations between it and other objects are modified (e.g. a task being added to a project). A task is not considered modified just because another object it is associated with (e.g. a subtask) is modified. Actions that count as modifying the task include assigning, renaming, completing, and adding stories.* - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.getTasks = function( - params, - dispatchOptions -) { - var path = "/tasks"; - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get tasks from a project - * @param {String} projectGid: (required) Globally unique identifier for the project. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.getTasksForProject = function( - projectGid, - params, - dispatchOptions -) { - var path = "/projects/{project_gid}/tasks".replace("{project_gid}", projectGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get tasks from a section - * @param {String} sectionGid: (required) The globally unique identifier for the section. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.getTasksForSection = function( - sectionGid, - params, - dispatchOptions -) { - var path = "/sections/{section_gid}/tasks".replace("{section_gid}", sectionGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get tasks from a tag - * @param {String} tagGid: (required) Globally unique identifier for the tag. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.getTasksForTag = function( - tagGid, - params, - dispatchOptions -) { - var path = "/tags/{tag_gid}/tasks".replace("{tag_gid}", tagGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get tasks from a user task list - * @param {String} userTaskListGid: (required) Globally unique identifier for the user task list. - * @param {Object} params: Parameters for the request - - completedSince {String}: Only return tasks that are either incomplete or that have been completed since this time. Accepts a date-time string or the keyword *now*. - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.getTasksForUserTaskList = function( - userTaskListGid, - params, - dispatchOptions -) { - var path = "/user_task_lists/{user_task_list_gid}/tasks".replace("{user_task_list_gid}", userTaskListGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Unlink dependencies from a task - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.removeDependenciesForTask = function( - taskGid, - data, - dispatchOptions -) { - var path = "/tasks/{task_gid}/removeDependencies".replace("{task_gid}", taskGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Unlink dependents from a task - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.removeDependentsForTask = function( - taskGid, - data, - dispatchOptions -) { - var path = "/tasks/{task_gid}/removeDependents".replace("{task_gid}", taskGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Remove followers from a task - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.removeFollowerForTask = function( - taskGid, - data, - dispatchOptions -) { - var path = "/tasks/{task_gid}/removeFollowers".replace("{task_gid}", taskGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Remove a project from a task - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.removeProjectForTask = function( - taskGid, - data, - dispatchOptions -) { - var path = "/tasks/{task_gid}/removeProject".replace("{task_gid}", taskGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Remove a tag from a task - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.removeTagForTask = function( - taskGid, - data, - dispatchOptions -) { - var path = "/tasks/{task_gid}/removeTag".replace("{task_gid}", taskGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Search tasks in a workspace - * @param {String} workspaceGid: (required) Globally unique identifier for the workspace or organization. - * @param {Object} params: Parameters for the request - - text {String}: Performs full-text search on both task name and description - - resourceSubtype {String}: Filters results by the task's resource_subtype - - assigneeAny {String}: Comma-separated list of user identifiers - - assigneeNot {String}: Comma-separated list of user identifiers - - assigneeStatus {String}: One of `inbox`, `today`, `upcoming`, or `later` - - portfoliosAny {String}: Comma-separated list of portfolio IDs - - projectsAny {String}: Comma-separated list of project IDs - - projectsNot {String}: Comma-separated list of project IDs - - projectsAll {String}: Comma-separated list of project IDs - - sectionsAny {String}: Comma-separated list of section or column IDs - - sectionsNot {String}: Comma-separated list of section or column IDs - - sectionsAll {String}: Comma-separated list of section or column IDs - - tagsAny {String}: Comma-separated list of tag IDs - - tagsNot {String}: Comma-separated list of tag IDs - - tagsAll {String}: Comma-separated list of tag IDs - - teamsAny {String}: Comma-separated list of team IDs - - followersAny {String}: Comma-separated list of user identifiers - - followersNot {String}: Comma-separated list of user identifiers - - createdByAny {String}: Comma-separated list of user identifiers - - createdByNot {String}: Comma-separated list of user identifiers - - assignedByAny {String}: Comma-separated list of user identifiers - - assignedByNot {String}: Comma-separated list of user identifiers - - likedByAny {String}: Comma-separated list of user identifiers - - likedByNot {String}: Comma-separated list of user identifiers - - commentedOnByAny {String}: Comma-separated list of user identifiers - - commentedOnByNot {String}: Comma-separated list of user identifiers - - dueOnBefore {Date}: ISO 8601 date string - - dueOnAfter {Date}: ISO 8601 date string - - dueOn {Date}: ISO 8601 date string or `null` - - dueAtBefore {Date}: ISO 8601 datetime string - - dueAtAfter {Date}: ISO 8601 datetime string - - startOnBefore {Date}: ISO 8601 date string - - startOnAfter {Date}: ISO 8601 date string - - startOn {Date}: ISO 8601 date string or `null` - - createdOnBefore {Date}: ISO 8601 date string - - createdOnAfter {Date}: ISO 8601 date string - - createdOn {Date}: ISO 8601 date string or `null` - - createdAtBefore {Date}: ISO 8601 datetime string - - createdAtAfter {Date}: ISO 8601 datetime string - - completedOnBefore {Date}: ISO 8601 date string - - completedOnAfter {Date}: ISO 8601 date string - - completedOn {Date}: ISO 8601 date string or `null` - - completedAtBefore {Date}: ISO 8601 datetime string - - completedAtAfter {Date}: ISO 8601 datetime string - - modifiedOnBefore {Date}: ISO 8601 date string - - modifiedOnAfter {Date}: ISO 8601 date string - - modifiedOn {Date}: ISO 8601 date string or `null` - - modifiedAtBefore {Date}: ISO 8601 datetime string - - modifiedAtAfter {Date}: ISO 8601 datetime string - - isBlocking {Boolean}: Filter to incomplete tasks with dependents - - isBlocked {Boolean}: Filter to tasks with incomplete dependencies - - hasAttachment {Boolean}: Filter to tasks with attachments - - completed {Boolean}: Filter to completed tasks - - isSubtask {Boolean}: Filter to subtasks - - sortBy {String}: One of `due_date`, `created_at`, `completed_at`, `likes`, or `modified_at`, defaults to `modified_at` - - sortAscending {Boolean}: Default `false` - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.searchTasksForWorkspace = function( - workspaceGid, - params, - dispatchOptions -) { - var path = "/workspaces/{workspace_gid}/tasks/search".replace("{workspace_gid}", workspaceGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Set the parent of a task - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.setParentForTask = function( - taskGid, - data, - dispatchOptions -) { - var path = "/tasks/{task_gid}/setParent".replace("{task_gid}", taskGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Update a task - * @param {String} taskGid: (required) The task to operate on. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.updateTask = function( - taskGid, - data, - dispatchOptions -) { - var path = "/tasks/{task_gid}".replace("{task_gid}", taskGid); - - return this.dispatchPut(path, data, dispatchOptions) -}; - -module.exports = Tasks; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],48:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function Teams(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(Teams, Resource); - - -/** - * Add a user to a team - * @param {String} teamGid: (required) Globally unique identifier for the team. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Teams.prototype.addUserForTeam = function( - teamGid, - data, - dispatchOptions -) { - var path = "/teams/{team_gid}/addUser".replace("{team_gid}", teamGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Get a team - * @param {String} teamGid: (required) Globally unique identifier for the team. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Teams.prototype.getTeam = function( - teamGid, - params, - dispatchOptions -) { - var path = "/teams/{team_gid}".replace("{team_gid}", teamGid); - - return this.dispatchGet(path, params, dispatchOptions) -}; - - -/** - * Get teams in an organization - * @param {String} workspaceGid: (required) Globally unique identifier for the workspace or organization. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Teams.prototype.getTeamsForOrganization = function( - workspaceGid, - params, - dispatchOptions -) { - var path = "/organizations/{workspace_gid}/teams".replace("{workspace_gid}", workspaceGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get teams for a user - * @param {String} userGid: (required) A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. - * @param {Object} params: Parameters for the request - - organization {String}: (required) The workspace or organization to filter teams on. - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Teams.prototype.getTeamsForUser = function( - userGid, - params, - dispatchOptions -) { - var path = "/users/{user_gid}/teams".replace("{user_gid}", userGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Remove a user from a team - * @param {String} teamGid: (required) Globally unique identifier for the team. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Teams.prototype.removeUserForTeam = function( - teamGid, - data, - dispatchOptions -) { - var path = "/teams/{team_gid}/removeUser".replace("{team_gid}", teamGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - -module.exports = Teams; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],49:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function Typeahead(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(Typeahead, Resource); - - -/** - * Get objects via typeahead - * @param {String} workspaceGid: (required) Globally unique identifier for the workspace or organization. - * @param {Object} params: Parameters for the request - - resourceType {String}: (required) The type of values the typeahead should return. You can choose from one of the following: `custom_field`, `project`, `portfolio`, `tag`, `task`, and `user`. Note that unlike in the names of endpoints, the types listed here are in singular form (e.g. `task`). Using multiple types is not yet supported. - - type {String}: *Deprecated: new integrations should prefer the resource_type field.* - - query {String}: The string that will be used to search for relevant objects. If an empty string is passed in, the API will currently return an empty result set. - - count {Number}: The number of results to return. The default is 20 if this parameter is omitted, with a minimum of 1 and a maximum of 100. If there are fewer results found than requested, all will be returned. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Typeahead.prototype.typeaheadForWorkspace = function( - workspaceGid, - params, - dispatchOptions -) { - var path = "/workspaces/{workspace_gid}/typeahead".replace("{workspace_gid}", workspaceGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - -module.exports = Typeahead; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],50:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function UserTaskLists(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(UserTaskLists, Resource); - - -/** - * Get a user task list - * @param {String} userTaskListGid: (required) Globally unique identifier for the user task list. - * @param {Object} params: Parameters for the request - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -UserTaskLists.prototype.getUserTaskList = function( - userTaskListGid, - params, - dispatchOptions -) { - var path = "/user_task_lists/{user_task_list_gid}".replace("{user_task_list_gid}", userTaskListGid); - - return this.dispatchGet(path, params, dispatchOptions) -}; - - -/** - * Get a user's task list - * @param {String} userGid: (required) A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. - * @param {Object} params: Parameters for the request - - workspace {String}: (required) The workspace in which to get the user task list. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -UserTaskLists.prototype.getUserTaskListForUser = function( - userGid, - params, - dispatchOptions -) { - var path = "/users/{user_gid}/user_task_list".replace("{user_gid}", userGid); - - return this.dispatchGet(path, params, dispatchOptions) -}; - -module.exports = UserTaskLists; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],51:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function Users(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(Users, Resource); - - -/** - * Get a user's favorites - * @param {String} userGid: (required) A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. - * @param {Object} params: Parameters for the request - - resourceType {String}: (required) The resource type of favorites to be returned. - - workspace {String}: (required) The workspace in which to get favorites. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Users.prototype.getFavoritesForUser = function( - userGid, - params, - dispatchOptions -) { - var path = "/users/{user_gid}/favorites".replace("{user_gid}", userGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get a user - * @param {String} userGid: (required) A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. - * @param {Object} params: Parameters for the request - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Users.prototype.getUser = function( - userGid, - params, - dispatchOptions -) { - var path = "/users/{user_gid}".replace("{user_gid}", userGid); - - return this.dispatchGet(path, params, dispatchOptions) -}; - - -/** - * Get multiple users - * @param {Object} params: Parameters for the request - - workspace {String}: The workspace or organization ID to filter users on. - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Users.prototype.getUsers = function( - params, - dispatchOptions -) { - var path = "/users"; - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get users in a team - * @param {String} teamGid: (required) Globally unique identifier for the team. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Users.prototype.getUsersForTeam = function( - teamGid, - params, - dispatchOptions -) { - var path = "/teams/{team_gid}/users".replace("{team_gid}", teamGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get users in a workspace or organization - * @param {String} workspaceGid: (required) Globally unique identifier for the workspace or organization. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Users.prototype.getUsersForWorkspace = function( - workspaceGid, - params, - dispatchOptions -) { - var path = "/workspaces/{workspace_gid}/users".replace("{workspace_gid}", workspaceGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - -module.exports = Users; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],52:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function Webhooks(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(Webhooks, Resource); - - -/** - * Establish a webhook - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Webhooks.prototype.createWebhook = function( - data, - dispatchOptions -) { - var path = "/webhooks"; - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Delete a webhook - * @param {String} webhookGid: (required) Globally unique identifier for the webhook. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Webhooks.prototype.deleteWebhook = function( - webhookGid, - data, - dispatchOptions -) { - var path = "/webhooks/{webhook_gid}".replace("{webhook_gid}", webhookGid); - - return this.dispatchDelete(path, data, dispatchOptions) -}; - - -/** - * Get a webhook - * @param {String} webhookGid: (required) Globally unique identifier for the webhook. - * @param {Object} params: Parameters for the request - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Webhooks.prototype.getWebhook = function( - webhookGid, - params, - dispatchOptions -) { - var path = "/webhooks/{webhook_gid}".replace("{webhook_gid}", webhookGid); - - return this.dispatchGet(path, params, dispatchOptions) -}; - - -/** - * Get multiple webhooks - * @param {Object} params: Parameters for the request - - workspace {String}: (required) The workspace to query for webhooks in. - - resource {String}: Only return webhooks for the given resource. - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Webhooks.prototype.getWebhooks = function( - params, - dispatchOptions -) { - var path = "/webhooks"; - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - -module.exports = Webhooks; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],53:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function WorkspaceMemberships(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(WorkspaceMemberships, Resource); - - -/** - * Get a workspace membership - * @param {String} workspaceMembershipGid: (required) - * @param {Object} params: Parameters for the request - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -WorkspaceMemberships.prototype.getWorkspaceMembership = function( - workspaceMembershipGid, - params, - dispatchOptions -) { - var path = "/workspace_memberships/{workspace_membership_gid}".replace("{workspace_membership_gid}", workspaceMembershipGid); - - return this.dispatchGet(path, params, dispatchOptions) -}; - - -/** - * Get workspace memberships for a user - * @param {String} userGid: (required) A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -WorkspaceMemberships.prototype.getWorkspaceMembershipsForUser = function( - userGid, - params, - dispatchOptions -) { - var path = "/users/{user_gid}/workspace_memberships".replace("{user_gid}", userGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Get the workspace memberships for a workspace - * @param {String} workspaceGid: (required) Globally unique identifier for the workspace or organization. - * @param {Object} params: Parameters for the request - - user {String}: A string identifying a user. This can either be the string \"me\", an email, or the gid of a user. - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -WorkspaceMemberships.prototype.getWorkspaceMembershipsForWorkspace = function( - workspaceGid, - params, - dispatchOptions -) { - var path = "/workspaces/{workspace_gid}/workspace_memberships".replace("{workspace_gid}", workspaceGid); - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - -module.exports = WorkspaceMemberships; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],54:[function(require,module,exports){ -/** - * This file is auto-generated by our openapi spec. - * We try to keep the generated code pretty clean but there will be lint - * errors that are just not worth fixing (like unused requires). - * TODO: maybe we can just disable those specifically and keep this code - * pretty lint-free too! - */ -/* jshint ignore:start */ -var Resource = require('../resource'); -var util = require('util'); -var _ = require('lodash'); - -function Workspaces(dispatcher) { - Resource.call(this, dispatcher); -} -util.inherits(Workspaces, Resource); - - -/** - * Add a user to a workspace or organization - * @param {String} workspaceGid: (required) Globally unique identifier for the workspace or organization. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Workspaces.prototype.addUserForWorkspace = function( - workspaceGid, - data, - dispatchOptions -) { - var path = "/workspaces/{workspace_gid}/addUser".replace("{workspace_gid}", workspaceGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Get a workspace - * @param {String} workspaceGid: (required) Globally unique identifier for the workspace or organization. - * @param {Object} params: Parameters for the request - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Workspaces.prototype.getWorkspace = function( - workspaceGid, - params, - dispatchOptions -) { - var path = "/workspaces/{workspace_gid}".replace("{workspace_gid}", workspaceGid); - - return this.dispatchGet(path, params, dispatchOptions) -}; - - -/** - * Get multiple workspaces - * @param {Object} params: Parameters for the request - - offset {String}: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. 'Note: You can only pass in an offset that was returned to you via a previously paginated request.' - - limit {Number}: Results per page. The number of objects to return per page. The value must be between 1 and 100. - - optFields {[String]}: Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. - - optPretty {Boolean}: Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Workspaces.prototype.getWorkspaces = function( - params, - dispatchOptions -) { - var path = "/workspaces"; - - return this.dispatchGetCollection(path, params, dispatchOptions) -}; - - -/** - * Remove a user from a workspace or organization - * @param {String} workspaceGid: (required) Globally unique identifier for the workspace or organization. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Workspaces.prototype.removeUserForWorkspace = function( - workspaceGid, - data, - dispatchOptions -) { - var path = "/workspaces/{workspace_gid}/removeUser".replace("{workspace_gid}", workspaceGid); - - return this.dispatchPost(path, data, dispatchOptions) -}; - - -/** - * Update a workspace - * @param {String} workspaceGid: (required) Globally unique identifier for the workspace or organization. - * @param {Object} data: Data for the request - * @param {Object} [dispatchOptions]: Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Workspaces.prototype.updateWorkspace = function( - workspaceGid, - data, - dispatchOptions -) { - var path = "/workspaces/{workspace_gid}".replace("{workspace_gid}", workspaceGid); - - return this.dispatchPut(path, data, dispatchOptions) -}; - -module.exports = Workspaces; -/* jshint ignore:end */ - -},{"../resource":63,"lodash":90,"util":119}],55:[function(require,module,exports){ -exports.Resource = require('./resource'); - -exports.Attachments = require('./attachments'); -exports.BatchAPI = require('./batch_api'); -exports.CustomFieldSettings = require('./custom_field_settings'); -exports.CustomFields = require('./custom_fields'); -exports.Events = require('./events'); -exports.Jobs = require('./jobs'); -exports.OrganizationExports = require('./organization_exports'); -exports.Projects = require('./projects'); -exports.PortfolioMemberships = require('./portfolio_memberships'); -exports.Portfolios = require('./portfolios'); -exports.ProjectMemberships = require('./project_memberships'); -exports.ProjectStatuses = require('./project_statuses'); -exports.Sections = require('./sections'); -exports.Stories = require('./stories'); -exports.Tags = require('./tags'); -exports.Tasks = require('./tasks'); -exports.Teams = require('./teams'); -exports.Typeahead = require('./typeahead'); -exports.Users = require('./users'); -exports.UserTaskLists = require('./user_task_lists'); -exports.Workspaces = require('./workspaces'); -exports.WorkspaceMemberships = require('./workspace_memberships'); -exports.Webhooks = require('./webhooks'); - -},{"./attachments":27,"./batch_api":28,"./custom_field_settings":29,"./custom_fields":30,"./events":31,"./jobs":56,"./organization_exports":57,"./portfolio_memberships":58,"./portfolios":59,"./project_memberships":60,"./project_statuses":61,"./projects":62,"./resource":63,"./sections":64,"./stories":65,"./tags":66,"./tasks":67,"./teams":68,"./typeahead":69,"./user_task_lists":70,"./users":71,"./webhooks":72,"./workspace_memberships":73,"./workspaces":74}],56:[function(require,module,exports){ -var Jobs = require('./gen/jobs'); -/* jshint ignore:start */ -var util = require('util'); - -/** - * Returns the complete job record for a single job. - * @param {String} job The job to get. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Jobs.prototype.findById = function( - job, - params, - dispatchOptions -) { - var path = util.format('/jobs/%s', job); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/* jshint ignore:end */ -module.exports = Jobs; - -},{"./gen/jobs":37,"util":119}],57:[function(require,module,exports){ -var OrganizationExports = require('./gen/organization_exports'); -/* jshint ignore:start */ -var util = require('util'); - -/** - * Returns details of a previously-requested Organization export. - * @param {String} organization_export Globally unique identifier for the Organization export. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -OrganizationExports.prototype.findById = function( - organizationExport, - params, - dispatchOptions -) { - var path = util.format('/organization_exports/%s', organizationExport); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * This method creates a request to export an Organization. Asana will complete the export at some - * point after you create the request. - * @param {Object} data Data for the request - * @param {String} data.organization Globally unique identifier for the workspace or organization. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -OrganizationExports.prototype.create = function( - data, - dispatchOptions -) { - var path = util.format('/organization_exports'); - - return this.dispatchPost(path, data, dispatchOptions); -}; - - -/* jshint ignore:end */ -module.exports = OrganizationExports; - -},{"./gen/organization_exports":38,"util":119}],58:[function(require,module,exports){ -var PortfolioMemberships = require('./gen/portfolio_memberships'); -/* jshint ignore:start */ -var util = require('util'); - -/** - * Returns the compact portfolio membership records for the portfolio. You must - * specify `portfolio`, `portfolio` and `user`, or `workspace` and `user`. - * @param {Object} [params] Parameters for the request - * @param {String} [params.portfolio] The portfolio for which to fetch memberships. - * @param {String} [params.workspace] The workspace for which to fetch memberships. - * @param {String} [params.user] The user to filter the memberships to. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -PortfolioMemberships.prototype.findAll = function( - params, - dispatchOptions -) { - var path = util.format('/portfolio_memberships'); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Returns the compact portfolio membership records for the portfolio. - * @param {String} portfolio The portfolio for which to fetch memberships. - * @param {Object} [params] Parameters for the request - * @param {String} [params.user] If present, the user to filter the memberships to. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -PortfolioMemberships.prototype.findByPortfolio = function( - portfolio, - params, - dispatchOptions -) { - var path = util.format('/portfolios/%s/portfolio_memberships', portfolio); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Returns the portfolio membership record. - * @param {String} portfolio_membership Globally unique identifier for the portfolio membership. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -PortfolioMemberships.prototype.findById = function( - portfolioMembership, - params, - dispatchOptions -) { - var path = util.format('/portfolio_memberships/%s', portfolioMembership); - - return this.dispatchGet(path, params, dispatchOptions); -}; - - -/* jshint ignore:end */ -module.exports = PortfolioMemberships; - -},{"./gen/portfolio_memberships":39,"util":119}],59:[function(require,module,exports){ -var Portfolios = require('./gen/portfolios'); -/* jshint ignore:start */ -var util = require('util'); - -/** - * Creates a new portfolio in the given workspace with the supplied name. - * - * Note that portfolios created in the Asana UI may have some state - * (like the "Priority" custom field) which is automatically added to the - * portfolio when it is created. Portfolios created via our API will **not** - * be created with the same initial state to allow integrations to create - * their own starting state on a portfolio. - * @param {Object} data Data for the request - * @param {String} data.workspace The workspace or organization in which to create the portfolio. - * @param {String} data.name The name of the newly-created portfolio - * @param {String} [data.color] An optional color for the portfolio - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Portfolios.prototype.create = function( - data, - dispatchOptions -) { - var path = util.format('/portfolios'); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Returns the complete record for a single portfolio. - * @param {String} portfolio The portfolio to get. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Portfolios.prototype.findById = function( - portfolio, - params, - dispatchOptions -) { - var path = util.format('/portfolios/%s', portfolio); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * An existing portfolio can be updated by making a PUT request on the - * URL for that portfolio. Only the fields provided in the `data` block will be - * updated; any unspecified fields will remain unchanged. - * - * Returns the complete updated portfolio record. - * @param {String} portfolio The portfolio to update. - * @param {Object} data Data for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Portfolios.prototype.update = function( - portfolio, - data, - dispatchOptions -) { - var path = util.format('/portfolios/%s', portfolio); - - return this.dispatchPut(path, data, dispatchOptions); -}; - -/** - * An existing portfolio can be deleted by making a DELETE request - * on the URL for that portfolio. - * - * Returns an empty data record. - * @param {String} portfolio The portfolio to delete. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Portfolios.prototype.delete = function( - portfolio, - dispatchOptions -) { - var path = util.format('/portfolios/%s', portfolio); - - return this.dispatchDelete(path, dispatchOptions); -}; - -/** - * Returns a list of the portfolios in compact representation that are owned - * by the current API user. - * @param {Object} [params] Parameters for the request - * @param {String} params.workspace The workspace or organization to filter portfolios on. - * @param {String} params.owner The user who owns the portfolio. Currently, API users can only get a - * list of portfolios that they themselves own. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Portfolios.prototype.findAll = function( - params, - dispatchOptions -) { - var path = util.format('/portfolios'); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Get a list of the items in compact form in a portfolio. - * @param {String} portfolio The portfolio from which to get the list of items. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Portfolios.prototype.getItems = function( - portfolio, - params, - dispatchOptions -) { - var path = util.format('/portfolios/%s/items', portfolio); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * Add an item to a portfolio. - * - * Returns an empty data block. - * @param {String} portfolio The portfolio to which to add an item. - * @param {Object} data Data for the request - * @param {String} data.item The item to add to the portfolio. - * @param {String} [data.insert_before] An id of an item in this portfolio. The new item will be added before the one specified here. - * `insert_before` and `insert_after` parameters cannot both be specified. - * @param {String} [data.insert_after] An id of an item in this portfolio. The new item will be added after the one specified here. - * `insert_before` and `insert_after` parameters cannot both be specified. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Portfolios.prototype.addItem = function( - portfolio, - data, - dispatchOptions -) { - var path = util.format('/portfolios/%s/addItem', portfolio); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Remove an item to a portfolio. - * - * Returns an empty data block. - * @param {String} portfolio The portfolio from which to remove the item. - * @param {Object} data Data for the request - * @param {String} data.item The item to remove from the portfolio. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Portfolios.prototype.removeItem = function( - portfolio, - data, - dispatchOptions -) { - var path = util.format('/portfolios/%s/removeItem', portfolio); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Adds the specified list of users as members of the portfolio. Returns the updated portfolio record. - * @param {String} portfolio The portfolio to add members to. - * @param {Object} data Data for the request - * @param {Array} data.members An array of user ids. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Portfolios.prototype.addMembers = function( - portfolio, - data, - dispatchOptions -) { - var path = util.format('/portfolios/%s/addMembers', portfolio); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Removes the specified list of members from the portfolio. Returns the updated portfolio record. - * @param {String} portfolio The portfolio to remove members from. - * @param {Object} data Data for the request - * @param {Array} data.members An array of user ids. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Portfolios.prototype.removeMembers = function( - portfolio, - data, - dispatchOptions -) { - var path = util.format('/portfolios/%s/removeMembers', portfolio); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Get the custom field settings on a portfolio. - * @param {String} portfolio The portfolio from which to get the custom field settings. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Portfolios.prototype.customFieldSettings = function( - portfolio, - params, - dispatchOptions -) { - var path = util.format('/portfolios/%s/custom_field_settings', portfolio); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * Create a new custom field setting on the portfolio. Returns the full - * record for the new custom field setting. - * @param {String} portfolio The portfolio onto which to add the custom field. - * @param {Object} data Data for the request - * @param {String} data.custom_field The id of the custom field to add to the portfolio. - * @param {Boolean} [data.is_important] Whether this field should be considered important to this portfolio (for instance, to display in the list view of items in the portfolio). - * @param {String} [data.insert_before] An id of a custom field setting on this portfolio. The new custom field setting will be added before this one. - * `insert_before` and `insert_after` parameters cannot both be specified. - * @param {String} [data.insert_after] An id of a custom field setting on this portfolio. The new custom field setting will be added after this one. - * `insert_before` and `insert_after` parameters cannot both be specified. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Portfolios.prototype.addCustomFieldSetting = function( - portfolio, - data, - dispatchOptions -) { - var path = util.format('/portfolios/%s/addCustomFieldSetting', portfolio); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Remove a custom field setting on the portfolio. Returns an empty data - * block. - * @param {String} portfolio The portfolio from which to remove the custom field. - * @param {Object} data Data for the request - * @param {String} data.custom_field The id of the custom field to remove from this portfolio. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Portfolios.prototype.removeCustomFieldSetting = function( - portfolio, - data, - dispatchOptions -) { - var path = util.format('/portfolios/%s/removeCustomFieldSetting', portfolio); - - return this.dispatchPost(path, data, dispatchOptions); -}; - - -/* jshint ignore:end */ -module.exports = Portfolios; - -},{"./gen/portfolios":40,"util":119}],60:[function(require,module,exports){ -var ProjectMemberships = require('./gen/project_memberships'); -/* jshint ignore:start */ -var util = require('util'); - -/** - * Returns the compact project membership records for the project. - * @param {String} project The project for which to fetch memberships. - * @param {Object} [params] Parameters for the request - * @param {String} [params.user] If present, the user to filter the memberships to. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -ProjectMemberships.prototype.findByProject = function( - project, - params, - dispatchOptions -) { - var path = util.format('/projects/%s/project_memberships', project); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Returns the project membership record. - * @param {String} projectMembership Globally unique identifier for the project membership. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -ProjectMemberships.prototype.findById = function( - projectMembership, - params, - dispatchOptions -) { - var path = util.format('/project_memberships/%s', projectMembership); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * This is for compatibility reasons. Please use findByProject. - */ -ProjectMemberships.prototype.getMany = - ProjectMemberships.prototype.findByProject; -/** - * This is for compatibility reasons. Please use findById. - */ -ProjectMemberships.prototype.getSingle = ProjectMemberships.prototype.findById; - -/* jshint ignore:end */ -module.exports = ProjectMemberships; - -},{"./gen/project_memberships":41,"util":119}],61:[function(require,module,exports){ -var ProjectStatuses = require('./gen/project_statuses'); -/* jshint ignore:start */ -var util = require('util'); - -/** - * Creates a new status update on the project. - * - * Returns the full record of the newly created project status update. - * @param {String} project The project on which to create a status update. - * @param {Object} data Data for the request - * @param {String} data.text The text of the project status update. - * @param {String} data.color The color to associate with the status update. Must be one of `"red"`, `"yellow"`, or `"green"`. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -ProjectStatuses.prototype.createInProject = function( - project, - data, - dispatchOptions -) { - var path = util.format('/projects/%s/project_statuses', project); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Returns the compact project status update records for all updates on the project. - * @param {String} project The project to find status updates for. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -ProjectStatuses.prototype.findByProject = function( - project, - params, - dispatchOptions -) { - var path = util.format('/projects/%s/project_statuses', project); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Returns the complete record for a single status update. - * @param {String} project-status The project status update to get. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -ProjectStatuses.prototype.findById = function( - projectStatus, - params, - dispatchOptions -) { - var path = util.format('/project_statuses/%s', projectStatus); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * Deletes a specific, existing project status update. - * - * Returns an empty data record. - * @param {String} project-status The project status update to delete. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -ProjectStatuses.prototype.delete = function( - projectStatus, - dispatchOptions -) { - var path = util.format('/project_statuses/%s', projectStatus); - - return this.dispatchDelete(path, dispatchOptions); -}; - -/** - * This is for compatibility reasons. Please use createInProject. - */ -ProjectStatuses.prototype.create = ProjectStatuses.prototype.createInProject; - -/* jshint ignore:end */ -module.exports = ProjectStatuses; - -},{"./gen/project_statuses":42,"util":119}],62:[function(require,module,exports){ -var Projects = require('./gen/projects'); -/* jshint ignore:start */ -var util = require('util'); - -/** - * Creates a new project in a workspace or team. - * - * Every project is required to be created in a specific workspace or - * organization, and this cannot be changed once set. Note that you can use - * the `workspace` parameter regardless of whether or not it is an - * organization. - * - * If the workspace for your project _is_ an organization, you must also - * supply a `team` to share the project with. - * - * Returns the full record of the newly created project. - * @param {Object} data Data for the request - * @param {String} data.workspace The workspace or organization to create the project in. - * @param {String} [data.team] If creating in an organization, the specific team to create the - * project in. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Projects.prototype.create = function( - data, - dispatchOptions -) { - var path = util.format('/projects'); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * If the workspace for your project _is_ an organization, you must also - * supply a `team` to share the project with. - * - * Returns the full record of the newly created project. - * @param {String} workspace The workspace or organization to create the project in. - * @param {Object} data Data for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Projects.prototype.createInWorkspace = function( - workspace, - data, - dispatchOptions -) { - var path = util.format('/workspaces/%s/projects', workspace); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Creates a project shared with the given team. - * - * Returns the full record of the newly created project. - * @param {String} team The team to create the project in. - * @param {Object} data Data for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Projects.prototype.createInTeam = function( - team, - data, - dispatchOptions -) { - var path = util.format('/teams/%s/projects', team); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Returns the complete project record for a single project. - * @param {String} project The project to get. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Projects.prototype.findById = function( - project, - params, - dispatchOptions -) { - var path = util.format('/projects/%s', project); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * A specific, existing project can be updated by making a PUT request on the - * URL for that project. Only the fields provided in the `data` block will be - * updated; any unspecified fields will remain unchanged. - * - * When using this method, it is best to specify only those fields you wish - * to change, or else you may overwrite changes made by another user since - * you last retrieved the task. - * - * Returns the complete updated project record. - * @param {String} project The project to update. - * @param {Object} data Data for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Projects.prototype.update = function( - project, - data, - dispatchOptions -) { - var path = util.format('/projects/%s', project); - - return this.dispatchPut(path, data, dispatchOptions); -}; - -/** - * A specific, existing project can be deleted by making a DELETE request - * on the URL for that project. - * - * Returns an empty data record. - * @param {String} project The project to delete. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Projects.prototype.delete = function( - project, - dispatchOptions -) { - var path = util.format('/projects/%s', project); - - return this.dispatchDelete(path, dispatchOptions); -}; - -/** - * Creates and returns a job that will asynchronously handle the duplication. - * @param {String} project The project to duplicate. - * @param {Object} data Data for the request - * @param {String} data.name The name of the new project. - * @param {String} [data.team] Sets the team of the new project. If team is not defined, the new project - * will be in the same team as the the original project. - * @param {Array} [data.include] The elements that will be duplicated to the new project. - * Tasks are always included. - * @param {String} [data.schedule_dates] A dictionary of options to auto-shift dates. - * `task_dates` must be included to use this option. - * Requires either `start_on` or `due_on`, but not both. - * `start_on` will set the first start date of the new - * project to the given date, while `due_on` will set the last due date - * to the given date. Both will offset the remaining dates by the same amount - * of the original project. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Projects.prototype.duplicateProject = function( - project, - data, - dispatchOptions -) { - var path = util.format('/projects/%s/duplicate', project); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Returns the compact project records for some filtered set of projects. - * Use one or more of the parameters provided to filter the projects returned. - * @param {Object} [params] Parameters for the request - * @param {String} [params.workspace] The workspace or organization to filter projects on. - * @param {String} [params.team] The team to filter projects on. - * @param {Boolean} [params.is_template] **Note: This parameter can only be included if a team is also defined, or the workspace is not an organization** - * Filters results to include only template projects. - * @param {Boolean} [params.archived] Only return projects whose `archived` field takes on the value of - * this parameter. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Projects.prototype.findAll = function( - params, - dispatchOptions -) { - var path = util.format('/projects'); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Returns the compact project records for all projects in the workspace. - * @param {String} workspace The workspace or organization to find projects in. - * @param {Object} [params] Parameters for the request - * @param {Boolean} [params.is_template] **Note: This parameter can only be included if a team is also defined, or the workspace is not an organization** - * Filters results to include only template projects. - * @param {Boolean} [params.archived] Only return projects whose `archived` field takes on the value of - * this parameter. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Projects.prototype.findByWorkspace = function( - workspace, - params, - dispatchOptions -) { - var path = util.format('/workspaces/%s/projects', workspace); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Returns the compact project records for all projects in the team. - * @param {String} team The team to find projects in. - * @param {Object} [params] Parameters for the request - * @param {Boolean} [params.is_template] Filters results to include only template projects. - * @param {Boolean} [params.archived] Only return projects whose `archived` field takes on the value of - * this parameter. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Projects.prototype.findByTeam = function( - team, - params, - dispatchOptions -) { - var path = util.format('/teams/%s/projects', team); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Returns the compact task records for all tasks within the given project, - * ordered by their priority within the project. Tasks can exist in more than one project at a time. - * @param {String} project The project in which to search for tasks. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Projects.prototype.tasks = function( - project, - params, - dispatchOptions -) { - var path = util.format('/projects/%s/tasks', project); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Adds the specified list of users as followers to the project. Followers are a subset of members, therefore if - * the users are not already members of the project they will also become members as a result of this operation. - * Returns the updated project record. - * @param {String} project The project to add followers to. - * @param {Object} data Data for the request - * @param {Array} data.followers An array of followers to add to the project. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Projects.prototype.addFollowers = function( - project, - data, - dispatchOptions -) { - var path = util.format('/projects/%s/addFollowers', project); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Removes the specified list of users from following the project, this will not affect project membership status. - * Returns the updated project record. - * @param {String} project The project to remove followers from. - * @param {Object} data Data for the request - * @param {Array} data.followers An array of followers to remove from the project. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Projects.prototype.removeFollowers = function( - project, - data, - dispatchOptions -) { - var path = util.format('/projects/%s/removeFollowers', project); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Adds the specified list of users as members of the project. Returns the updated project record. - * @param {String} project The project to add members to. - * @param {Object} data Data for the request - * @param {Array} data.members An array of user ids. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Projects.prototype.addMembers = function( - project, - data, - dispatchOptions -) { - var path = util.format('/projects/%s/addMembers', project); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Removes the specified list of members from the project. Returns the updated project record. - * @param {String} project The project to remove members from. - * @param {Object} data Data for the request - * @param {Array} data.members An array of user ids. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Projects.prototype.removeMembers = function( - project, - data, - dispatchOptions -) { - var path = util.format('/projects/%s/removeMembers', project); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Create a new custom field setting on the project. - * @param {String} project The project to associate the custom field with - * @param {Object} data Data for the request - * @param {String} data.custom_field The id of the custom field to associate with this project. - * @param {Boolean} [data.is_important] Whether this field should be considered important to this project. - * @param {String} [data.insert_before] An id of a Custom Field Settings on this project, before which the new Custom Field Settings will be added. - * `insert_before` and `insert_after` parameters cannot both be specified. - * @param {String} [data.insert_after] An id of a Custom Field Settings on this project, after which the new Custom Field Settings will be added. - * `insert_before` and `insert_after` parameters cannot both be specified. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Projects.prototype.addCustomFieldSetting = function( - project, - data, - dispatchOptions -) { - var path = util.format('/projects/%s/addCustomFieldSetting', project); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Remove a custom field setting on the project. - * @param {String} project The project to associate the custom field with - * @param {Object} data Data for the request - * @param {String} [data.custom_field] The id of the custom field to remove from this project. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Projects.prototype.removeCustomFieldSetting = function( - project, - data, - dispatchOptions -) { - var path = util.format('/projects/%s/removeCustomFieldSetting', project); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/* jshint ignore:end */ -module.exports = Projects; - -},{"./gen/projects":43,"util":119}],63:[function(require,module,exports){ -var Collection = require('../util/collection'); - -/** - * Base class for a resource accessible via the API. Uses a `Dispatcher` to - * access the resources. - * @param {Dispatcher} dispatcher - * @constructor - */ -function Resource(dispatcher) { - /** - * An instance of the dispatcher. This is usually passed from the client. - * @type {Dispatcher} - */ - this.dispatcher = dispatcher; -} - -/** - * @type {number} Default number of items to get per page. - */ -Resource.DEFAULT_PAGE_LIMIT = 50; - -/** - * Helper method that dispatches a GET request to the API, where the expected - * result is a collection. - * @param {Dispatcher} dispatcher - * @param {String} path The path of the API - * @param {Object} [query] The query params - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `Dispatcher.dispatch`. - * @return {Promise} The Collection response for the request - */ -Resource.getCollection = function(dispatcher, path, query, dispatchOptions) { - query = query || {}; - query.limit = query.limit || Resource.DEFAULT_PAGE_LIMIT; - return Collection.fromDispatch( - dispatcher.get(path, query, dispatchOptions), - dispatcher, - dispatchOptions); -}; - -/** - * Helper method for any request Promise from the Dispatcher, unwraps the `data` - * value from the payload. - * @param {Promise} promise A promise returned from a `Dispatcher` request. - * @return {Promise} The `data` portion of the response payload. - */ -Resource.unwrap = function(promise) { - return promise.then(function(payload) { - return payload.data; - }); -}; - -/** - * Dispatches a GET request to the API, where the expected result is a - * single resource. - * @param {String} path The path of the API - * @param {Object} [query] The query params - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `Dispatcher.dispatch`. - * @return {Promise} The response for the request - */ -Resource.prototype.dispatchGet = function(path, query, dispatchOptions) { - return Resource.unwrap(this.dispatcher.get(path, query, dispatchOptions)); -}; - -/** - * Dispatches a GET request to the API, where the expected result is a - * collection. - * @param {String} path The path of the API - * @param {Object} [query] The query params - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `Dispatcher.dispatch`. - * @return {Promise} The response for the request - */ -Resource.prototype.dispatchGetCollection = - function(path, query, dispatchOptions) { - return Resource.getCollection(this.dispatcher, path, query, dispatchOptions); -}; - -/** - * Dispatches a POST request to the API, where the expected response is a - * single resource. - * @param {String} path The path of the API - * @param {Object} [query] The query params - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `Dispatcher.dispatch`. - * @return {Promise} The response for the request - */ -Resource.prototype.dispatchPost = function(path, query, dispatchOptions) { - return Resource.unwrap(this.dispatcher.post(path, query, dispatchOptions)); -}; - -/** - * Dispatches a POST request to the API, where the expected response is a - * single resource. - * @param {String} path The path of the API - * @param {Object} [query] The query params - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `Dispatcher.dispatch`. - * @return {Promise} The response for the request - */ -Resource.prototype.dispatchPut = function(path, query, dispatchOptions) { - return Resource.unwrap(this.dispatcher.put(path, query, dispatchOptions)); -}; - -/** - * Dispatches a DELETE request to the API. The expected response is an - * empty resource. - * @param {String} path The path of the API - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `Dispatcher.dispatch`. - * @return {Promise} The response for the request - */ -Resource.prototype.dispatchDelete = function(path, dispatchOptions) { - return Resource.unwrap(this.dispatcher.delete(path, dispatchOptions)); -}; - -module.exports = Resource; - -},{"../util/collection":76}],64:[function(require,module,exports){ -var Sections = require('./gen/sections'); -/* jshint ignore:start */ -var util = require('util'); - -/** - * Creates a new section in a project. - * - * Returns the full record of the newly created section. - * @param {String} project The project to create the section in - * @param {Object} data Data for the request - * @param {String} data.name The text to be displayed as the section name. This cannot be an empty string. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Sections.prototype.createInProject = function( - project, - data, - dispatchOptions -) { - var path = util.format('/projects/%s/sections', project); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Returns the compact records for all sections in the specified project. - * @param {String} project The project to get sections from. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Sections.prototype.findByProject = function( - project, - params, - dispatchOptions -) { - var path = util.format('/projects/%s/sections', project); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * Returns the complete record for a single section. - * @param {String} section The section to get. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Sections.prototype.findById = function( - section, - params, - dispatchOptions -) { - var path = util.format('/sections/%s', section); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * A specific, existing section can be updated by making a PUT request on - * the URL for that project. Only the fields provided in the `data` block - * will be updated; any unspecified fields will remain unchanged. (note that - * at this time, the only field that can be updated is the `name` field.) - * - * When using this method, it is best to specify only those fields you wish - * to change, or else you may overwrite changes made by another user since - * you last retrieved the task. - * - * Returns the complete updated section record. - * @param {String} section The section to update. - * @param {Object} data Data for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Sections.prototype.update = function( - section, - data, - dispatchOptions -) { - var path = util.format('/sections/%s', section); - - return this.dispatchPut(path, data, dispatchOptions); -}; - -/** - * A specific, existing section can be deleted by making a DELETE request - * on the URL for that section. - * - * Note that sections must be empty to be deleted. - * - * The last remaining section in a board view cannot be deleted. - * - * Returns an empty data block. - * @param {String} section The section to delete. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Sections.prototype.delete = function( - section, - dispatchOptions -) { - var path = util.format('/sections/%s', section); - - return this.dispatchDelete(path, dispatchOptions); -}; - -/** - * Add a task to a specific, existing section. This will remove the task from other sections of the project. - * - * The task will be inserted at the top of a section unless an `insert_before` or `insert_after` parameter is declared. - * - * This does not work for separators (tasks with the `resource_subtype` of section). - * @param {String} task The task to add to this section - * @param {Object} data Data for the request - * @param {String} [data.insert_before] Insert the given task immediately before the task specified by this parameter. Cannot be provided together with `insert_after`. - * @param {String} [data.insert_after] Insert the given task immediately after the task specified by this parameter. Cannot be provided together with `insert_before`. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Sections.prototype.addTask = function( - task, - data, - dispatchOptions -) { - var path = util.format('/sections/%s/addTask', task); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Move sections relative to each other in a board view. One of - * `before_section` or `after_section` is required. - * - * Sections cannot be moved between projects. - * - * At this point in time, moving sections is not supported in list views, only board views. - * - * Returns an empty data block. - * @param {String} project The project in which to reorder the given section - * @param {Object} data Data for the request - * @param {String} data.section The section to reorder - * @param {String} [data.before_section] Insert the given section immediately before the section specified by this parameter. - * @param {String} [data.after_section] Insert the given section immediately after the section specified by this parameter. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Sections.prototype.insertInProject = function( - project, - data, - dispatchOptions -) { - var path = util.format('/projects/%s/sections/insert', project); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/* jshint ignore:end */ -module.exports = Sections; - -},{"./gen/sections":44,"util":119}],65:[function(require,module,exports){ -var Stories = require('./gen/stories'); -/* jshint ignore:start */ -var util = require('util'); - -/** - * Returns the compact records for all stories on the task. - * @param {String} task Globally unique identifier for the task. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Stories.prototype.findByTask = function( - task, - params, - dispatchOptions -) { - var path = util.format('/tasks/%s/stories', task); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Returns the full record for a single story. - * @param {String} story Globally unique identifier for the story. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Stories.prototype.findById = function( - story, - params, - dispatchOptions -) { - var path = util.format('/stories/%s', story); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * Adds a comment to a task. The comment will be authored by the - * currently authenticated user, and timestamped when the server receives - * the request. - * - * Returns the full record for the new story added to the task. - * @param {String} task Globally unique identifier for the task. - * @param {Object} data Data for the request - * @param {String} data.text The plain text of the comment to add. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Stories.prototype.createOnTask = function( - task, - data, - dispatchOptions -) { - var path = util.format('/tasks/%s/stories', task); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Updates the story and returns the full record for the updated story. - * Only comment stories can have their text updated, and only comment stories and - * attachment stories can be pinned. Only one of `text` and `html_text` can be specified. - * @param {String} story Globally unique identifier for the story. - * @param {Object} data Data for the request - * @param {String} [data.text] The plain text with which to update the comment. - * @param {String} [data.html_text] The rich text with which to update the comment. - * @param {Boolean} [data.is_pinned] Whether the story should be pinned on the resource. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Stories.prototype.update = function( - story, - data, - dispatchOptions -) { - var path = util.format('/stories/%s', story); - - return this.dispatchPut(path, data, dispatchOptions); -}; - -/** - * Deletes a story. A user can only delete stories they have created. Returns an empty data record. - * @param {String} story Globally unique identifier for the story. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Stories.prototype.delete = function( - story, - dispatchOptions -) { - var path = util.format('/stories/%s', story); - - return this.dispatchDelete(path, dispatchOptions); -}; - -/* jshint ignore:end */ -module.exports = Stories; - -},{"./gen/stories":45,"util":119}],66:[function(require,module,exports){ -var Tags = require('./gen/tags'); -/* jshint ignore:start */ -var util = require('util'); - -/** - * Creates a new tag in a workspace or organization. - * - * Every tag is required to be created in a specific workspace or - * organization, and this cannot be changed once set. Note that you can use - * the `workspace` parameter regardless of whether or not it is an - * organization. - * - * Returns the full record of the newly created tag. - * @param {Object} data Data for the request - * @param {String} data.workspace The workspace or organization to create the tag in. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tags.prototype.create = function( - data, - dispatchOptions -) { - var path = util.format('/tags'); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Creates a new tag in a workspace or organization. - * - * Every tag is required to be created in a specific workspace or - * organization, and this cannot be changed once set. Note that you can use - * the `workspace` parameter regardless of whether or not it is an - * organization. - * - * Returns the full record of the newly created tag. - * @param {String} workspace The workspace or organization to create the tag in. - * @param {Object} data Data for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tags.prototype.createInWorkspace = function( - workspace, - data, - dispatchOptions -) { - var path = util.format('/workspaces/%s/tags', workspace); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Returns the complete tag record for a single tag. - * @param {String} tag The tag to get. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tags.prototype.findById = function( - tag, - params, - dispatchOptions -) { - var path = util.format('/tags/%s', tag); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * Updates the properties of a tag. Only the fields provided in the `data` - * block will be updated; any unspecified fields will remain unchanged. - * - * When using this method, it is best to specify only those fields you wish - * to change, or else you may overwrite changes made by another user since - * you last retrieved the task. - * - * Returns the complete updated tag record. - * @param {String} tag The tag to update. - * @param {Object} data Data for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tags.prototype.update = function( - tag, - data, - dispatchOptions -) { - var path = util.format('/tags/%s', tag); - - return this.dispatchPut(path, data, dispatchOptions); -}; - -/** - * A specific, existing tag can be deleted by making a DELETE request - * on the URL for that tag. - * - * Returns an empty data record. - * @param {String} tag The tag to delete. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tags.prototype.delete = function( - tag, - dispatchOptions -) { - var path = util.format('/tags/%s', tag); - - return this.dispatchDelete(path, dispatchOptions); -}; - -/** - * Returns the compact tag records for some filtered set of tags. - * Use one or more of the parameters provided to filter the tags returned. - * @param {Object} [params] Parameters for the request - * @param {String} [params.workspace] The workspace or organization to filter tags on. - * @param {String} [params.team] The team to filter tags on. - * @param {Boolean} [params.archived] Only return tags whose `archived` field takes on the value of - * this parameter. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tags.prototype.findAll = function( - params, - dispatchOptions -) { - var path = util.format('/tags'); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Returns the compact tag records for all tags in the workspace. - * @param {String} workspace The workspace or organization to find tags in. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tags.prototype.findByWorkspace = function( - workspace, - params, - dispatchOptions -) { - var path = util.format('/workspaces/%s/tags', workspace); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Returns the compact task records for all tasks with the given tag. - * Tasks can have more than one tag at a time. - * @param {String} tag The tag to fetch tasks from. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tags.prototype.getTasksWithTag = function( - tag, - params, - dispatchOptions -) { - var path = util.format('/tags/%s/tasks', tag); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/* jshint ignore:end */ -module.exports = Tags; - -},{"./gen/tags":46,"util":119}],67:[function(require,module,exports){ -var Tasks = require('./gen/tasks'); -/* jshint ignore:start */ -var util = require('util'); -var _ = require('lodash'); - -/** - * Returns the task named by the given external ID - * @param {String} externalId The task id - * @param {Object} [params] Extra params for the dispatcher - * @return {Promise} The result of the API call - */ -Tasks.prototype.findByExternalId = function(externalId, params) { - var path = util.format( - '/tasks/%s', encodeURIComponent('external:' + externalId)); - return this.dispatchGet(path, params); -}; - -/** - * Changes the parent of a task. Each task may only be a subtask of a single - * parent, or no parent task at all. Returns an empty data block. - * @param {String} task The task to change the parent of. - * @param {String} parent The new parent of the task, or `null` for no parent. - * @param {Object} [data] Data for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.setParent = function( - task, - parent, - data - ) { - var path = util.format('/tasks/%s/setParent', task); - - data = _.extend({}, data || {}, { - parent: parent !== null ? String(parent) : null - }); - return this.dispatchPost(path, data); -}; - -/** - * Creating a new task is as easy as POSTing to the `/tasks` endpoint - * with a data block containing the fields you'd like to set on the task. - * Any unspecified fields will take on default values. - * - * Every task is required to be created in a specific workspace, and this - * workspace cannot be changed once set. The workspace need not be set - * explicitly if you specify `projects` or a `parent` task instead. - * - * `projects` can be a comma separated list of projects, or just a single - * project the task should belong to. - * @param {Object} data Data for the request - * @param {String} [data.workspace] The workspace to create a task in. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.create = function( - data, - dispatchOptions -) { - var path = util.format('/tasks'); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Creating a new task is as easy as POSTing to the `/tasks` endpoint - * with a data block containing the fields you'd like to set on the task. - * Any unspecified fields will take on default values. - * - * Every task is required to be created in a specific workspace, and this - * workspace cannot be changed once set. The workspace need not be set - * explicitly if you specify a `project` or a `parent` task instead. - * @param {String} workspace The workspace to create a task in. - * @param {Object} data Data for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.createInWorkspace = function( - workspace, - data, - dispatchOptions -) { - var path = util.format('/workspaces/%s/tasks', workspace); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Returns the complete task record for a single task. - * @param {String} task The task to get. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.findById = function( - task, - params, - dispatchOptions -) { - var path = util.format('/tasks/%s', task); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * A specific, existing task can be updated by making a PUT request on the - * URL for that task. Only the fields provided in the `data` block will be - * updated; any unspecified fields will remain unchanged. - * - * When using this method, it is best to specify only those fields you wish - * to change, or else you may overwrite changes made by another user since - * you last retrieved the task. - * - * Returns the complete updated task record. - * @param {String} task The task to update. - * @param {Object} data Data for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.update = function( - task, - data, - dispatchOptions -) { - var path = util.format('/tasks/%s', task); - - return this.dispatchPut(path, data, dispatchOptions); -}; - -/** - * A specific, existing task can be deleted by making a DELETE request on the - * URL for that task. Deleted tasks go into the "trash" of the user making - * the delete request. Tasks can be recovered from the trash within a period - * of 30 days; afterward they are completely removed from the system. - * - * Returns an empty data record. - * @param {String} task The task to delete. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.delete = function( - task, - dispatchOptions -) { - var path = util.format('/tasks/%s', task); - - return this.dispatchDelete(path, dispatchOptions); -}; - -/** - * Creates and returns a job that will asynchronously handle the duplication. - * @param {String} task The task to duplicate. - * @param {Object} data Data for the request - * @param {String} data.name The name of the new task. - * @param {Array} [data.include] The fields that will be duplicated to the new task. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.duplicateTask = function( - task, - data, - dispatchOptions -) { - var path = util.format('/tasks/%s/duplicate', task); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Returns the compact task records for all tasks within the given project, - * ordered by their priority within the project. - * @param {String} project The project in which to search for tasks. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.findByProject = function( - project, - params, - dispatchOptions -) { - var path = util.format('/projects/%s/tasks', project); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Returns the compact task records for all tasks with the given tag. - * @param {String} tag The tag in which to search for tasks. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.findByTag = function( - tag, - params, - dispatchOptions -) { - var path = util.format('/tags/%s/tasks', tag); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Board view only: Returns the compact section records for all tasks within the given section. - * @param {String} section The section in which to search for tasks. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.findBySection = function( - section, - params, - dispatchOptions -) { - var path = util.format('/sections/%s/tasks', section); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Returns the compact list of tasks in a user's My Tasks list. The returned - * tasks will be in order within each assignee status group of `Inbox`, - * `Today`, and `Upcoming`. - * - * **Note:** tasks in `Later` have a different ordering in the Asana web app - * than the other assignee status groups; this endpoint will still return - * them in list order in `Later` (differently than they show up in Asana, - * but the same order as in Asana's mobile apps). - * - * **Note:** Access control is enforced for this endpoint as with all Asana - * API endpoints, meaning a user's private tasks will be filtered out if the - * API-authenticated user does not have access to them. - * - * **Note:** Both complete and incomplete tasks are returned by default - * unless they are filtered out (for example, setting `completed_since=now` - * will return only incomplete tasks, which is the default view for "My - * Tasks" in Asana.) - * @param {String} user_task_list The user task list in which to search for tasks. - * @param {Object} [params] Parameters for the request - * @param {String} [params.completed_since] Only return tasks that are either incomplete or that have been - * completed since this time. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.findByUserTaskList = function( - userTaskList, - params, - dispatchOptions -) { - var path = util.format('/user_task_lists/%s/tasks', userTaskList); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Returns the compact task records for some filtered set of tasks. Use one - * or more of the parameters provided to filter the tasks returned. You must - * specify a `project`, `section`, `tag`, or `user_task_list` if you do not - * specify `assignee` and `workspace`. - * @param {Object} [params] Parameters for the request - * @param {String} [params.assignee] The assignee to filter tasks on. - * @param {String} [params.workspace] The workspace or organization to filter tasks on. - * @param {String} [params.project] The project to filter tasks on. - * @param {String} [params.section] The section to filter tasks on. - * @param {String} [params.tag] The tag to filter tasks on. - * @param {String} [params.user_task_list] The user task list to filter tasks on. - * @param {String} [params.completed_since] Only return tasks that are either incomplete or that have been - * completed since this time. - * @param {String} [params.modified_since] Only return tasks that have been modified since the given time. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.findAll = function( - params, - dispatchOptions -) { - var path = util.format('/tasks'); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Returns the compact task records for all tasks with the given tag. - * Tasks can have more than one tag at a time. - * @param {String} tag The tag to fetch tasks from. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.getTasksWithTag = function( - tag, - params, - dispatchOptions -) { - var path = util.format('/tags/%s/tasks', tag); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * The search endpoint allows you to build complex queries to find and fetch exactly the data you need from Asana. For a more comprehensive description of all the query parameters and limitations of this endpoint, see our [long-form documentation](/developers/documentation/getting-started/search-api) for this feature. - * @param {String} workspace The workspace or organization in which to search for tasks. - * @param {Object} [params] Parameters for the request - * @param {String} [params.resource_subtype] Filters results by the task's resource_subtype. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.searchInWorkspace = function( - workspace, - params, - dispatchOptions -) { - var path = util.format('/workspaces/%s/tasks/search', workspace); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Returns the compact representations of all of the dependencies of a task. - * @param {String} task The task to get dependencies on. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.dependencies = function( - task, - params, - dispatchOptions -) { - var path = util.format('/tasks/%s/dependencies', task); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * Returns the compact representations of all of the dependents of a task. - * @param {String} task The task to get dependents on. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Tasks.prototype.dependents = function( - task, - params, - dispatchOptions -) { - var path = util.format('/tasks/%s/dependents', task); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * Marks a set of tasks as dependencies of this task, if they are not - * already dependencies. *A task can have at most 15 dependencies.* - * @param {String} task The task to add dependencies to. - * @param {Object} data Data for the request - * @param {Array} data.dependencies An array of task IDs that this task should depend on. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.addDependencies = function( - task, - data, - dispatchOptions -) { - var path = util.format('/tasks/%s/addDependencies', task); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Marks a set of tasks as dependents of this task, if they are not already - * dependents. *A task can have at most 30 dependents.* - * @param {String} task The task to add dependents to. - * @param {Object} data Data for the request - * @param {Array} data.dependents An array of task IDs that should depend on this task. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.addDependents = function( - task, - data, - dispatchOptions -) { - var path = util.format('/tasks/%s/addDependents', task); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Unlinks a set of dependencies from this task. - * @param {String} task The task to remove dependencies from. - * @param {Object} data Data for the request - * @param {Array} data.dependencies An array of task IDs to remove as dependencies. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.removeDependencies = function( - task, - data, - dispatchOptions -) { - var path = util.format('/tasks/%s/removeDependencies', task); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Unlinks a set of dependents from this task. - * @param {String} task The task to remove dependents from. - * @param {Object} data Data for the request - * @param {Array} data.dependents An array of task IDs to remove as dependents. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.removeDependents = function( - task, - data, - dispatchOptions -) { - var path = util.format('/tasks/%s/removeDependents', task); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Adds each of the specified followers to the task, if they are not already - * following. Returns the complete, updated record for the affected task. - * @param {String} task The task to add followers to. - * @param {Object} data Data for the request - * @param {Array} data.followers An array of followers to add to the task. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.addFollowers = function( - task, - data, - dispatchOptions -) { - var path = util.format('/tasks/%s/addFollowers', task); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Removes each of the specified followers from the task if they are - * following. Returns the complete, updated record for the affected task. - * @param {String} task The task to remove followers from. - * @param {Object} data Data for the request - * @param {Array} data.followers An array of followers to remove from the task. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.removeFollowers = function( - task, - data, - dispatchOptions -) { - var path = util.format('/tasks/%s/removeFollowers', task); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Returns a compact representation of all of the projects the task is in. - * @param {String} task The task to get projects on. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.projects = function( - task, - params, - dispatchOptions -) { - var path = util.format('/tasks/%s/projects', task); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Adds the task to the specified project, in the optional location - * specified. If no location arguments are given, the task will be added to - * the end of the project. - * - * `addProject` can also be used to reorder a task within a project or section that - * already contains it. - * - * At most one of `insert_before`, `insert_after`, or `section` should be - * specified. Inserting into a section in an non-order-dependent way can be - * done by specifying `section`, otherwise, to insert within a section in a - * particular place, specify `insert_before` or `insert_after` and a task - * within the section to anchor the position of this task. - * - * Returns an empty data block. - * @param {String} task The task to add to a project. - * @param {Object} data Data for the request - * @param {String} data.project The project to add the task to. - * @param {String} [data.insert_after] A task in the project to insert the task after, or `null` to - * insert at the beginning of the list. - * @param {String} [data.insert_before] A task in the project to insert the task before, or `null` to - * insert at the end of the list. - * @param {String} [data.section] A section in the project to insert the task into. The task will be - * inserted at the bottom of the section. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.addProject = function( - task, - data, - dispatchOptions -) { - var path = util.format('/tasks/%s/addProject', task); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Removes the task from the specified project. The task will still exist - * in the system, but it will not be in the project anymore. - * - * Returns an empty data block. - * @param {String} task The task to remove from a project. - * @param {Object} data Data for the request - * @param {String} data.project The project to remove the task from. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.removeProject = function( - task, - data, - dispatchOptions -) { - var path = util.format('/tasks/%s/removeProject', task); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Returns a compact representation of all of the tags the task has. - * @param {String} task The task to get tags on. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.tags = function( - task, - params, - dispatchOptions -) { - var path = util.format('/tasks/%s/tags', task); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Adds a tag to a task. Returns an empty data block. - * @param {String} task The task to add a tag to. - * @param {Object} data Data for the request - * @param {String} data.tag The tag to add to the task. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.addTag = function( - task, - data, - dispatchOptions -) { - var path = util.format('/tasks/%s/addTag', task); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Removes a tag from the task. Returns an empty data block. - * @param {String} task The task to remove a tag from. - * @param {Object} data Data for the request - * @param {String} data.tag The tag to remove from the task. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.removeTag = function( - task, - data, - dispatchOptions -) { - var path = util.format('/tasks/%s/removeTag', task); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Returns a compact representation of all of the subtasks of a task. - * @param {String} task The task to get the subtasks of. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.subtasks = function( - task, - params, - dispatchOptions -) { - var path = util.format('/tasks/%s/subtasks', task); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Creates a new subtask and adds it to the parent task. Returns the full record - * for the newly created subtask. - * @param {String} task The task to add a subtask to. - * @param {Object} data Data for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.addSubtask = function( - task, - data, - dispatchOptions -) { - var path = util.format('/tasks/%s/subtasks', task); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Returns a compact representation of all of the stories on the task. - * @param {String} task The task containing the stories to get. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.stories = function( - task, - params, - dispatchOptions -) { - var path = util.format('/tasks/%s/stories', task); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Adds a comment to a task. The comment will be authored by the - * currently authenticated user, and timestamped when the server receives - * the request. - * - * Returns the full record for the new story added to the task. - * @param {String} task Globally unique identifier for the task. - * @param {Object} data Data for the request - * @param {String} data.text The plain text of the comment to add. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.addComment = function( - task, - data, - dispatchOptions -) { - var path = util.format('/tasks/%s/stories', task); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Insert or reorder tasks in a user's My Tasks list. If the task was not - * assigned to the owner of the user task list it will be reassigned when - * this endpoint is called. If neither `insert_before` nor `insert_after` - * are provided the task will be inserted at the top of the assignee's - * inbox. - * - * Returns an empty data block. - * @param {String} user_task_list Globally unique identifier for the user task list. - * @param {Object} data Data for the request - * @param {String} data.task Globally unique identifier for the task. - * @param {String} [data.insert_before] Insert the task before the task specified by this field. The inserted - * task will inherit the `assignee_status` of this task. `insert_before` - * and `insert_after` parameters cannot both be specified. - * @param {String} [data.insert_after] Insert the task after the task specified by this field. The inserted - * task will inherit the `assignee_status` of this task. `insert_before` - * and `insert_after` parameters cannot both be specified. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Tasks.prototype.insertInUserTaskList = function( - userTaskList, - data, - dispatchOptions -) { - var path = util.format('/user_task_lists/%s/tasks/insert', userTaskList); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * This is for compatibility reasons. Please use searchInWorkspace. - */ -Tasks.prototype.search = Tasks.prototype.searchInWorkspace; - -/* jshint ignore:end */ -module.exports = Tasks; - -},{"./gen/tasks":47,"lodash":90,"util":119}],68:[function(require,module,exports){ -var Teams = require('./gen/teams'); -/* jshint ignore:start */ -var util = require('util'); - -/** - * Returns the full record for a single team. - * @param {String} team Globally unique identifier for the team. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Teams.prototype.findById = function( - team, - params, - dispatchOptions -) { - var path = util.format('/teams/%s', team); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * Returns the compact records for all teams in the organization visible to - * the authorized user. - * @param {String} organization Globally unique identifier for the workspace or organization. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Teams.prototype.findByOrganization = function( - organization, - params, - dispatchOptions -) { - var path = util.format('/organizations/%s/teams', organization); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Returns the compact records for all teams to which user is assigned. - * @param {String} user An identifier for the user. Can be one of an email address, - * the globally unique identifier for the user, or the keyword `me` - * to indicate the current user making the request. - * @param {Object} [params] Parameters for the request - * @param {String} [params.organization] The workspace or organization to filter teams on. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Teams.prototype.findByUser = function( - user, - params, - dispatchOptions -) { - var path = util.format('/users/%s/teams', user); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Returns the compact records for all users that are members of the team. - * @param {String} team Globally unique identifier for the team. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Teams.prototype.users = function( - team, - params, - dispatchOptions -) { - var path = util.format('/teams/%s/users', team); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * The user making this call must be a member of the team in order to add others. - * The user to add must exist in the same organization as the team in order to be added. - * The user to add can be referenced by their globally unique user ID or their email address. - * Returns the full user record for the added user. - * @param {String} team Globally unique identifier for the team. - * @param {Object} data Data for the request - * @param {String} data.user An identifier for the user. Can be one of an email address, - * the globally unique identifier for the user, or the keyword `me` - * to indicate the current user making the request. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Teams.prototype.addUser = function( - team, - data, - dispatchOptions -) { - var path = util.format('/teams/%s/addUser', team); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * The user to remove can be referenced by their globally unique user ID or their email address. - * Removes the user from the specified team. Returns an empty data record. - * @param {String} team Globally unique identifier for the team. - * @param {Object} data Data for the request - * @param {String} data.user An identifier for the user. Can be one of an email address, - * the globally unique identifier for the user, or the keyword `me` - * to indicate the current user making the request. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Teams.prototype.removeUser = function( - team, - data, - dispatchOptions -) { - var path = util.format('/teams/%s/removeUser', team); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/* jshint ignore:end */ -module.exports = Teams; - -},{"./gen/teams":48,"util":119}],69:[function(require,module,exports){ -var Typeahead = require('./gen/typeahead'); - -module.exports = Typeahead; - -},{"./gen/typeahead":49}],70:[function(require,module,exports){ -var UserTaskLists = require('./gen/user_task_lists'); -/* jshint ignore:start */ -var util = require('util'); - -/** - * Returns the full record for the user task list for the given user - * @param {String} user An identifier for the user. Can be one of an email address, - * the globally unique identifier for the user, or the keyword `me` - * to indicate the current user making the request. - * @param {Object} [params] Parameters for the request - * @param {String} params.workspace Globally unique identifier for the workspace or organization. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -UserTaskLists.prototype.findByUser = function( - user, - params, - dispatchOptions -) { - var path = util.format('/users/%s/user_task_list', user); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * Returns the full record for a user task list. - * @param {String} userTaskList Globally unique identifier for the user task list. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -UserTaskLists.prototype.findById = function( - userTaskList, - params, - dispatchOptions -) { - var path = util.format('/user_task_lists/%s', userTaskList); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * Returns the compact list of tasks in a user's My Tasks list. The returned - * tasks will be in order within each assignee status group of `Inbox`, - * `Today`, and `Upcoming`. - * - * **Note:** tasks in `Later` have a different ordering in the Asana web app - * than the other assignee status groups; this endpoint will still return - * them in list order in `Later` (differently than they show up in Asana, - * but the same order as in Asana's mobile apps). - * - * **Note:** Access control is enforced for this endpoint as with all Asana - * API endpoints, meaning a user's private tasks will be filtered out if the - * API-authenticated user does not have access to them. - * - * **Note:** Both complete and incomplete tasks are returned by default - * unless they are filtered out (for example, setting `completed_since=now` - * will return only incomplete tasks, which is the default view for "My - * Tasks" in Asana.) - * @param {String} userTaskList The user task list in which to search for tasks. - * @param {Object} [params] Parameters for the request - * @param {String} [params.completed_since] Only return tasks that are either incomplete or that have been - * completed since this time. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -UserTaskLists.prototype.tasks = function( - userTaskList, - params, - dispatchOptions -) { - var path = util.format('/user_task_lists/%s/tasks', userTaskList); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/* jshint ignore:end */ -module.exports = UserTaskLists; - -},{"./gen/user_task_lists":50,"util":119}],71:[function(require,module,exports){ -var Users = require('./gen/users'); -/* jshint ignore:start */ -var util = require('util'); - -/** - * Returns the full user record for the currently authenticated user. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Users.prototype.me = function( - params, - dispatchOptions -) { - var path = util.format('/users/me'); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * Returns the full user record for the single user with the provided ID. - * @param {String} user An identifier for the user. Can be one of an email address, - * the globally unique identifier for the user, or the keyword `me` - * to indicate the current user making the request. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Users.prototype.findById = function( - user, - params, - dispatchOptions -) { - var path = util.format('/users/%s', user); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * Returns all of a user's favorites in the given workspace, of the given type. - * Results are given in order (The same order as Asana's sidebar). - * @param {String} user An identifier for the user. Can be one of an email address, - * the globally unique identifier for the user, or the keyword `me` - * to indicate the current user making the request. - * @param {Object} [params] Parameters for the request - * @param {String} params.workspace The workspace in which to get favorites. - * @param {String} params.resource_type The resource type of favorites to be returned. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Users.prototype.getUserFavorites = function( - user, - params, - dispatchOptions -) { - var path = util.format('/users/%s/favorites', user); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Returns the user records for all users in the specified workspace or - * organization. - * @param {String} workspace The workspace in which to get users. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Users.prototype.findByWorkspace = function( - workspace, - params, - dispatchOptions -) { - var path = util.format('/workspaces/%s/users', workspace); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Returns the user records for all users in all workspaces and organizations - * accessible to the authenticated user. Accepts an optional workspace ID - * parameter. - * @param {Object} [params] Parameters for the request - * @param {String} [params.workspace] The workspace or organization to filter users on. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Users.prototype.findAll = function( - params, - dispatchOptions -) { - var path = util.format('/users'); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/* jshint ignore:end */ -module.exports = Users; - -},{"./gen/users":51,"util":119}],72:[function(require,module,exports){ -var Webhooks = require('./gen/webhooks'); -/* jshint ignore:start */ -var util = require('util'); -var _ = require('lodash'); - -/** - * Establishing a webhook is a two-part process. First, a simple HTTP POST - * similar to any other resource creation. Since you could have multiple - * webhooks we recommend specifying a unique local id for each target. - * - * Next comes the confirmation handshake. When a webhook is created, we will - * send a test POST to the `target` with an `X-Hook-Secret` header as - * described in the - * [Resthooks Security documentation](http://resthooks.org/docs/security/). - * The target must respond with a `200 OK` and a matching `X-Hook-Secret` - * header to confirm that this webhook subscription is indeed expected. - * - * If you do not acknowledge the webhook's confirmation handshake it will - * fail to setup, and you will receive an error in response to your attempt - * to create it. This means you need to be able to receive and complete the - * webhook *while* the POST request is in-flight. - * @param {String} resource A resource ID to subscribe to. The resource can be a task or project. - * @param {String} target The URL to receive the HTTP POST. - * @param {Object} data Data for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Webhooks.prototype.create = function( - resource, - target, - data, - dispatchOptions -) { - var path = util.format('/webhooks'); - - data = _.extend({}, data || {}, { - resource: resource, - target: target - }); - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * Returns the compact representation of all webhooks your app has - * registered for the authenticated user in the given workspace. - * @param {String} workspace The workspace to query for webhooks in. - * @param {Object} [params] Parameters for the request - * @param {String} [params.resource] Only return webhooks for the given resource. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Webhooks.prototype.getAll = function( - workspace, - params, - dispatchOptions -) { - var path = util.format('/webhooks'); - - params = _.extend({}, params || {}, { - workspace: workspace - }); - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * Returns the full record for the given webhook. - * @param {String} webhook The webhook to get. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Webhooks.prototype.getById = function( - webhook, - params, - dispatchOptions -) { - var path = util.format('/webhooks/%s', webhook); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * This method permanently removes a webhook. Note that it may be possible - * to receive a request that was already in flight after deleting the - * webhook, but no further requests will be issued. - * @param {String} webhook The webhook to delete. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Webhooks.prototype.deleteById = function( - webhook, - dispatchOptions -) { - var path = util.format('/webhooks/%s', webhook); - - return this.dispatchDelete(path, dispatchOptions); -}; - -/* jshint ignore:end */ -module.exports = Webhooks; - -},{"./gen/webhooks":52,"lodash":90,"util":119}],73:[function(require,module,exports){ -var WorkspaceMemberships = require('./gen/workspace_memberships'); - -module.exports = WorkspaceMemberships; - -},{"./gen/workspace_memberships":53}],74:[function(require,module,exports){ -var Workspaces = require('./gen/workspaces'); -/* jshint ignore:start */ -var util = require('util'); - -/** - * Returns the full workspace record for a single workspace. - * @param {String} workspace Globally unique identifier for the workspace or organization. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The requested resource - */ -Workspaces.prototype.findById = function( - workspace, - params, - dispatchOptions -) { - var path = util.format('/workspaces/%s', workspace); - - return this.dispatchGet(path, params, dispatchOptions); -}; - -/** - * Returns the compact records for all workspaces visible to the authorized user. - * @param {Object} [params] Parameters for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Workspaces.prototype.findAll = function( - params, - dispatchOptions -) { - var path = util.format('/workspaces'); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * A specific, existing workspace can be updated by making a PUT request on - * the URL for that workspace. Only the fields provided in the data block - * will be updated; any unspecified fields will remain unchanged. - * - * Currently the only field that can be modified for a workspace is its `name`. - * - * Returns the complete, updated workspace record. - * @param {String} workspace The workspace to update. - * @param {Object} data Data for the request - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Workspaces.prototype.update = function( - workspace, - data, - dispatchOptions -) { - var path = util.format('/workspaces/%s', workspace); - - return this.dispatchPut(path, data, dispatchOptions); -}; - -/** - * Retrieves objects in the workspace based on an auto-completion/typeahead - * search algorithm. This feature is meant to provide results quickly, so do - * not rely on this API to provide extremely accurate search results. The - * result set is limited to a single page of results with a maximum size, - * so you won't be able to fetch large numbers of results. - * @param {String} workspace The workspace to fetch objects from. - * @param {Object} [params] Parameters for the request - * @param {String} params.resource_type The type of values the typeahead should return. You can choose from - * one of the following: custom_field, project, tag, task, and user. - * Note that unlike in the names of endpoints, the types listed here are - * in singular form (e.g. `task`). Using multiple types is not yet supported. - * @param {String} [params.type] **Deprecated: new integrations should prefer the resource_type field.** - * @param {String} [params.query] The string that will be used to search for relevant objects. If an - * empty string is passed in, the API will currently return an empty - * result set. - * @param {Number} [params.count] The number of results to return. The default is `20` if this - * parameter is omitted, with a minimum of `1` and a maximum of `100`. - * If there are fewer results found than requested, all will be returned. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Workspaces.prototype.typeahead = function( - workspace, - params, - dispatchOptions -) { - var path = util.format('/workspaces/%s/typeahead', workspace); - - return this.dispatchGetCollection(path, params, dispatchOptions); -}; - -/** - * The user can be referenced by their globally unique user ID or their email address. - * Returns the full user record for the invited user. - * @param {String} workspace The workspace or organization to invite the user to. - * @param {Object} data Data for the request - * @param {String} data.user An identifier for the user. Can be one of an email address, - * the globally unique identifier for the user, or the keyword `me` - * to indicate the current user making the request. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Workspaces.prototype.addUser = function( - workspace, - data, - dispatchOptions -) { - var path = util.format('/workspaces/%s/addUser', workspace); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/** - * The user making this call must be an admin in the workspace. - * Returns an empty data record. - * @param {String} workspace The workspace or organization to invite the user to. - * @param {Object} data Data for the request - * @param {String} data.user An identifier for the user. Can be one of an email address, - * the globally unique identifier for the user, or the keyword `me` - * to indicate the current user making the request. - * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * @return {Promise} The response from the API - */ -Workspaces.prototype.removeUser = function( - workspace, - data, - dispatchOptions -) { - var path = util.format('/workspaces/%s/removeUser', workspace); - - return this.dispatchPost(path, data, dispatchOptions); -}; - -/* jshint ignore:end */ -module.exports = Workspaces; - -},{"./gen/workspaces":54,"util":119}],75:[function(require,module,exports){ -var Readable = require('stream').Readable; -var util = require('util'); - -/** - * Creates a readable stream that contains a buffer in case downstream - * pushes back. This is useful for streams that are populated by "expensive" - * requests that return batches of data, because it provides signal (via the - * `_pushUnbuffered` call) as to whether it is buffering. - * - * This is preferable to just piping to some kind of buffering stream, - * because we want to be aware of whether or not we are buffered downstream, - * to avoid making requests from upstream until necessary. If we piped to a - * pure buffering stream it would only make sense for its `push` call to signal - * whether the buffer was full, which is not helpful for our use case. - * - * Instances must override `_readUnbuffered` instead of `_read`, and call - * `pushBuffered` instead of `push`. - * - * @param {Object} options Options for `Readable`. - * @constructor - */ -function BufferedReadable(options) { - Readable.call(this, options); - this._buffer = []; -} - -util.inherits(BufferedReadable, Readable); - -BufferedReadable.prototype._read = function() { - // Drain buffer. - if (this._buffer.length > 0) { - for (var i = 0; i < this._buffer.length; i++) { - if (!this.push(this._buffer[i])) { - this._buffer = this._buffer.slice(i + 1); - return; - } - } - this._buffer = []; - } - // Fill the buffer - this._readUnbuffered(); -}; - -BufferedReadable.prototype.pushBuffered = function(object) { - var buffering = this._buffer.length > 0; - if (!buffering && !this.push(object)) { - buffering = true; - } - if (buffering) { - this._buffer.push(object); - } - return !buffering; -}; - -BufferedReadable.prototype._readUnbuffered = function() { - throw new Error('not implemented'); -}; - -module.exports = BufferedReadable; - -},{"stream":97,"util":119}],76:[function(require,module,exports){ -var Bluebird = require('bluebird'); -var ResourceStream = require('./resource_stream'); - -/* - * @type {Number} Maximum number of items in a collection this library will - * ever return. This is currently way higher than the practical limit - * of items one can expect to get from the API. - */ -var MAX_COLLECTION_SIZE = 100000; - -/** - * Create a Collection object from a response containing a list of resources. - * - * @param {Object} response Full payload from a response to a - * collection request. - * @param {Dispatcher} dispatcher - * @param {Object} [dispatchOptions] - * @returns {Object} Collection - */ - -function Collection(response, dispatcher, dispatchOptions) { - if (!Collection.isCollectionResponse(response)) { - throw new Error( - 'Cannot create Collection from response that does not have resources'); - } - - this.data = response.data; - this._response = response; - this._dispatcher = dispatcher; - this._dispatchOptions = dispatchOptions; -} - -/** - * Transforms a Promise of a raw response into a Promise for a Collection. - * - * @param {Promise} promise - * @param {Dispatcher} dispatcher - * @param {Object} [dispatchOptions] - * @returns {Promise} - */ -Collection.fromDispatch = function(promise, dispatcher, dispatchOptions) { - return promise.then(function(response) { - return new Collection(response, dispatcher, dispatchOptions); - }); -}; - -/** - * @param response {Object} Response that a request promise resolved to - * @returns {boolean} True iff the response is a collection (possibly empty) - */ -Collection.isCollectionResponse = function(response) { - return typeof(response) === 'object' && - typeof(response.data) === 'object' && - typeof(response.data.length) === 'number'; -}; - - -/** - * Return a stream for all the remaining elements in the collection. It will - * automatically fetch more pages as needed. - * @return {ResourceStream} - */ -Collection.prototype.stream = function() { - return new ResourceStream(this); -}; - - -/** - * Get the next page of results in a collection. - * - * @returns {Promise} Resolves to either a collection representing - * the next page of results, or null if no more pages. - */ -Collection.prototype.nextPage = function() { - /* jshint camelcase:false */ - var me = this; - var next = me._response.next_page; - if (typeof(next) === 'object' && next !== null) { - var url = next.uri; - return Collection.fromDispatch( - me._dispatcher.dispatch({ - method: 'GET', - url: url, - json: true - }, me._dispatchOptions), - me._dispatcher, - me._dispatchOptions); - } else { - // No more results. - return Bluebird.resolve(null); - } -}; - - -/** - * Get remaining results from a collection request, transparently - * paginating until pages exhausted or until `maxItems` items collected. - * - * @param {Number} [maxItems] Maximum number of items to return. - * @returns {Promise} Resolves to the entire set of results for the collection - * request. - */ -Collection.prototype.fetch = function(maxItems) { - var me = this; - maxItems = maxItems || MAX_COLLECTION_SIZE; - return new Bluebird(function(resolve, reject) { - // We will build up these results in pages. - var results = []; - - function fetch(collection) { - if (collection === null) { - // Reached end of pages. - resolve(results); - } else { - // Add collected data to results - [].push.apply(results, collection.data); - if (results.length >= maxItems) { - // We have enough - ensure the returned collection is limited by the - // given size, and resolve. - results = results.slice(0, maxItems); - resolve(results); - } else { - // We need more - try to get another page. - collection.nextPage().then(fetch).catch(reject); - } - } - } - - fetch(me); - }); -}; - -module.exports = Collection; - -},{"./resource_stream":78,"bluebird":80}],77:[function(require,module,exports){ -var BufferedReadable = require('./buffered_readable'); -var util = require('util'); - -function EventStream(events, resourceId, options) { - BufferedReadable.call(this, { - objectMode: true - }); - this.resourceId = resourceId; - this.events = events; - this.syncToken = null; - this.options = options || {}; - this.options.periodSeconds = this.options.periodSeconds || 5; - this._lastPollTime = 0; - this._polling = false; -} - -util.inherits(EventStream, BufferedReadable); - -EventStream.prototype._readUnbuffered = function() { - // Poll if we're not already. - if (!this._polling) { - this._schedule(); - } -}; - -EventStream.prototype._schedule = function() { - var me = this; - if (me._lastPollTime === 0) { - // First time reading - just do it. - me._poll(); - } else { - // Schedule a poll for some time in the future based on when we last - // polled. - var now = Date.now(); - var delay = Math.max( - 0, me.options.periodSeconds * 1000 - (now - me._lastPollTime)); - setTimeout(function() { - me._poll(); - }, delay); - } -}; - -EventStream.prototype._poll = function() { - var me = this; - me._polling = true; - - me._lastPollTime = Date.now(); - me.events.get(me.resourceId, me.syncToken).then(function(response) { - // Successful request (though may lack actual data) - // Store off new sync token. - me.syncToken = response.sync; - var available = true; - if (response.data && response.data.length > 0) { - // Response contained actual events! Push them to the stream, or - // buffer them if the stream doesn't want any more. - response.data.forEach(function(event) { - available = available && me.pushBuffered(event); - }); - } - if (available) { - me._schedule(); - } - }).catch(function(error) { - // Failure - emit error. If we survive then the error was "handled" - // and we'll continue to fetch events. - me.emit('error', error); - me._schedule(); - }); -}; - -module.exports = EventStream; -},{"./buffered_readable":75,"util":119}],78:[function(require,module,exports){ -var BufferedReadable = require('./buffered_readable'); -var util = require('util'); - -/** - * A ResourceStream is a Node stream implementation for objects that are - * fetched from the API. Basically, any Collection of resources from the - * API can be wrapped in this stream, and the stream will fetch new pages - * of items as needed. - * - * @param {Collection} collection Response from initial collection request. - * @constructor - */ - -function ResourceStream(collection) { - var me = this; - BufferedReadable.call(me, { - objectMode: true - }); - - // @type {Collection} The collection whose data was last pushed into the - // stream, such that if we have to go back for more, we should fetch - // its `nextPage`. - me._collection = collection; - - // @type {boolean} True iff a request for more items is in flight. - me._fetching = false; - - // Ensure the initial collection's data is in the stream. - me._pushCollection(); -} - -util.inherits(ResourceStream, BufferedReadable); - -ResourceStream.prototype._pushCollection = function() { - var me = this; - me._collection.data.forEach(function(resource) { - me.pushBuffered(resource); - }); -}; - -ResourceStream.prototype._readUnbuffered = function() { - /* jshint camelcase:false */ - var me = this; - - if (!me._collection) { - // No more resources to get. - me.pushBuffered(null); - return; - } - - // Avoid fetching more than the next page, in case a `_read` comes in - // while we are still waiting for results. - if (me._fetching) { - return; - } - me._fetching = true; - - function updateStream(collection) { - me._fetching = false; - if (!collection) { - // No more pages - me.pushBuffered(null); - } else { - me._collection = collection; - me._pushCollection(); - } - } - - function handleError(error) { - // Failure - emit error. - me._fetching = false; - me._collection = null; - me.emit('error', error); - } - - // When response comes back, we will push to stream. - me._collection.nextPage().then(updateStream).catch(handleError); -}; - -module.exports = ResourceStream; -},{"./buffered_readable":75,"util":119}],79:[function(require,module,exports){ -'use strict' - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] -} - -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk( - uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) - )) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') -} - -},{}],80:[function(require,module,exports){ -(function (process,global,setImmediate){ -/* @preserve - * The MIT License (MIT) - * - * Copyright (c) 2013-2018 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -/** - * bluebird build version 3.7.2 - * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each -*/ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0) { - _drainQueueStep(queue); - } -} - -function _drainQueueStep(queue) { - var fn = queue.shift(); - if (typeof fn !== "function") { - fn._settlePromises(); - } else { - var receiver = queue.shift(); - var arg = queue.shift(); - fn.call(receiver, arg); - } -} - -Async.prototype._drainQueues = function () { - _drainQueue(this._normalQueue); - this._reset(); - this._haveDrainedQueues = true; - _drainQueue(this._lateQueue); -}; - -Async.prototype._queueTick = function () { - if (!this._isTickUsed) { - this._isTickUsed = true; - this._schedule(this.drainQueues); - } -}; - -Async.prototype._reset = function () { - this._isTickUsed = false; -}; - -module.exports = Async; -module.exports.firstLineError = firstLineError; - -},{"./queue":26,"./schedule":29}],3:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { -var calledBind = false; -var rejectThis = function(_, e) { - this._reject(e); -}; - -var targetRejected = function(e, context) { - context.promiseRejectionQueued = true; - context.bindingPromise._then(rejectThis, rejectThis, null, this, e); -}; - -var bindingResolved = function(thisArg, context) { - if (((this._bitField & 50397184) === 0)) { - this._resolveCallback(context.target); - } -}; - -var bindingRejected = function(e, context) { - if (!context.promiseRejectionQueued) this._reject(e); -}; - -Promise.prototype.bind = function (thisArg) { - if (!calledBind) { - calledBind = true; - Promise.prototype._propagateFrom = debug.propagateFromFunction(); - Promise.prototype._boundValue = debug.boundValueFunction(); - } - var maybePromise = tryConvertToPromise(thisArg); - var ret = new Promise(INTERNAL); - ret._propagateFrom(this, 1); - var target = this._target(); - ret._setBoundTo(maybePromise); - if (maybePromise instanceof Promise) { - var context = { - promiseRejectionQueued: false, - promise: ret, - target: target, - bindingPromise: maybePromise - }; - target._then(INTERNAL, targetRejected, undefined, ret, context); - maybePromise._then( - bindingResolved, bindingRejected, undefined, ret, context); - ret._setOnCancel(maybePromise); - } else { - ret._resolveCallback(target); - } - return ret; -}; - -Promise.prototype._setBoundTo = function (obj) { - if (obj !== undefined) { - this._bitField = this._bitField | 2097152; - this._boundTo = obj; - } else { - this._bitField = this._bitField & (~2097152); - } -}; - -Promise.prototype._isBound = function () { - return (this._bitField & 2097152) === 2097152; -}; - -Promise.bind = function (thisArg, value) { - return Promise.resolve(value).bind(thisArg); -}; -}; - -},{}],4:[function(_dereq_,module,exports){ -"use strict"; -var old; -if (typeof Promise !== "undefined") old = Promise; -function noConflict() { - try { if (Promise === bluebird) Promise = old; } - catch (e) {} - return bluebird; -} -var bluebird = _dereq_("./promise")(); -bluebird.noConflict = noConflict; -module.exports = bluebird; - -},{"./promise":22}],5:[function(_dereq_,module,exports){ -"use strict"; -var cr = Object.create; -if (cr) { - var callerCache = cr(null); - var getterCache = cr(null); - callerCache[" size"] = getterCache[" size"] = 0; -} - -module.exports = function(Promise) { -var util = _dereq_("./util"); -var canEvaluate = util.canEvaluate; -var isIdentifier = util.isIdentifier; - -var getMethodCaller; -var getGetter; -if (!true) { -var makeMethodCaller = function (methodName) { - return new Function("ensureMethod", " \n\ - return function(obj) { \n\ - 'use strict' \n\ - var len = this.length; \n\ - ensureMethod(obj, 'methodName'); \n\ - switch(len) { \n\ - case 1: return obj.methodName(this[0]); \n\ - case 2: return obj.methodName(this[0], this[1]); \n\ - case 3: return obj.methodName(this[0], this[1], this[2]); \n\ - case 0: return obj.methodName(); \n\ - default: \n\ - return obj.methodName.apply(obj, this); \n\ - } \n\ - }; \n\ - ".replace(/methodName/g, methodName))(ensureMethod); -}; - -var makeGetter = function (propertyName) { - return new Function("obj", " \n\ - 'use strict'; \n\ - return obj.propertyName; \n\ - ".replace("propertyName", propertyName)); -}; - -var getCompiled = function(name, compiler, cache) { - var ret = cache[name]; - if (typeof ret !== "function") { - if (!isIdentifier(name)) { - return null; - } - ret = compiler(name); - cache[name] = ret; - cache[" size"]++; - if (cache[" size"] > 512) { - var keys = Object.keys(cache); - for (var i = 0; i < 256; ++i) delete cache[keys[i]]; - cache[" size"] = keys.length - 256; - } - } - return ret; -}; - -getMethodCaller = function(name) { - return getCompiled(name, makeMethodCaller, callerCache); -}; - -getGetter = function(name) { - return getCompiled(name, makeGetter, getterCache); -}; -} - -function ensureMethod(obj, methodName) { - var fn; - if (obj != null) fn = obj[methodName]; - if (typeof fn !== "function") { - var message = "Object " + util.classString(obj) + " has no method '" + - util.toString(methodName) + "'"; - throw new Promise.TypeError(message); - } - return fn; -} - -function caller(obj) { - var methodName = this.pop(); - var fn = ensureMethod(obj, methodName); - return fn.apply(obj, this); -} -Promise.prototype.call = function (methodName) { - var args = [].slice.call(arguments, 1);; - if (!true) { - if (canEvaluate) { - var maybeCaller = getMethodCaller(methodName); - if (maybeCaller !== null) { - return this._then( - maybeCaller, undefined, undefined, args, undefined); - } - } - } - args.push(methodName); - return this._then(caller, undefined, undefined, args, undefined); -}; - -function namedGetter(obj) { - return obj[this]; -} -function indexedGetter(obj) { - var index = +this; - if (index < 0) index = Math.max(0, index + obj.length); - return obj[index]; -} -Promise.prototype.get = function (propertyName) { - var isIndex = (typeof propertyName === "number"); - var getter; - if (!isIndex) { - if (canEvaluate) { - var maybeGetter = getGetter(propertyName); - getter = maybeGetter !== null ? maybeGetter : namedGetter; - } else { - getter = namedGetter; - } - } else { - getter = indexedGetter; - } - return this._then(getter, undefined, undefined, propertyName, undefined); -}; -}; - -},{"./util":36}],6:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, PromiseArray, apiRejection, debug) { -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var async = Promise._async; - -Promise.prototype["break"] = Promise.prototype.cancel = function() { - if (!debug.cancellation()) return this._warn("cancellation is disabled"); - - var promise = this; - var child = promise; - while (promise._isCancellable()) { - if (!promise._cancelBy(child)) { - if (child._isFollowing()) { - child._followee().cancel(); - } else { - child._cancelBranched(); - } - break; - } - - var parent = promise._cancellationParent; - if (parent == null || !parent._isCancellable()) { - if (promise._isFollowing()) { - promise._followee().cancel(); - } else { - promise._cancelBranched(); - } - break; - } else { - if (promise._isFollowing()) promise._followee().cancel(); - promise._setWillBeCancelled(); - child = promise; - promise = parent; - } - } -}; - -Promise.prototype._branchHasCancelled = function() { - this._branchesRemainingToCancel--; -}; - -Promise.prototype._enoughBranchesHaveCancelled = function() { - return this._branchesRemainingToCancel === undefined || - this._branchesRemainingToCancel <= 0; -}; - -Promise.prototype._cancelBy = function(canceller) { - if (canceller === this) { - this._branchesRemainingToCancel = 0; - this._invokeOnCancel(); - return true; - } else { - this._branchHasCancelled(); - if (this._enoughBranchesHaveCancelled()) { - this._invokeOnCancel(); - return true; - } - } - return false; -}; - -Promise.prototype._cancelBranched = function() { - if (this._enoughBranchesHaveCancelled()) { - this._cancel(); - } -}; - -Promise.prototype._cancel = function() { - if (!this._isCancellable()) return; - this._setCancelled(); - async.invoke(this._cancelPromises, this, undefined); -}; - -Promise.prototype._cancelPromises = function() { - if (this._length() > 0) this._settlePromises(); -}; - -Promise.prototype._unsetOnCancel = function() { - this._onCancelField = undefined; -}; - -Promise.prototype._isCancellable = function() { - return this.isPending() && !this._isCancelled(); -}; - -Promise.prototype.isCancellable = function() { - return this.isPending() && !this.isCancelled(); -}; - -Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { - if (util.isArray(onCancelCallback)) { - for (var i = 0; i < onCancelCallback.length; ++i) { - this._doInvokeOnCancel(onCancelCallback[i], internalOnly); - } - } else if (onCancelCallback !== undefined) { - if (typeof onCancelCallback === "function") { - if (!internalOnly) { - var e = tryCatch(onCancelCallback).call(this._boundValue()); - if (e === errorObj) { - this._attachExtraTrace(e.e); - async.throwLater(e.e); - } - } - } else { - onCancelCallback._resultCancelled(this); - } - } -}; - -Promise.prototype._invokeOnCancel = function() { - var onCancelCallback = this._onCancel(); - this._unsetOnCancel(); - async.invoke(this._doInvokeOnCancel, this, onCancelCallback); -}; - -Promise.prototype._invokeInternalOnCancel = function() { - if (this._isCancellable()) { - this._doInvokeOnCancel(this._onCancel(), true); - this._unsetOnCancel(); - } -}; - -Promise.prototype._resultCancelled = function() { - this.cancel(); -}; - -}; - -},{"./util":36}],7:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(NEXT_FILTER) { -var util = _dereq_("./util"); -var getKeys = _dereq_("./es5").keys; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; - -function catchFilter(instances, cb, promise) { - return function(e) { - var boundTo = promise._boundValue(); - predicateLoop: for (var i = 0; i < instances.length; ++i) { - var item = instances[i]; - - if (item === Error || - (item != null && item.prototype instanceof Error)) { - if (e instanceof item) { - return tryCatch(cb).call(boundTo, e); - } - } else if (typeof item === "function") { - var matchesPredicate = tryCatch(item).call(boundTo, e); - if (matchesPredicate === errorObj) { - return matchesPredicate; - } else if (matchesPredicate) { - return tryCatch(cb).call(boundTo, e); - } - } else if (util.isObject(e)) { - var keys = getKeys(item); - for (var j = 0; j < keys.length; ++j) { - var key = keys[j]; - if (item[key] != e[key]) { - continue predicateLoop; - } - } - return tryCatch(cb).call(boundTo, e); - } - } - return NEXT_FILTER; - }; -} - -return catchFilter; -}; - -},{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise) { -var longStackTraces = false; -var contextStack = []; - -Promise.prototype._promiseCreated = function() {}; -Promise.prototype._pushContext = function() {}; -Promise.prototype._popContext = function() {return null;}; -Promise._peekContext = Promise.prototype._peekContext = function() {}; - -function Context() { - this._trace = new Context.CapturedTrace(peekContext()); -} -Context.prototype._pushContext = function () { - if (this._trace !== undefined) { - this._trace._promiseCreated = null; - contextStack.push(this._trace); - } -}; - -Context.prototype._popContext = function () { - if (this._trace !== undefined) { - var trace = contextStack.pop(); - var ret = trace._promiseCreated; - trace._promiseCreated = null; - return ret; - } - return null; -}; - -function createContext() { - if (longStackTraces) return new Context(); -} - -function peekContext() { - var lastIndex = contextStack.length - 1; - if (lastIndex >= 0) { - return contextStack[lastIndex]; - } - return undefined; -} -Context.CapturedTrace = null; -Context.create = createContext; -Context.deactivateLongStackTraces = function() {}; -Context.activateLongStackTraces = function() { - var Promise_pushContext = Promise.prototype._pushContext; - var Promise_popContext = Promise.prototype._popContext; - var Promise_PeekContext = Promise._peekContext; - var Promise_peekContext = Promise.prototype._peekContext; - var Promise_promiseCreated = Promise.prototype._promiseCreated; - Context.deactivateLongStackTraces = function() { - Promise.prototype._pushContext = Promise_pushContext; - Promise.prototype._popContext = Promise_popContext; - Promise._peekContext = Promise_PeekContext; - Promise.prototype._peekContext = Promise_peekContext; - Promise.prototype._promiseCreated = Promise_promiseCreated; - longStackTraces = false; - }; - longStackTraces = true; - Promise.prototype._pushContext = Context.prototype._pushContext; - Promise.prototype._popContext = Context.prototype._popContext; - Promise._peekContext = Promise.prototype._peekContext = peekContext; - Promise.prototype._promiseCreated = function() { - var ctx = this._peekContext(); - if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; - }; -}; -return Context; -}; - -},{}],9:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, Context, - enableAsyncHooks, disableAsyncHooks) { -var async = Promise._async; -var Warning = _dereq_("./errors").Warning; -var util = _dereq_("./util"); -var es5 = _dereq_("./es5"); -var canAttachTrace = util.canAttachTrace; -var unhandledRejectionHandled; -var possiblyUnhandledRejection; -var bluebirdFramePattern = - /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; -var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; -var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; -var stackFramePattern = null; -var formatStack = null; -var indentStackFrames = false; -var printWarning; -var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && - (true || - util.env("BLUEBIRD_DEBUG") || - util.env("NODE_ENV") === "development")); - -var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && - (debugging || util.env("BLUEBIRD_WARNINGS"))); - -var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && - (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); - -var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && - (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); - -var deferUnhandledRejectionCheck; -(function() { - var promises = []; - - function unhandledRejectionCheck() { - for (var i = 0; i < promises.length; ++i) { - promises[i]._notifyUnhandledRejection(); - } - unhandledRejectionClear(); - } - - function unhandledRejectionClear() { - promises.length = 0; - } - - deferUnhandledRejectionCheck = function(promise) { - promises.push(promise); - setTimeout(unhandledRejectionCheck, 1); - }; - - es5.defineProperty(Promise, "_unhandledRejectionCheck", { - value: unhandledRejectionCheck - }); - es5.defineProperty(Promise, "_unhandledRejectionClear", { - value: unhandledRejectionClear - }); -})(); - -Promise.prototype.suppressUnhandledRejections = function() { - var target = this._target(); - target._bitField = ((target._bitField & (~1048576)) | - 524288); -}; - -Promise.prototype._ensurePossibleRejectionHandled = function () { - if ((this._bitField & 524288) !== 0) return; - this._setRejectionIsUnhandled(); - deferUnhandledRejectionCheck(this); -}; - -Promise.prototype._notifyUnhandledRejectionIsHandled = function () { - fireRejectionEvent("rejectionHandled", - unhandledRejectionHandled, undefined, this); -}; - -Promise.prototype._setReturnedNonUndefined = function() { - this._bitField = this._bitField | 268435456; -}; - -Promise.prototype._returnedNonUndefined = function() { - return (this._bitField & 268435456) !== 0; -}; - -Promise.prototype._notifyUnhandledRejection = function () { - if (this._isRejectionUnhandled()) { - var reason = this._settledValue(); - this._setUnhandledRejectionIsNotified(); - fireRejectionEvent("unhandledRejection", - possiblyUnhandledRejection, reason, this); - } -}; - -Promise.prototype._setUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField | 262144; -}; - -Promise.prototype._unsetUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField & (~262144); -}; - -Promise.prototype._isUnhandledRejectionNotified = function () { - return (this._bitField & 262144) > 0; -}; - -Promise.prototype._setRejectionIsUnhandled = function () { - this._bitField = this._bitField | 1048576; -}; - -Promise.prototype._unsetRejectionIsUnhandled = function () { - this._bitField = this._bitField & (~1048576); - if (this._isUnhandledRejectionNotified()) { - this._unsetUnhandledRejectionIsNotified(); - this._notifyUnhandledRejectionIsHandled(); - } -}; - -Promise.prototype._isRejectionUnhandled = function () { - return (this._bitField & 1048576) > 0; -}; - -Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { - return warn(message, shouldUseOwnTrace, promise || this); -}; - -Promise.onPossiblyUnhandledRejection = function (fn) { - var context = Promise._getContext(); - possiblyUnhandledRejection = util.contextBind(context, fn); -}; - -Promise.onUnhandledRejectionHandled = function (fn) { - var context = Promise._getContext(); - unhandledRejectionHandled = util.contextBind(context, fn); -}; - -var disableLongStackTraces = function() {}; -Promise.longStackTraces = function () { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - if (!config.longStackTraces && longStackTracesIsSupported()) { - var Promise_captureStackTrace = Promise.prototype._captureStackTrace; - var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; - var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace; - config.longStackTraces = true; - disableLongStackTraces = function() { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - Promise.prototype._captureStackTrace = Promise_captureStackTrace; - Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; - Promise.prototype._dereferenceTrace = Promise_dereferenceTrace; - Context.deactivateLongStackTraces(); - config.longStackTraces = false; - }; - Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; - Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; - Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace; - Context.activateLongStackTraces(); - } -}; - -Promise.hasLongStackTraces = function () { - return config.longStackTraces && longStackTracesIsSupported(); -}; - - -var legacyHandlers = { - unhandledrejection: { - before: function() { - var ret = util.global.onunhandledrejection; - util.global.onunhandledrejection = null; - return ret; - }, - after: function(fn) { - util.global.onunhandledrejection = fn; - } - }, - rejectionhandled: { - before: function() { - var ret = util.global.onrejectionhandled; - util.global.onrejectionhandled = null; - return ret; - }, - after: function(fn) { - util.global.onrejectionhandled = fn; - } - } -}; - -var fireDomEvent = (function() { - var dispatch = function(legacy, e) { - if (legacy) { - var fn; - try { - fn = legacy.before(); - return !util.global.dispatchEvent(e); - } finally { - legacy.after(fn); - } - } else { - return !util.global.dispatchEvent(e); - } - }; - try { - if (typeof CustomEvent === "function") { - var event = new CustomEvent("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - name = name.toLowerCase(); - var eventData = { - detail: event, - cancelable: true - }; - var domEvent = new CustomEvent(name, eventData); - es5.defineProperty( - domEvent, "promise", {value: event.promise}); - es5.defineProperty( - domEvent, "reason", {value: event.reason}); - - return dispatch(legacyHandlers[name], domEvent); - }; - } else if (typeof Event === "function") { - var event = new Event("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - name = name.toLowerCase(); - var domEvent = new Event(name, { - cancelable: true - }); - domEvent.detail = event; - es5.defineProperty(domEvent, "promise", {value: event.promise}); - es5.defineProperty(domEvent, "reason", {value: event.reason}); - return dispatch(legacyHandlers[name], domEvent); - }; - } else { - var event = document.createEvent("CustomEvent"); - event.initCustomEvent("testingtheevent", false, true, {}); - util.global.dispatchEvent(event); - return function(name, event) { - name = name.toLowerCase(); - var domEvent = document.createEvent("CustomEvent"); - domEvent.initCustomEvent(name, false, true, - event); - return dispatch(legacyHandlers[name], domEvent); - }; - } - } catch (e) {} - return function() { - return false; - }; -})(); - -var fireGlobalEvent = (function() { - if (util.isNode) { - return function() { - return process.emit.apply(process, arguments); - }; - } else { - if (!util.global) { - return function() { - return false; - }; - } - return function(name) { - var methodName = "on" + name.toLowerCase(); - var method = util.global[methodName]; - if (!method) return false; - method.apply(util.global, [].slice.call(arguments, 1)); - return true; - }; - } -})(); - -function generatePromiseLifecycleEventObject(name, promise) { - return {promise: promise}; -} - -var eventToObjectGenerator = { - promiseCreated: generatePromiseLifecycleEventObject, - promiseFulfilled: generatePromiseLifecycleEventObject, - promiseRejected: generatePromiseLifecycleEventObject, - promiseResolved: generatePromiseLifecycleEventObject, - promiseCancelled: generatePromiseLifecycleEventObject, - promiseChained: function(name, promise, child) { - return {promise: promise, child: child}; - }, - warning: function(name, warning) { - return {warning: warning}; - }, - unhandledRejection: function (name, reason, promise) { - return {reason: reason, promise: promise}; - }, - rejectionHandled: generatePromiseLifecycleEventObject -}; - -var activeFireEvent = function (name) { - var globalEventFired = false; - try { - globalEventFired = fireGlobalEvent.apply(null, arguments); - } catch (e) { - async.throwLater(e); - globalEventFired = true; - } - - var domEventFired = false; - try { - domEventFired = fireDomEvent(name, - eventToObjectGenerator[name].apply(null, arguments)); - } catch (e) { - async.throwLater(e); - domEventFired = true; - } - - return domEventFired || globalEventFired; -}; - -Promise.config = function(opts) { - opts = Object(opts); - if ("longStackTraces" in opts) { - if (opts.longStackTraces) { - Promise.longStackTraces(); - } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { - disableLongStackTraces(); - } - } - if ("warnings" in opts) { - var warningsOption = opts.warnings; - config.warnings = !!warningsOption; - wForgottenReturn = config.warnings; - - if (util.isObject(warningsOption)) { - if ("wForgottenReturn" in warningsOption) { - wForgottenReturn = !!warningsOption.wForgottenReturn; - } - } - } - if ("cancellation" in opts && opts.cancellation && !config.cancellation) { - if (async.haveItemsQueued()) { - throw new Error( - "cannot enable cancellation after promises are in use"); - } - Promise.prototype._clearCancellationData = - cancellationClearCancellationData; - Promise.prototype._propagateFrom = cancellationPropagateFrom; - Promise.prototype._onCancel = cancellationOnCancel; - Promise.prototype._setOnCancel = cancellationSetOnCancel; - Promise.prototype._attachCancellationCallback = - cancellationAttachCancellationCallback; - Promise.prototype._execute = cancellationExecute; - propagateFromFunction = cancellationPropagateFrom; - config.cancellation = true; - } - if ("monitoring" in opts) { - if (opts.monitoring && !config.monitoring) { - config.monitoring = true; - Promise.prototype._fireEvent = activeFireEvent; - } else if (!opts.monitoring && config.monitoring) { - config.monitoring = false; - Promise.prototype._fireEvent = defaultFireEvent; - } - } - if ("asyncHooks" in opts && util.nodeSupportsAsyncResource) { - var prev = config.asyncHooks; - var cur = !!opts.asyncHooks; - if (prev !== cur) { - config.asyncHooks = cur; - if (cur) { - enableAsyncHooks(); - } else { - disableAsyncHooks(); - } - } - } - return Promise; -}; - -function defaultFireEvent() { return false; } - -Promise.prototype._fireEvent = defaultFireEvent; -Promise.prototype._execute = function(executor, resolve, reject) { - try { - executor(resolve, reject); - } catch (e) { - return e; - } -}; -Promise.prototype._onCancel = function () {}; -Promise.prototype._setOnCancel = function (handler) { ; }; -Promise.prototype._attachCancellationCallback = function(onCancel) { - ; -}; -Promise.prototype._captureStackTrace = function () {}; -Promise.prototype._attachExtraTrace = function () {}; -Promise.prototype._dereferenceTrace = function () {}; -Promise.prototype._clearCancellationData = function() {}; -Promise.prototype._propagateFrom = function (parent, flags) { - ; - ; -}; - -function cancellationExecute(executor, resolve, reject) { - var promise = this; - try { - executor(resolve, reject, function(onCancel) { - if (typeof onCancel !== "function") { - throw new TypeError("onCancel must be a function, got: " + - util.toString(onCancel)); - } - promise._attachCancellationCallback(onCancel); - }); - } catch (e) { - return e; - } -} - -function cancellationAttachCancellationCallback(onCancel) { - if (!this._isCancellable()) return this; - - var previousOnCancel = this._onCancel(); - if (previousOnCancel !== undefined) { - if (util.isArray(previousOnCancel)) { - previousOnCancel.push(onCancel); - } else { - this._setOnCancel([previousOnCancel, onCancel]); - } - } else { - this._setOnCancel(onCancel); - } -} - -function cancellationOnCancel() { - return this._onCancelField; -} - -function cancellationSetOnCancel(onCancel) { - this._onCancelField = onCancel; -} - -function cancellationClearCancellationData() { - this._cancellationParent = undefined; - this._onCancelField = undefined; -} - -function cancellationPropagateFrom(parent, flags) { - if ((flags & 1) !== 0) { - this._cancellationParent = parent; - var branchesRemainingToCancel = parent._branchesRemainingToCancel; - if (branchesRemainingToCancel === undefined) { - branchesRemainingToCancel = 0; - } - parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; - } - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } -} - -function bindingPropagateFrom(parent, flags) { - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } -} -var propagateFromFunction = bindingPropagateFrom; - -function boundValueFunction() { - var ret = this._boundTo; - if (ret !== undefined) { - if (ret instanceof Promise) { - if (ret.isFulfilled()) { - return ret.value(); - } else { - return undefined; - } - } - } - return ret; -} - -function longStackTracesCaptureStackTrace() { - this._trace = new CapturedTrace(this._peekContext()); -} - -function longStackTracesAttachExtraTrace(error, ignoreSelf) { - if (canAttachTrace(error)) { - var trace = this._trace; - if (trace !== undefined) { - if (ignoreSelf) trace = trace._parent; - } - if (trace !== undefined) { - trace.attachExtraTrace(error); - } else if (!error.__stackCleaned__) { - var parsed = parseStackAndMessage(error); - util.notEnumerableProp(error, "stack", - parsed.message + "\n" + parsed.stack.join("\n")); - util.notEnumerableProp(error, "__stackCleaned__", true); - } - } -} - -function longStackTracesDereferenceTrace() { - this._trace = undefined; -} - -function checkForgottenReturns(returnValue, promiseCreated, name, promise, - parent) { - if (returnValue === undefined && promiseCreated !== null && - wForgottenReturn) { - if (parent !== undefined && parent._returnedNonUndefined()) return; - if ((promise._bitField & 65535) === 0) return; - - if (name) name = name + " "; - var handlerLine = ""; - var creatorLine = ""; - if (promiseCreated._trace) { - var traceLines = promiseCreated._trace.stack.split("\n"); - var stack = cleanStack(traceLines); - for (var i = stack.length - 1; i >= 0; --i) { - var line = stack[i]; - if (!nodeFramePattern.test(line)) { - var lineMatches = line.match(parseLinePattern); - if (lineMatches) { - handlerLine = "at " + lineMatches[1] + - ":" + lineMatches[2] + ":" + lineMatches[3] + " "; - } - break; - } - } - - if (stack.length > 0) { - var firstUserLine = stack[0]; - for (var i = 0; i < traceLines.length; ++i) { - - if (traceLines[i] === firstUserLine) { - if (i > 0) { - creatorLine = "\n" + traceLines[i - 1]; - } - break; - } - } - - } - } - var msg = "a promise was created in a " + name + - "handler " + handlerLine + "but was not returned from it, " + - "see http://goo.gl/rRqMUw" + - creatorLine; - promise._warn(msg, true, promiseCreated); - } -} - -function deprecated(name, replacement) { - var message = name + - " is deprecated and will be removed in a future version."; - if (replacement) message += " Use " + replacement + " instead."; - return warn(message); -} - -function warn(message, shouldUseOwnTrace, promise) { - if (!config.warnings) return; - var warning = new Warning(message); - var ctx; - if (shouldUseOwnTrace) { - promise._attachExtraTrace(warning); - } else if (config.longStackTraces && (ctx = Promise._peekContext())) { - ctx.attachExtraTrace(warning); - } else { - var parsed = parseStackAndMessage(warning); - warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); - } - - if (!activeFireEvent("warning", warning)) { - formatAndLogError(warning, "", true); - } -} - -function reconstructStack(message, stacks) { - for (var i = 0; i < stacks.length - 1; ++i) { - stacks[i].push("From previous event:"); - stacks[i] = stacks[i].join("\n"); - } - if (i < stacks.length) { - stacks[i] = stacks[i].join("\n"); - } - return message + "\n" + stacks.join("\n"); -} - -function removeDuplicateOrEmptyJumps(stacks) { - for (var i = 0; i < stacks.length; ++i) { - if (stacks[i].length === 0 || - ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { - stacks.splice(i, 1); - i--; - } - } -} - -function removeCommonRoots(stacks) { - var current = stacks[0]; - for (var i = 1; i < stacks.length; ++i) { - var prev = stacks[i]; - var currentLastIndex = current.length - 1; - var currentLastLine = current[currentLastIndex]; - var commonRootMeetPoint = -1; - - for (var j = prev.length - 1; j >= 0; --j) { - if (prev[j] === currentLastLine) { - commonRootMeetPoint = j; - break; - } - } - - for (var j = commonRootMeetPoint; j >= 0; --j) { - var line = prev[j]; - if (current[currentLastIndex] === line) { - current.pop(); - currentLastIndex--; - } else { - break; - } - } - current = prev; - } -} - -function cleanStack(stack) { - var ret = []; - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - var isTraceLine = " (No stack trace)" === line || - stackFramePattern.test(line); - var isInternalFrame = isTraceLine && shouldIgnore(line); - if (isTraceLine && !isInternalFrame) { - if (indentStackFrames && line.charAt(0) !== " ") { - line = " " + line; - } - ret.push(line); - } - } - return ret; -} - -function stackFramesAsArray(error) { - var stack = error.stack.replace(/\s+$/g, "").split("\n"); - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - if (" (No stack trace)" === line || stackFramePattern.test(line)) { - break; - } - } - if (i > 0 && error.name != "SyntaxError") { - stack = stack.slice(i); - } - return stack; -} - -function parseStackAndMessage(error) { - var stack = error.stack; - var message = error.toString(); - stack = typeof stack === "string" && stack.length > 0 - ? stackFramesAsArray(error) : [" (No stack trace)"]; - return { - message: message, - stack: error.name == "SyntaxError" ? stack : cleanStack(stack) - }; -} - -function formatAndLogError(error, title, isSoft) { - if (typeof console !== "undefined") { - var message; - if (util.isObject(error)) { - var stack = error.stack; - message = title + formatStack(stack, error); - } else { - message = title + String(error); - } - if (typeof printWarning === "function") { - printWarning(message, isSoft); - } else if (typeof console.log === "function" || - typeof console.log === "object") { - console.log(message); - } - } -} - -function fireRejectionEvent(name, localHandler, reason, promise) { - var localEventFired = false; - try { - if (typeof localHandler === "function") { - localEventFired = true; - if (name === "rejectionHandled") { - localHandler(promise); - } else { - localHandler(reason, promise); - } - } - } catch (e) { - async.throwLater(e); - } - - if (name === "unhandledRejection") { - if (!activeFireEvent(name, reason, promise) && !localEventFired) { - formatAndLogError(reason, "Unhandled rejection "); - } - } else { - activeFireEvent(name, promise); - } -} - -function formatNonError(obj) { - var str; - if (typeof obj === "function") { - str = "[function " + - (obj.name || "anonymous") + - "]"; - } else { - str = obj && typeof obj.toString === "function" - ? obj.toString() : util.toString(obj); - var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; - if (ruselessToString.test(str)) { - try { - var newStr = JSON.stringify(obj); - str = newStr; - } - catch(e) { - - } - } - if (str.length === 0) { - str = "(empty array)"; - } - } - return ("(<" + snip(str) + ">, no stack trace)"); -} - -function snip(str) { - var maxChars = 41; - if (str.length < maxChars) { - return str; - } - return str.substr(0, maxChars - 3) + "..."; -} - -function longStackTracesIsSupported() { - return typeof captureStackTrace === "function"; -} - -var shouldIgnore = function() { return false; }; -var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; -function parseLineInfo(line) { - var matches = line.match(parseLineInfoRegex); - if (matches) { - return { - fileName: matches[1], - line: parseInt(matches[2], 10) - }; - } -} - -function setBounds(firstLineError, lastLineError) { - if (!longStackTracesIsSupported()) return; - var firstStackLines = (firstLineError.stack || "").split("\n"); - var lastStackLines = (lastLineError.stack || "").split("\n"); - var firstIndex = -1; - var lastIndex = -1; - var firstFileName; - var lastFileName; - for (var i = 0; i < firstStackLines.length; ++i) { - var result = parseLineInfo(firstStackLines[i]); - if (result) { - firstFileName = result.fileName; - firstIndex = result.line; - break; - } - } - for (var i = 0; i < lastStackLines.length; ++i) { - var result = parseLineInfo(lastStackLines[i]); - if (result) { - lastFileName = result.fileName; - lastIndex = result.line; - break; - } - } - if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || - firstFileName !== lastFileName || firstIndex >= lastIndex) { - return; - } - - shouldIgnore = function(line) { - if (bluebirdFramePattern.test(line)) return true; - var info = parseLineInfo(line); - if (info) { - if (info.fileName === firstFileName && - (firstIndex <= info.line && info.line <= lastIndex)) { - return true; - } - } - return false; - }; -} - -function CapturedTrace(parent) { - this._parent = parent; - this._promisesCreated = 0; - var length = this._length = 1 + (parent === undefined ? 0 : parent._length); - captureStackTrace(this, CapturedTrace); - if (length > 32) this.uncycle(); -} -util.inherits(CapturedTrace, Error); -Context.CapturedTrace = CapturedTrace; - -CapturedTrace.prototype.uncycle = function() { - var length = this._length; - if (length < 2) return; - var nodes = []; - var stackToIndex = {}; - - for (var i = 0, node = this; node !== undefined; ++i) { - nodes.push(node); - node = node._parent; - } - length = this._length = i; - for (var i = length - 1; i >= 0; --i) { - var stack = nodes[i].stack; - if (stackToIndex[stack] === undefined) { - stackToIndex[stack] = i; - } - } - for (var i = 0; i < length; ++i) { - var currentStack = nodes[i].stack; - var index = stackToIndex[currentStack]; - if (index !== undefined && index !== i) { - if (index > 0) { - nodes[index - 1]._parent = undefined; - nodes[index - 1]._length = 1; - } - nodes[i]._parent = undefined; - nodes[i]._length = 1; - var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; - - if (index < length - 1) { - cycleEdgeNode._parent = nodes[index + 1]; - cycleEdgeNode._parent.uncycle(); - cycleEdgeNode._length = - cycleEdgeNode._parent._length + 1; - } else { - cycleEdgeNode._parent = undefined; - cycleEdgeNode._length = 1; - } - var currentChildLength = cycleEdgeNode._length + 1; - for (var j = i - 2; j >= 0; --j) { - nodes[j]._length = currentChildLength; - currentChildLength++; - } - return; - } - } -}; - -CapturedTrace.prototype.attachExtraTrace = function(error) { - if (error.__stackCleaned__) return; - this.uncycle(); - var parsed = parseStackAndMessage(error); - var message = parsed.message; - var stacks = [parsed.stack]; - - var trace = this; - while (trace !== undefined) { - stacks.push(cleanStack(trace.stack.split("\n"))); - trace = trace._parent; - } - removeCommonRoots(stacks); - removeDuplicateOrEmptyJumps(stacks); - util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); - util.notEnumerableProp(error, "__stackCleaned__", true); -}; - -var captureStackTrace = (function stackDetection() { - var v8stackFramePattern = /^\s*at\s*/; - var v8stackFormatter = function(stack, error) { - if (typeof stack === "string") return stack; - - if (error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; - - if (typeof Error.stackTraceLimit === "number" && - typeof Error.captureStackTrace === "function") { - Error.stackTraceLimit += 6; - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - var captureStackTrace = Error.captureStackTrace; - - shouldIgnore = function(line) { - return bluebirdFramePattern.test(line); - }; - return function(receiver, ignoreUntil) { - Error.stackTraceLimit += 6; - captureStackTrace(receiver, ignoreUntil); - Error.stackTraceLimit -= 6; - }; - } - var err = new Error(); - - if (typeof err.stack === "string" && - err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { - stackFramePattern = /@/; - formatStack = v8stackFormatter; - indentStackFrames = true; - return function captureStackTrace(o) { - o.stack = new Error().stack; - }; - } - - var hasStackAfterThrow; - try { throw new Error(); } - catch(e) { - hasStackAfterThrow = ("stack" in e); - } - if (!("stack" in err) && hasStackAfterThrow && - typeof Error.stackTraceLimit === "number") { - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - return function captureStackTrace(o) { - Error.stackTraceLimit += 6; - try { throw new Error(); } - catch(e) { o.stack = e.stack; } - Error.stackTraceLimit -= 6; - }; - } - - formatStack = function(stack, error) { - if (typeof stack === "string") return stack; - - if ((typeof error === "object" || - typeof error === "function") && - error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; - - return null; - -})([]); - -if (typeof console !== "undefined" && typeof console.warn !== "undefined") { - printWarning = function (message) { - console.warn(message); - }; - if (util.isNode && process.stderr.isTTY) { - printWarning = function(message, isSoft) { - var color = isSoft ? "\u001b[33m" : "\u001b[31m"; - console.warn(color + message + "\u001b[0m\n"); - }; - } else if (!util.isNode && typeof (new Error().stack) === "string") { - printWarning = function(message, isSoft) { - console.warn("%c" + message, - isSoft ? "color: darkorange" : "color: red"); - }; - } -} - -var config = { - warnings: warnings, - longStackTraces: false, - cancellation: false, - monitoring: false, - asyncHooks: false -}; - -if (longStackTraces) Promise.longStackTraces(); - -return { - asyncHooks: function() { - return config.asyncHooks; - }, - longStackTraces: function() { - return config.longStackTraces; - }, - warnings: function() { - return config.warnings; - }, - cancellation: function() { - return config.cancellation; - }, - monitoring: function() { - return config.monitoring; - }, - propagateFromFunction: function() { - return propagateFromFunction; - }, - boundValueFunction: function() { - return boundValueFunction; - }, - checkForgottenReturns: checkForgottenReturns, - setBounds: setBounds, - warn: warn, - deprecated: deprecated, - CapturedTrace: CapturedTrace, - fireDomEvent: fireDomEvent, - fireGlobalEvent: fireGlobalEvent -}; -}; - -},{"./errors":12,"./es5":13,"./util":36}],10:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise) { -function returner() { - return this.value; -} -function thrower() { - throw this.reason; -} - -Promise.prototype["return"] = -Promise.prototype.thenReturn = function (value) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - returner, undefined, undefined, {value: value}, undefined); -}; - -Promise.prototype["throw"] = -Promise.prototype.thenThrow = function (reason) { - return this._then( - thrower, undefined, undefined, {reason: reason}, undefined); -}; - -Promise.prototype.catchThrow = function (reason) { - if (arguments.length <= 1) { - return this._then( - undefined, thrower, undefined, {reason: reason}, undefined); - } else { - var _reason = arguments[1]; - var handler = function() {throw _reason;}; - return this.caught(reason, handler); - } -}; - -Promise.prototype.catchReturn = function (value) { - if (arguments.length <= 1) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - undefined, returner, undefined, {value: value}, undefined); - } else { - var _value = arguments[1]; - if (_value instanceof Promise) _value.suppressUnhandledRejections(); - var handler = function() {return _value;}; - return this.caught(value, handler); - } -}; -}; - -},{}],11:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var PromiseReduce = Promise.reduce; -var PromiseAll = Promise.all; - -function promiseAllThis() { - return PromiseAll(this); -} - -function PromiseMapSeries(promises, fn) { - return PromiseReduce(promises, fn, INTERNAL, INTERNAL); -} - -Promise.prototype.each = function (fn) { - return PromiseReduce(this, fn, INTERNAL, 0) - ._then(promiseAllThis, undefined, undefined, this, undefined); -}; - -Promise.prototype.mapSeries = function (fn) { - return PromiseReduce(this, fn, INTERNAL, INTERNAL); -}; - -Promise.each = function (promises, fn) { - return PromiseReduce(promises, fn, INTERNAL, 0) - ._then(promiseAllThis, undefined, undefined, promises, undefined); -}; - -Promise.mapSeries = PromiseMapSeries; -}; - - -},{}],12:[function(_dereq_,module,exports){ -"use strict"; -var es5 = _dereq_("./es5"); -var Objectfreeze = es5.freeze; -var util = _dereq_("./util"); -var inherits = util.inherits; -var notEnumerableProp = util.notEnumerableProp; - -function subError(nameProperty, defaultMessage) { - function SubError(message) { - if (!(this instanceof SubError)) return new SubError(message); - notEnumerableProp(this, "message", - typeof message === "string" ? message : defaultMessage); - notEnumerableProp(this, "name", nameProperty); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - Error.call(this); - } - } - inherits(SubError, Error); - return SubError; -} - -var _TypeError, _RangeError; -var Warning = subError("Warning", "warning"); -var CancellationError = subError("CancellationError", "cancellation error"); -var TimeoutError = subError("TimeoutError", "timeout error"); -var AggregateError = subError("AggregateError", "aggregate error"); -try { - _TypeError = TypeError; - _RangeError = RangeError; -} catch(e) { - _TypeError = subError("TypeError", "type error"); - _RangeError = subError("RangeError", "range error"); -} - -var methods = ("join pop push shift unshift slice filter forEach some " + - "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); - -for (var i = 0; i < methods.length; ++i) { - if (typeof Array.prototype[methods[i]] === "function") { - AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; - } -} - -es5.defineProperty(AggregateError.prototype, "length", { - value: 0, - configurable: false, - writable: true, - enumerable: true -}); -AggregateError.prototype["isOperational"] = true; -var level = 0; -AggregateError.prototype.toString = function() { - var indent = Array(level * 4 + 1).join(" "); - var ret = "\n" + indent + "AggregateError of:" + "\n"; - level++; - indent = Array(level * 4 + 1).join(" "); - for (var i = 0; i < this.length; ++i) { - var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; - var lines = str.split("\n"); - for (var j = 0; j < lines.length; ++j) { - lines[j] = indent + lines[j]; - } - str = lines.join("\n"); - ret += str + "\n"; - } - level--; - return ret; -}; - -function OperationalError(message) { - if (!(this instanceof OperationalError)) - return new OperationalError(message); - notEnumerableProp(this, "name", "OperationalError"); - notEnumerableProp(this, "message", message); - this.cause = message; - this["isOperational"] = true; - - if (message instanceof Error) { - notEnumerableProp(this, "message", message.message); - notEnumerableProp(this, "stack", message.stack); - } else if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - -} -inherits(OperationalError, Error); - -var errorTypes = Error["__BluebirdErrorTypes__"]; -if (!errorTypes) { - errorTypes = Objectfreeze({ - CancellationError: CancellationError, - TimeoutError: TimeoutError, - OperationalError: OperationalError, - RejectionError: OperationalError, - AggregateError: AggregateError - }); - es5.defineProperty(Error, "__BluebirdErrorTypes__", { - value: errorTypes, - writable: false, - enumerable: false, - configurable: false - }); -} - -module.exports = { - Error: Error, - TypeError: _TypeError, - RangeError: _RangeError, - CancellationError: errorTypes.CancellationError, - OperationalError: errorTypes.OperationalError, - TimeoutError: errorTypes.TimeoutError, - AggregateError: errorTypes.AggregateError, - Warning: Warning -}; - -},{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){ -var isES5 = (function(){ - "use strict"; - return this === undefined; -})(); - -if (isES5) { - module.exports = { - freeze: Object.freeze, - defineProperty: Object.defineProperty, - getDescriptor: Object.getOwnPropertyDescriptor, - keys: Object.keys, - names: Object.getOwnPropertyNames, - getPrototypeOf: Object.getPrototypeOf, - isArray: Array.isArray, - isES5: isES5, - propertyIsWritable: function(obj, prop) { - var descriptor = Object.getOwnPropertyDescriptor(obj, prop); - return !!(!descriptor || descriptor.writable || descriptor.set); - } - }; -} else { - var has = {}.hasOwnProperty; - var str = {}.toString; - var proto = {}.constructor.prototype; - - var ObjectKeys = function (o) { - var ret = []; - for (var key in o) { - if (has.call(o, key)) { - ret.push(key); - } - } - return ret; - }; - - var ObjectGetDescriptor = function(o, key) { - return {value: o[key]}; - }; - - var ObjectDefineProperty = function (o, key, desc) { - o[key] = desc.value; - return o; - }; - - var ObjectFreeze = function (obj) { - return obj; - }; - - var ObjectGetPrototypeOf = function (obj) { - try { - return Object(obj).constructor.prototype; - } - catch (e) { - return proto; - } - }; - - var ArrayIsArray = function (obj) { - try { - return str.call(obj) === "[object Array]"; - } - catch(e) { - return false; - } - }; - - module.exports = { - isArray: ArrayIsArray, - keys: ObjectKeys, - names: ObjectKeys, - defineProperty: ObjectDefineProperty, - getDescriptor: ObjectGetDescriptor, - freeze: ObjectFreeze, - getPrototypeOf: ObjectGetPrototypeOf, - isES5: isES5, - propertyIsWritable: function() { - return true; - } - }; -} - -},{}],14:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var PromiseMap = Promise.map; - -Promise.prototype.filter = function (fn, options) { - return PromiseMap(this, fn, options, INTERNAL); -}; - -Promise.filter = function (promises, fn, options) { - return PromiseMap(promises, fn, options, INTERNAL); -}; -}; - -},{}],15:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) { -var util = _dereq_("./util"); -var CancellationError = Promise.CancellationError; -var errorObj = util.errorObj; -var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); - -function PassThroughHandlerContext(promise, type, handler) { - this.promise = promise; - this.type = type; - this.handler = handler; - this.called = false; - this.cancelPromise = null; -} - -PassThroughHandlerContext.prototype.isFinallyHandler = function() { - return this.type === 0; -}; - -function FinallyHandlerCancelReaction(finallyHandler) { - this.finallyHandler = finallyHandler; -} - -FinallyHandlerCancelReaction.prototype._resultCancelled = function() { - checkCancel(this.finallyHandler); -}; - -function checkCancel(ctx, reason) { - if (ctx.cancelPromise != null) { - if (arguments.length > 1) { - ctx.cancelPromise._reject(reason); - } else { - ctx.cancelPromise._cancel(); - } - ctx.cancelPromise = null; - return true; - } - return false; -} - -function succeed() { - return finallyHandler.call(this, this.promise._target()._settledValue()); -} -function fail(reason) { - if (checkCancel(this, reason)) return; - errorObj.e = reason; - return errorObj; -} -function finallyHandler(reasonOrValue) { - var promise = this.promise; - var handler = this.handler; - - if (!this.called) { - this.called = true; - var ret = this.isFinallyHandler() - ? handler.call(promise._boundValue()) - : handler.call(promise._boundValue(), reasonOrValue); - if (ret === NEXT_FILTER) { - return ret; - } else if (ret !== undefined) { - promise._setReturnedNonUndefined(); - var maybePromise = tryConvertToPromise(ret, promise); - if (maybePromise instanceof Promise) { - if (this.cancelPromise != null) { - if (maybePromise._isCancelled()) { - var reason = - new CancellationError("late cancellation observer"); - promise._attachExtraTrace(reason); - errorObj.e = reason; - return errorObj; - } else if (maybePromise.isPending()) { - maybePromise._attachCancellationCallback( - new FinallyHandlerCancelReaction(this)); - } - } - return maybePromise._then( - succeed, fail, undefined, this, undefined); - } - } - } - - if (promise.isRejected()) { - checkCancel(this); - errorObj.e = reasonOrValue; - return errorObj; - } else { - checkCancel(this); - return reasonOrValue; - } -} - -Promise.prototype._passThrough = function(handler, type, success, fail) { - if (typeof handler !== "function") return this.then(); - return this._then(success, - fail, - undefined, - new PassThroughHandlerContext(this, type, handler), - undefined); -}; - -Promise.prototype.lastly = -Promise.prototype["finally"] = function (handler) { - return this._passThrough(handler, - 0, - finallyHandler, - finallyHandler); -}; - - -Promise.prototype.tap = function (handler) { - return this._passThrough(handler, 1, finallyHandler); -}; - -Promise.prototype.tapCatch = function (handlerOrPredicate) { - var len = arguments.length; - if(len === 1) { - return this._passThrough(handlerOrPredicate, - 1, - undefined, - finallyHandler); - } else { - var catchInstances = new Array(len - 1), - j = 0, i; - for (i = 0; i < len - 1; ++i) { - var item = arguments[i]; - if (util.isObject(item)) { - catchInstances[j++] = item; - } else { - return Promise.reject(new TypeError( - "tapCatch statement predicate: " - + "expecting an object but got " + util.classString(item) - )); - } - } - catchInstances.length = j; - var handler = arguments[i]; - return this._passThrough(catchFilter(catchInstances, handler, this), - 1, - undefined, - finallyHandler); - } - -}; - -return PassThroughHandlerContext; -}; - -},{"./catch_filter":7,"./util":36}],16:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, - apiRejection, - INTERNAL, - tryConvertToPromise, - Proxyable, - debug) { -var errors = _dereq_("./errors"); -var TypeError = errors.TypeError; -var util = _dereq_("./util"); -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -var yieldHandlers = []; - -function promiseFromYieldHandler(value, yieldHandlers, traceParent) { - for (var i = 0; i < yieldHandlers.length; ++i) { - traceParent._pushContext(); - var result = tryCatch(yieldHandlers[i])(value); - traceParent._popContext(); - if (result === errorObj) { - traceParent._pushContext(); - var ret = Promise.reject(errorObj.e); - traceParent._popContext(); - return ret; - } - var maybePromise = tryConvertToPromise(result, traceParent); - if (maybePromise instanceof Promise) return maybePromise; - } - return null; -} - -function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { - if (debug.cancellation()) { - var internal = new Promise(INTERNAL); - var _finallyPromise = this._finallyPromise = new Promise(INTERNAL); - this._promise = internal.lastly(function() { - return _finallyPromise; - }); - internal._captureStackTrace(); - internal._setOnCancel(this); - } else { - var promise = this._promise = new Promise(INTERNAL); - promise._captureStackTrace(); - } - this._stack = stack; - this._generatorFunction = generatorFunction; - this._receiver = receiver; - this._generator = undefined; - this._yieldHandlers = typeof yieldHandler === "function" - ? [yieldHandler].concat(yieldHandlers) - : yieldHandlers; - this._yieldedPromise = null; - this._cancellationPhase = false; -} -util.inherits(PromiseSpawn, Proxyable); - -PromiseSpawn.prototype._isResolved = function() { - return this._promise === null; -}; - -PromiseSpawn.prototype._cleanup = function() { - this._promise = this._generator = null; - if (debug.cancellation() && this._finallyPromise !== null) { - this._finallyPromise._fulfill(); - this._finallyPromise = null; - } -}; - -PromiseSpawn.prototype._promiseCancelled = function() { - if (this._isResolved()) return; - var implementsReturn = typeof this._generator["return"] !== "undefined"; - - var result; - if (!implementsReturn) { - var reason = new Promise.CancellationError( - "generator .return() sentinel"); - Promise.coroutine.returnSentinel = reason; - this._promise._attachExtraTrace(reason); - this._promise._pushContext(); - result = tryCatch(this._generator["throw"]).call(this._generator, - reason); - this._promise._popContext(); - } else { - this._promise._pushContext(); - result = tryCatch(this._generator["return"]).call(this._generator, - undefined); - this._promise._popContext(); - } - this._cancellationPhase = true; - this._yieldedPromise = null; - this._continue(result); -}; - -PromiseSpawn.prototype._promiseFulfilled = function(value) { - this._yieldedPromise = null; - this._promise._pushContext(); - var result = tryCatch(this._generator.next).call(this._generator, value); - this._promise._popContext(); - this._continue(result); -}; - -PromiseSpawn.prototype._promiseRejected = function(reason) { - this._yieldedPromise = null; - this._promise._attachExtraTrace(reason); - this._promise._pushContext(); - var result = tryCatch(this._generator["throw"]) - .call(this._generator, reason); - this._promise._popContext(); - this._continue(result); -}; - -PromiseSpawn.prototype._resultCancelled = function() { - if (this._yieldedPromise instanceof Promise) { - var promise = this._yieldedPromise; - this._yieldedPromise = null; - promise.cancel(); - } -}; - -PromiseSpawn.prototype.promise = function () { - return this._promise; -}; - -PromiseSpawn.prototype._run = function () { - this._generator = this._generatorFunction.call(this._receiver); - this._receiver = - this._generatorFunction = undefined; - this._promiseFulfilled(undefined); -}; - -PromiseSpawn.prototype._continue = function (result) { - var promise = this._promise; - if (result === errorObj) { - this._cleanup(); - if (this._cancellationPhase) { - return promise.cancel(); - } else { - return promise._rejectCallback(result.e, false); - } - } - - var value = result.value; - if (result.done === true) { - this._cleanup(); - if (this._cancellationPhase) { - return promise.cancel(); - } else { - return promise._resolveCallback(value); - } - } else { - var maybePromise = tryConvertToPromise(value, this._promise); - if (!(maybePromise instanceof Promise)) { - maybePromise = - promiseFromYieldHandler(maybePromise, - this._yieldHandlers, - this._promise); - if (maybePromise === null) { - this._promiseRejected( - new TypeError( - "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", String(value)) + - "From coroutine:\u000a" + - this._stack.split("\n").slice(1, -7).join("\n") - ) - ); - return; - } - } - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - this._yieldedPromise = maybePromise; - maybePromise._proxy(this, null); - } else if (((bitField & 33554432) !== 0)) { - Promise._async.invoke( - this._promiseFulfilled, this, maybePromise._value() - ); - } else if (((bitField & 16777216) !== 0)) { - Promise._async.invoke( - this._promiseRejected, this, maybePromise._reason() - ); - } else { - this._promiseCancelled(); - } - } -}; - -Promise.coroutine = function (generatorFunction, options) { - if (typeof generatorFunction !== "function") { - throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var yieldHandler = Object(options).yieldHandler; - var PromiseSpawn$ = PromiseSpawn; - var stack = new Error().stack; - return function () { - var generator = generatorFunction.apply(this, arguments); - var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, - stack); - var ret = spawn.promise(); - spawn._generator = generator; - spawn._promiseFulfilled(undefined); - return ret; - }; -}; - -Promise.coroutine.addYieldHandler = function(fn) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - yieldHandlers.push(fn); -}; - -Promise.spawn = function (generatorFunction) { - debug.deprecated("Promise.spawn()", "Promise.coroutine()"); - if (typeof generatorFunction !== "function") { - return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var spawn = new PromiseSpawn(generatorFunction, this); - var ret = spawn.promise(); - spawn._run(Promise.spawn); - return ret; -}; -}; - -},{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){ -"use strict"; -module.exports = -function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async) { -var util = _dereq_("./util"); -var canEvaluate = util.canEvaluate; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var reject; - -if (!true) { -if (canEvaluate) { - var thenCallback = function(i) { - return new Function("value", "holder", " \n\ - 'use strict'; \n\ - holder.pIndex = value; \n\ - holder.checkFulfillment(this); \n\ - ".replace(/Index/g, i)); - }; - - var promiseSetter = function(i) { - return new Function("promise", "holder", " \n\ - 'use strict'; \n\ - holder.pIndex = promise; \n\ - ".replace(/Index/g, i)); - }; - - var generateHolderClass = function(total) { - var props = new Array(total); - for (var i = 0; i < props.length; ++i) { - props[i] = "this.p" + (i+1); - } - var assignment = props.join(" = ") + " = null;"; - var cancellationCode= "var promise;\n" + props.map(function(prop) { - return " \n\ - promise = " + prop + "; \n\ - if (promise instanceof Promise) { \n\ - promise.cancel(); \n\ - } \n\ - "; - }).join("\n"); - var passedArguments = props.join(", "); - var name = "Holder$" + total; - - - var code = "return function(tryCatch, errorObj, Promise, async) { \n\ - 'use strict'; \n\ - function [TheName](fn) { \n\ - [TheProperties] \n\ - this.fn = fn; \n\ - this.asyncNeeded = true; \n\ - this.now = 0; \n\ - } \n\ - \n\ - [TheName].prototype._callFunction = function(promise) { \n\ - promise._pushContext(); \n\ - var ret = tryCatch(this.fn)([ThePassedArguments]); \n\ - promise._popContext(); \n\ - if (ret === errorObj) { \n\ - promise._rejectCallback(ret.e, false); \n\ - } else { \n\ - promise._resolveCallback(ret); \n\ - } \n\ - }; \n\ - \n\ - [TheName].prototype.checkFulfillment = function(promise) { \n\ - var now = ++this.now; \n\ - if (now === [TheTotal]) { \n\ - if (this.asyncNeeded) { \n\ - async.invoke(this._callFunction, this, promise); \n\ - } else { \n\ - this._callFunction(promise); \n\ - } \n\ - \n\ - } \n\ - }; \n\ - \n\ - [TheName].prototype._resultCancelled = function() { \n\ - [CancellationCode] \n\ - }; \n\ - \n\ - return [TheName]; \n\ - }(tryCatch, errorObj, Promise, async); \n\ - "; - - code = code.replace(/\[TheName\]/g, name) - .replace(/\[TheTotal\]/g, total) - .replace(/\[ThePassedArguments\]/g, passedArguments) - .replace(/\[TheProperties\]/g, assignment) - .replace(/\[CancellationCode\]/g, cancellationCode); - - return new Function("tryCatch", "errorObj", "Promise", "async", code) - (tryCatch, errorObj, Promise, async); - }; - - var holderClasses = []; - var thenCallbacks = []; - var promiseSetters = []; - - for (var i = 0; i < 8; ++i) { - holderClasses.push(generateHolderClass(i + 1)); - thenCallbacks.push(thenCallback(i + 1)); - promiseSetters.push(promiseSetter(i + 1)); - } - - reject = function (reason) { - this._reject(reason); - }; -}} - -Promise.join = function () { - var last = arguments.length - 1; - var fn; - if (last > 0 && typeof arguments[last] === "function") { - fn = arguments[last]; - if (!true) { - if (last <= 8 && canEvaluate) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - var HolderClass = holderClasses[last - 1]; - var holder = new HolderClass(fn); - var callbacks = thenCallbacks; - - for (var i = 0; i < last; ++i) { - var maybePromise = tryConvertToPromise(arguments[i], ret); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - maybePromise._then(callbacks[i], reject, - undefined, ret, holder); - promiseSetters[i](maybePromise, holder); - holder.asyncNeeded = false; - } else if (((bitField & 33554432) !== 0)) { - callbacks[i].call(ret, - maybePromise._value(), holder); - } else if (((bitField & 16777216) !== 0)) { - ret._reject(maybePromise._reason()); - } else { - ret._cancel(); - } - } else { - callbacks[i].call(ret, maybePromise, holder); - } - } - - if (!ret._isFateSealed()) { - if (holder.asyncNeeded) { - var context = Promise._getContext(); - holder.fn = util.contextBind(context, holder.fn); - } - ret._setAsyncGuaranteed(); - ret._setOnCancel(holder); - } - return ret; - } - } - } - var args = [].slice.call(arguments);; - if (fn) args.pop(); - var ret = new PromiseArray(args).promise(); - return fn !== undefined ? ret.spread(fn) : ret; -}; - -}; - -},{"./util":36}],18:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var async = Promise._async; - -function MappingPromiseArray(promises, fn, limit, _filter) { - this.constructor$(promises); - this._promise._captureStackTrace(); - var context = Promise._getContext(); - this._callback = util.contextBind(context, fn); - this._preservedValues = _filter === INTERNAL - ? new Array(this.length()) - : null; - this._limit = limit; - this._inFlight = 0; - this._queue = []; - async.invoke(this._asyncInit, this, undefined); - if (util.isArray(promises)) { - for (var i = 0; i < promises.length; ++i) { - var maybePromise = promises[i]; - if (maybePromise instanceof Promise) { - maybePromise.suppressUnhandledRejections(); - } - } - } -} -util.inherits(MappingPromiseArray, PromiseArray); - -MappingPromiseArray.prototype._asyncInit = function() { - this._init$(undefined, -2); -}; - -MappingPromiseArray.prototype._init = function () {}; - -MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { - var values = this._values; - var length = this.length(); - var preservedValues = this._preservedValues; - var limit = this._limit; - - if (index < 0) { - index = (index * -1) - 1; - values[index] = value; - if (limit >= 1) { - this._inFlight--; - this._drainQueue(); - if (this._isResolved()) return true; - } - } else { - if (limit >= 1 && this._inFlight >= limit) { - values[index] = value; - this._queue.push(index); - return false; - } - if (preservedValues !== null) preservedValues[index] = value; - - var promise = this._promise; - var callback = this._callback; - var receiver = promise._boundValue(); - promise._pushContext(); - var ret = tryCatch(callback).call(receiver, value, index, length); - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - preservedValues !== null ? "Promise.filter" : "Promise.map", - promise - ); - if (ret === errorObj) { - this._reject(ret.e); - return true; - } - - var maybePromise = tryConvertToPromise(ret, this._promise); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - if (limit >= 1) this._inFlight++; - values[index] = maybePromise; - maybePromise._proxy(this, (index + 1) * -1); - return false; - } else if (((bitField & 33554432) !== 0)) { - ret = maybePromise._value(); - } else if (((bitField & 16777216) !== 0)) { - this._reject(maybePromise._reason()); - return true; - } else { - this._cancel(); - return true; - } - } - values[index] = ret; - } - var totalResolved = ++this._totalResolved; - if (totalResolved >= length) { - if (preservedValues !== null) { - this._filter(values, preservedValues); - } else { - this._resolve(values); - } - return true; - } - return false; -}; - -MappingPromiseArray.prototype._drainQueue = function () { - var queue = this._queue; - var limit = this._limit; - var values = this._values; - while (queue.length > 0 && this._inFlight < limit) { - if (this._isResolved()) return; - var index = queue.pop(); - this._promiseFulfilled(values[index], index); - } -}; - -MappingPromiseArray.prototype._filter = function (booleans, values) { - var len = values.length; - var ret = new Array(len); - var j = 0; - for (var i = 0; i < len; ++i) { - if (booleans[i]) ret[j++] = values[i]; - } - ret.length = j; - this._resolve(ret); -}; - -MappingPromiseArray.prototype.preservedValues = function () { - return this._preservedValues; -}; - -function map(promises, fn, options, _filter) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - - var limit = 0; - if (options !== undefined) { - if (typeof options === "object" && options !== null) { - if (typeof options.concurrency !== "number") { - return Promise.reject( - new TypeError("'concurrency' must be a number but it is " + - util.classString(options.concurrency))); - } - limit = options.concurrency; - } else { - return Promise.reject(new TypeError( - "options argument must be an object but it is " + - util.classString(options))); - } - } - limit = typeof limit === "number" && - isFinite(limit) && limit >= 1 ? limit : 0; - return new MappingPromiseArray(promises, fn, limit, _filter).promise(); -} - -Promise.prototype.map = function (fn, options) { - return map(this, fn, options, null); -}; - -Promise.map = function (promises, fn, options, _filter) { - return map(promises, fn, options, _filter); -}; - - -}; - -},{"./util":36}],19:[function(_dereq_,module,exports){ -"use strict"; -module.exports = -function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; - -Promise.method = function (fn) { - if (typeof fn !== "function") { - throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); - } - return function () { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value = tryCatch(fn).apply(this, arguments); - var promiseCreated = ret._popContext(); - debug.checkForgottenReturns( - value, promiseCreated, "Promise.method", ret); - ret._resolveFromSyncValue(value); - return ret; - }; -}; - -Promise.attempt = Promise["try"] = function (fn) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value; - if (arguments.length > 1) { - debug.deprecated("calling Promise.try with more than 1 argument"); - var arg = arguments[1]; - var ctx = arguments[2]; - value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) - : tryCatch(fn).call(ctx, arg); - } else { - value = tryCatch(fn)(); - } - var promiseCreated = ret._popContext(); - debug.checkForgottenReturns( - value, promiseCreated, "Promise.try", ret); - ret._resolveFromSyncValue(value); - return ret; -}; - -Promise.prototype._resolveFromSyncValue = function (value) { - if (value === util.errorObj) { - this._rejectCallback(value.e, false); - } else { - this._resolveCallback(value, true); - } -}; -}; - -},{"./util":36}],20:[function(_dereq_,module,exports){ -"use strict"; -var util = _dereq_("./util"); -var maybeWrapAsError = util.maybeWrapAsError; -var errors = _dereq_("./errors"); -var OperationalError = errors.OperationalError; -var es5 = _dereq_("./es5"); - -function isUntypedError(obj) { - return obj instanceof Error && - es5.getPrototypeOf(obj) === Error.prototype; -} - -var rErrorKey = /^(?:name|message|stack|cause)$/; -function wrapAsOperationalError(obj) { - var ret; - if (isUntypedError(obj)) { - ret = new OperationalError(obj); - ret.name = obj.name; - ret.message = obj.message; - ret.stack = obj.stack; - var keys = es5.keys(obj); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (!rErrorKey.test(key)) { - ret[key] = obj[key]; - } - } - return ret; - } - util.markAsOriginatingFromRejection(obj); - return obj; -} - -function nodebackForPromise(promise, multiArgs) { - return function(err, value) { - if (promise === null) return; - if (err) { - var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); - promise._attachExtraTrace(wrapped); - promise._reject(wrapped); - } else if (!multiArgs) { - promise._fulfill(value); - } else { - var args = [].slice.call(arguments, 1);; - promise._fulfill(args); - } - promise = null; - }; -} - -module.exports = nodebackForPromise; - -},{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise) { -var util = _dereq_("./util"); -var async = Promise._async; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; - -function spreadAdapter(val, nodeback) { - var promise = this; - if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); - var ret = - tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} - -function successAdapter(val, nodeback) { - var promise = this; - var receiver = promise._boundValue(); - var ret = val === undefined - ? tryCatch(nodeback).call(receiver, null) - : tryCatch(nodeback).call(receiver, null, val); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} -function errorAdapter(reason, nodeback) { - var promise = this; - if (!reason) { - var newReason = new Error(reason + ""); - newReason.cause = reason; - reason = newReason; - } - var ret = tryCatch(nodeback).call(promise._boundValue(), reason); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} - -Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, - options) { - if (typeof nodeback == "function") { - var adapter = successAdapter; - if (options !== undefined && Object(options).spread) { - adapter = spreadAdapter; - } - this._then( - adapter, - errorAdapter, - undefined, - this, - nodeback - ); - } - return this; -}; -}; - -},{"./util":36}],22:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function() { -var makeSelfResolutionError = function () { - return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); -}; -var reflectHandler = function() { - return new Promise.PromiseInspection(this._target()); -}; -var apiRejection = function(msg) { - return Promise.reject(new TypeError(msg)); -}; -function Proxyable() {} -var UNDEFINED_BINDING = {}; -var util = _dereq_("./util"); -util.setReflectHandler(reflectHandler); - -var getDomain = function() { - var domain = process.domain; - if (domain === undefined) { - return null; - } - return domain; -}; -var getContextDefault = function() { - return null; -}; -var getContextDomain = function() { - return { - domain: getDomain(), - async: null - }; -}; -var AsyncResource = util.isNode && util.nodeSupportsAsyncResource ? - _dereq_("async_hooks").AsyncResource : null; -var getContextAsyncHooks = function() { - return { - domain: getDomain(), - async: new AsyncResource("Bluebird::Promise") - }; -}; -var getContext = util.isNode ? getContextDomain : getContextDefault; -util.notEnumerableProp(Promise, "_getContext", getContext); -var enableAsyncHooks = function() { - getContext = getContextAsyncHooks; - util.notEnumerableProp(Promise, "_getContext", getContextAsyncHooks); -}; -var disableAsyncHooks = function() { - getContext = getContextDomain; - util.notEnumerableProp(Promise, "_getContext", getContextDomain); -}; - -var es5 = _dereq_("./es5"); -var Async = _dereq_("./async"); -var async = new Async(); -es5.defineProperty(Promise, "_async", {value: async}); -var errors = _dereq_("./errors"); -var TypeError = Promise.TypeError = errors.TypeError; -Promise.RangeError = errors.RangeError; -var CancellationError = Promise.CancellationError = errors.CancellationError; -Promise.TimeoutError = errors.TimeoutError; -Promise.OperationalError = errors.OperationalError; -Promise.RejectionError = errors.OperationalError; -Promise.AggregateError = errors.AggregateError; -var INTERNAL = function(){}; -var APPLY = {}; -var NEXT_FILTER = {}; -var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); -var PromiseArray = - _dereq_("./promise_array")(Promise, INTERNAL, - tryConvertToPromise, apiRejection, Proxyable); -var Context = _dereq_("./context")(Promise); - /*jshint unused:false*/ -var createContext = Context.create; - -var debug = _dereq_("./debuggability")(Promise, Context, - enableAsyncHooks, disableAsyncHooks); -var CapturedTrace = debug.CapturedTrace; -var PassThroughHandlerContext = - _dereq_("./finally")(Promise, tryConvertToPromise, NEXT_FILTER); -var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); -var nodebackForPromise = _dereq_("./nodeback"); -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -function check(self, executor) { - if (self == null || self.constructor !== Promise) { - throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - if (typeof executor !== "function") { - throw new TypeError("expecting a function but got " + util.classString(executor)); - } - -} - -function Promise(executor) { - if (executor !== INTERNAL) { - check(this, executor); - } - this._bitField = 0; - this._fulfillmentHandler0 = undefined; - this._rejectionHandler0 = undefined; - this._promise0 = undefined; - this._receiver0 = undefined; - this._resolveFromExecutor(executor); - this._promiseCreated(); - this._fireEvent("promiseCreated", this); -} - -Promise.prototype.toString = function () { - return "[object Promise]"; -}; - -Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { - var len = arguments.length; - if (len > 1) { - var catchInstances = new Array(len - 1), - j = 0, i; - for (i = 0; i < len - 1; ++i) { - var item = arguments[i]; - if (util.isObject(item)) { - catchInstances[j++] = item; - } else { - return apiRejection("Catch statement predicate: " + - "expecting an object but got " + util.classString(item)); - } - } - catchInstances.length = j; - fn = arguments[i]; - - if (typeof fn !== "function") { - throw new TypeError("The last argument to .catch() " + - "must be a function, got " + util.toString(fn)); - } - return this.then(undefined, catchFilter(catchInstances, fn, this)); - } - return this.then(undefined, fn); -}; - -Promise.prototype.reflect = function () { - return this._then(reflectHandler, - reflectHandler, undefined, this, undefined); -}; - -Promise.prototype.then = function (didFulfill, didReject) { - if (debug.warnings() && arguments.length > 0 && - typeof didFulfill !== "function" && - typeof didReject !== "function") { - var msg = ".then() only accepts functions but was passed: " + - util.classString(didFulfill); - if (arguments.length > 1) { - msg += ", " + util.classString(didReject); - } - this._warn(msg); - } - return this._then(didFulfill, didReject, undefined, undefined, undefined); -}; - -Promise.prototype.done = function (didFulfill, didReject) { - var promise = - this._then(didFulfill, didReject, undefined, undefined, undefined); - promise._setIsFinal(); -}; - -Promise.prototype.spread = function (fn) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - return this.all()._then(fn, undefined, undefined, APPLY, undefined); -}; - -Promise.prototype.toJSON = function () { - var ret = { - isFulfilled: false, - isRejected: false, - fulfillmentValue: undefined, - rejectionReason: undefined - }; - if (this.isFulfilled()) { - ret.fulfillmentValue = this.value(); - ret.isFulfilled = true; - } else if (this.isRejected()) { - ret.rejectionReason = this.reason(); - ret.isRejected = true; - } - return ret; -}; - -Promise.prototype.all = function () { - if (arguments.length > 0) { - this._warn(".all() was passed arguments but it does not take any"); - } - return new PromiseArray(this).promise(); -}; - -Promise.prototype.error = function (fn) { - return this.caught(util.originatesFromRejection, fn); -}; - -Promise.getNewLibraryCopy = module.exports; - -Promise.is = function (val) { - return val instanceof Promise; -}; - -Promise.fromNode = Promise.fromCallback = function(fn) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs - : false; - var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); - if (result === errorObj) { - ret._rejectCallback(result.e, true); - } - if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); - return ret; -}; - -Promise.all = function (promises) { - return new PromiseArray(promises).promise(); -}; - -Promise.cast = function (obj) { - var ret = tryConvertToPromise(obj); - if (!(ret instanceof Promise)) { - ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._setFulfilled(); - ret._rejectionHandler0 = obj; - } - return ret; -}; - -Promise.resolve = Promise.fulfilled = Promise.cast; - -Promise.reject = Promise.rejected = function (reason) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._rejectCallback(reason, true); - return ret; -}; - -Promise.setScheduler = function(fn) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - return async.setScheduler(fn); -}; - -Promise.prototype._then = function ( - didFulfill, - didReject, - _, receiver, - internalData -) { - var haveInternalData = internalData !== undefined; - var promise = haveInternalData ? internalData : new Promise(INTERNAL); - var target = this._target(); - var bitField = target._bitField; - - if (!haveInternalData) { - promise._propagateFrom(this, 3); - promise._captureStackTrace(); - if (receiver === undefined && - ((this._bitField & 2097152) !== 0)) { - if (!((bitField & 50397184) === 0)) { - receiver = this._boundValue(); - } else { - receiver = target === this ? undefined : this._boundTo; - } - } - this._fireEvent("promiseChained", this, promise); - } - - var context = getContext(); - if (!((bitField & 50397184) === 0)) { - var handler, value, settler = target._settlePromiseCtx; - if (((bitField & 33554432) !== 0)) { - value = target._rejectionHandler0; - handler = didFulfill; - } else if (((bitField & 16777216) !== 0)) { - value = target._fulfillmentHandler0; - handler = didReject; - target._unsetRejectionIsUnhandled(); - } else { - settler = target._settlePromiseLateCancellationObserver; - value = new CancellationError("late cancellation observer"); - target._attachExtraTrace(value); - handler = didReject; - } - - async.invoke(settler, target, { - handler: util.contextBind(context, handler), - promise: promise, - receiver: receiver, - value: value - }); - } else { - target._addCallbacks(didFulfill, didReject, promise, - receiver, context); - } - - return promise; -}; - -Promise.prototype._length = function () { - return this._bitField & 65535; -}; - -Promise.prototype._isFateSealed = function () { - return (this._bitField & 117506048) !== 0; -}; - -Promise.prototype._isFollowing = function () { - return (this._bitField & 67108864) === 67108864; -}; - -Promise.prototype._setLength = function (len) { - this._bitField = (this._bitField & -65536) | - (len & 65535); -}; - -Promise.prototype._setFulfilled = function () { - this._bitField = this._bitField | 33554432; - this._fireEvent("promiseFulfilled", this); -}; - -Promise.prototype._setRejected = function () { - this._bitField = this._bitField | 16777216; - this._fireEvent("promiseRejected", this); -}; - -Promise.prototype._setFollowing = function () { - this._bitField = this._bitField | 67108864; - this._fireEvent("promiseResolved", this); -}; - -Promise.prototype._setIsFinal = function () { - this._bitField = this._bitField | 4194304; -}; - -Promise.prototype._isFinal = function () { - return (this._bitField & 4194304) > 0; -}; - -Promise.prototype._unsetCancelled = function() { - this._bitField = this._bitField & (~65536); -}; - -Promise.prototype._setCancelled = function() { - this._bitField = this._bitField | 65536; - this._fireEvent("promiseCancelled", this); -}; - -Promise.prototype._setWillBeCancelled = function() { - this._bitField = this._bitField | 8388608; -}; - -Promise.prototype._setAsyncGuaranteed = function() { - if (async.hasCustomScheduler()) return; - var bitField = this._bitField; - this._bitField = bitField | - (((bitField & 536870912) >> 2) ^ - 134217728); -}; - -Promise.prototype._setNoAsyncGuarantee = function() { - this._bitField = (this._bitField | 536870912) & - (~134217728); -}; - -Promise.prototype._receiverAt = function (index) { - var ret = index === 0 ? this._receiver0 : this[ - index * 4 - 4 + 3]; - if (ret === UNDEFINED_BINDING) { - return undefined; - } else if (ret === undefined && this._isBound()) { - return this._boundValue(); - } - return ret; -}; - -Promise.prototype._promiseAt = function (index) { - return this[ - index * 4 - 4 + 2]; -}; - -Promise.prototype._fulfillmentHandlerAt = function (index) { - return this[ - index * 4 - 4 + 0]; -}; - -Promise.prototype._rejectionHandlerAt = function (index) { - return this[ - index * 4 - 4 + 1]; -}; - -Promise.prototype._boundValue = function() {}; - -Promise.prototype._migrateCallback0 = function (follower) { - var bitField = follower._bitField; - var fulfill = follower._fulfillmentHandler0; - var reject = follower._rejectionHandler0; - var promise = follower._promise0; - var receiver = follower._receiverAt(0); - if (receiver === undefined) receiver = UNDEFINED_BINDING; - this._addCallbacks(fulfill, reject, promise, receiver, null); -}; - -Promise.prototype._migrateCallbackAt = function (follower, index) { - var fulfill = follower._fulfillmentHandlerAt(index); - var reject = follower._rejectionHandlerAt(index); - var promise = follower._promiseAt(index); - var receiver = follower._receiverAt(index); - if (receiver === undefined) receiver = UNDEFINED_BINDING; - this._addCallbacks(fulfill, reject, promise, receiver, null); -}; - -Promise.prototype._addCallbacks = function ( - fulfill, - reject, - promise, - receiver, - context -) { - var index = this._length(); - - if (index >= 65535 - 4) { - index = 0; - this._setLength(0); - } - - if (index === 0) { - this._promise0 = promise; - this._receiver0 = receiver; - if (typeof fulfill === "function") { - this._fulfillmentHandler0 = util.contextBind(context, fulfill); - } - if (typeof reject === "function") { - this._rejectionHandler0 = util.contextBind(context, reject); - } - } else { - var base = index * 4 - 4; - this[base + 2] = promise; - this[base + 3] = receiver; - if (typeof fulfill === "function") { - this[base + 0] = - util.contextBind(context, fulfill); - } - if (typeof reject === "function") { - this[base + 1] = - util.contextBind(context, reject); - } - } - this._setLength(index + 1); - return index; -}; - -Promise.prototype._proxy = function (proxyable, arg) { - this._addCallbacks(undefined, undefined, arg, proxyable, null); -}; - -Promise.prototype._resolveCallback = function(value, shouldBind) { - if (((this._bitField & 117506048) !== 0)) return; - if (value === this) - return this._rejectCallback(makeSelfResolutionError(), false); - var maybePromise = tryConvertToPromise(value, this); - if (!(maybePromise instanceof Promise)) return this._fulfill(value); - - if (shouldBind) this._propagateFrom(maybePromise, 2); - - - var promise = maybePromise._target(); - - if (promise === this) { - this._reject(makeSelfResolutionError()); - return; - } - - var bitField = promise._bitField; - if (((bitField & 50397184) === 0)) { - var len = this._length(); - if (len > 0) promise._migrateCallback0(this); - for (var i = 1; i < len; ++i) { - promise._migrateCallbackAt(this, i); - } - this._setFollowing(); - this._setLength(0); - this._setFollowee(maybePromise); - } else if (((bitField & 33554432) !== 0)) { - this._fulfill(promise._value()); - } else if (((bitField & 16777216) !== 0)) { - this._reject(promise._reason()); - } else { - var reason = new CancellationError("late cancellation observer"); - promise._attachExtraTrace(reason); - this._reject(reason); - } -}; - -Promise.prototype._rejectCallback = -function(reason, synchronous, ignoreNonErrorWarnings) { - var trace = util.ensureErrorObject(reason); - var hasStack = trace === reason; - if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { - var message = "a promise was rejected with a non-error: " + - util.classString(reason); - this._warn(message, true); - } - this._attachExtraTrace(trace, synchronous ? hasStack : false); - this._reject(reason); -}; - -Promise.prototype._resolveFromExecutor = function (executor) { - if (executor === INTERNAL) return; - var promise = this; - this._captureStackTrace(); - this._pushContext(); - var synchronous = true; - var r = this._execute(executor, function(value) { - promise._resolveCallback(value); - }, function (reason) { - promise._rejectCallback(reason, synchronous); - }); - synchronous = false; - this._popContext(); - - if (r !== undefined) { - promise._rejectCallback(r, true); - } -}; - -Promise.prototype._settlePromiseFromHandler = function ( - handler, receiver, value, promise -) { - var bitField = promise._bitField; - if (((bitField & 65536) !== 0)) return; - promise._pushContext(); - var x; - if (receiver === APPLY) { - if (!value || typeof value.length !== "number") { - x = errorObj; - x.e = new TypeError("cannot .spread() a non-array: " + - util.classString(value)); - } else { - x = tryCatch(handler).apply(this._boundValue(), value); - } - } else { - x = tryCatch(handler).call(receiver, value); - } - var promiseCreated = promise._popContext(); - bitField = promise._bitField; - if (((bitField & 65536) !== 0)) return; - - if (x === NEXT_FILTER) { - promise._reject(value); - } else if (x === errorObj) { - promise._rejectCallback(x.e, false); - } else { - debug.checkForgottenReturns(x, promiseCreated, "", promise, this); - promise._resolveCallback(x); - } -}; - -Promise.prototype._target = function() { - var ret = this; - while (ret._isFollowing()) ret = ret._followee(); - return ret; -}; - -Promise.prototype._followee = function() { - return this._rejectionHandler0; -}; - -Promise.prototype._setFollowee = function(promise) { - this._rejectionHandler0 = promise; -}; - -Promise.prototype._settlePromise = function(promise, handler, receiver, value) { - var isPromise = promise instanceof Promise; - var bitField = this._bitField; - var asyncGuaranteed = ((bitField & 134217728) !== 0); - if (((bitField & 65536) !== 0)) { - if (isPromise) promise._invokeInternalOnCancel(); - - if (receiver instanceof PassThroughHandlerContext && - receiver.isFinallyHandler()) { - receiver.cancelPromise = promise; - if (tryCatch(handler).call(receiver, value) === errorObj) { - promise._reject(errorObj.e); - } - } else if (handler === reflectHandler) { - promise._fulfill(reflectHandler.call(receiver)); - } else if (receiver instanceof Proxyable) { - receiver._promiseCancelled(promise); - } else if (isPromise || promise instanceof PromiseArray) { - promise._cancel(); - } else { - receiver.cancel(); - } - } else if (typeof handler === "function") { - if (!isPromise) { - handler.call(receiver, value, promise); - } else { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (receiver instanceof Proxyable) { - if (!receiver._isResolved()) { - if (((bitField & 33554432) !== 0)) { - receiver._promiseFulfilled(value, promise); - } else { - receiver._promiseRejected(value, promise); - } - } - } else if (isPromise) { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - if (((bitField & 33554432) !== 0)) { - promise._fulfill(value); - } else { - promise._reject(value); - } - } -}; - -Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { - var handler = ctx.handler; - var promise = ctx.promise; - var receiver = ctx.receiver; - var value = ctx.value; - if (typeof handler === "function") { - if (!(promise instanceof Promise)) { - handler.call(receiver, value, promise); - } else { - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (promise instanceof Promise) { - promise._reject(value); - } -}; - -Promise.prototype._settlePromiseCtx = function(ctx) { - this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); -}; - -Promise.prototype._settlePromise0 = function(handler, value, bitField) { - var promise = this._promise0; - var receiver = this._receiverAt(0); - this._promise0 = undefined; - this._receiver0 = undefined; - this._settlePromise(promise, handler, receiver, value); -}; - -Promise.prototype._clearCallbackDataAtIndex = function(index) { - var base = index * 4 - 4; - this[base + 2] = - this[base + 3] = - this[base + 0] = - this[base + 1] = undefined; -}; - -Promise.prototype._fulfill = function (value) { - var bitField = this._bitField; - if (((bitField & 117506048) >>> 16)) return; - if (value === this) { - var err = makeSelfResolutionError(); - this._attachExtraTrace(err); - return this._reject(err); - } - this._setFulfilled(); - this._rejectionHandler0 = value; - - if ((bitField & 65535) > 0) { - if (((bitField & 134217728) !== 0)) { - this._settlePromises(); - } else { - async.settlePromises(this); - } - this._dereferenceTrace(); - } -}; - -Promise.prototype._reject = function (reason) { - var bitField = this._bitField; - if (((bitField & 117506048) >>> 16)) return; - this._setRejected(); - this._fulfillmentHandler0 = reason; - - if (this._isFinal()) { - return async.fatalError(reason, util.isNode); - } - - if ((bitField & 65535) > 0) { - async.settlePromises(this); - } else { - this._ensurePossibleRejectionHandled(); - } -}; - -Promise.prototype._fulfillPromises = function (len, value) { - for (var i = 1; i < len; i++) { - var handler = this._fulfillmentHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, value); - } -}; - -Promise.prototype._rejectPromises = function (len, reason) { - for (var i = 1; i < len; i++) { - var handler = this._rejectionHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, reason); - } -}; - -Promise.prototype._settlePromises = function () { - var bitField = this._bitField; - var len = (bitField & 65535); - - if (len > 0) { - if (((bitField & 16842752) !== 0)) { - var reason = this._fulfillmentHandler0; - this._settlePromise0(this._rejectionHandler0, reason, bitField); - this._rejectPromises(len, reason); - } else { - var value = this._rejectionHandler0; - this._settlePromise0(this._fulfillmentHandler0, value, bitField); - this._fulfillPromises(len, value); - } - this._setLength(0); - } - this._clearCancellationData(); -}; - -Promise.prototype._settledValue = function() { - var bitField = this._bitField; - if (((bitField & 33554432) !== 0)) { - return this._rejectionHandler0; - } else if (((bitField & 16777216) !== 0)) { - return this._fulfillmentHandler0; - } -}; - -if (typeof Symbol !== "undefined" && Symbol.toStringTag) { - es5.defineProperty(Promise.prototype, Symbol.toStringTag, { - get: function () { - return "Object"; - } - }); -} - -function deferResolve(v) {this.promise._resolveCallback(v);} -function deferReject(v) {this.promise._rejectCallback(v, false);} - -Promise.defer = Promise.pending = function() { - debug.deprecated("Promise.defer", "new Promise"); - var promise = new Promise(INTERNAL); - return { - promise: promise, - resolve: deferResolve, - reject: deferReject - }; -}; - -util.notEnumerableProp(Promise, - "_makeSelfResolutionError", - makeSelfResolutionError); - -_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, - debug); -_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); -_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug); -_dereq_("./direct_resolve")(Promise); -_dereq_("./synchronous_inspection")(Promise); -_dereq_("./join")( - Promise, PromiseArray, tryConvertToPromise, INTERNAL, async); -Promise.Promise = Promise; -Promise.version = "3.7.2"; -_dereq_('./call_get.js')(Promise); -_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); -_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); -_dereq_('./nodeify.js')(Promise); -_dereq_('./promisify.js')(Promise, INTERNAL); -_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); -_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); -_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); -_dereq_('./settle.js')(Promise, PromiseArray, debug); -_dereq_('./some.js')(Promise, PromiseArray, apiRejection); -_dereq_('./timers.js')(Promise, INTERNAL, debug); -_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); -_dereq_('./any.js')(Promise); -_dereq_('./each.js')(Promise, INTERNAL); -_dereq_('./filter.js')(Promise, INTERNAL); - - util.toFastProperties(Promise); - util.toFastProperties(Promise.prototype); - function fillTypes(value) { - var p = new Promise(INTERNAL); - p._fulfillmentHandler0 = value; - p._rejectionHandler0 = value; - p._promise0 = value; - p._receiver0 = value; - } - // Complete slack tracking, opt out of field-type tracking and - // stabilize map - fillTypes({a: 1}); - fillTypes({b: 2}); - fillTypes({c: 3}); - fillTypes(1); - fillTypes(function(){}); - fillTypes(undefined); - fillTypes(false); - fillTypes(new Promise(INTERNAL)); - debug.setBounds(Async.firstLineError, util.lastLineError); - return Promise; - -}; - -},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36,"async_hooks":undefined}],23:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL, tryConvertToPromise, - apiRejection, Proxyable) { -var util = _dereq_("./util"); -var isArray = util.isArray; - -function toResolutionValue(val) { - switch(val) { - case -2: return []; - case -3: return {}; - case -6: return new Map(); - } -} - -function PromiseArray(values) { - var promise = this._promise = new Promise(INTERNAL); - if (values instanceof Promise) { - promise._propagateFrom(values, 3); - values.suppressUnhandledRejections(); - } - promise._setOnCancel(this); - this._values = values; - this._length = 0; - this._totalResolved = 0; - this._init(undefined, -2); -} -util.inherits(PromiseArray, Proxyable); - -PromiseArray.prototype.length = function () { - return this._length; -}; - -PromiseArray.prototype.promise = function () { - return this._promise; -}; - -PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { - var values = tryConvertToPromise(this._values, this._promise); - if (values instanceof Promise) { - values = values._target(); - var bitField = values._bitField; - ; - this._values = values; - - if (((bitField & 50397184) === 0)) { - this._promise._setAsyncGuaranteed(); - return values._then( - init, - this._reject, - undefined, - this, - resolveValueIfEmpty - ); - } else if (((bitField & 33554432) !== 0)) { - values = values._value(); - } else if (((bitField & 16777216) !== 0)) { - return this._reject(values._reason()); - } else { - return this._cancel(); - } - } - values = util.asArray(values); - if (values === null) { - var err = apiRejection( - "expecting an array or an iterable object but got " + util.classString(values)).reason(); - this._promise._rejectCallback(err, false); - return; - } - - if (values.length === 0) { - if (resolveValueIfEmpty === -5) { - this._resolveEmptyArray(); - } - else { - this._resolve(toResolutionValue(resolveValueIfEmpty)); - } - return; - } - this._iterate(values); -}; - -PromiseArray.prototype._iterate = function(values) { - var len = this.getActualLength(values.length); - this._length = len; - this._values = this.shouldCopyValues() ? new Array(len) : this._values; - var result = this._promise; - var isResolved = false; - var bitField = null; - for (var i = 0; i < len; ++i) { - var maybePromise = tryConvertToPromise(values[i], result); - - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - bitField = maybePromise._bitField; - } else { - bitField = null; - } - - if (isResolved) { - if (bitField !== null) { - maybePromise.suppressUnhandledRejections(); - } - } else if (bitField !== null) { - if (((bitField & 50397184) === 0)) { - maybePromise._proxy(this, i); - this._values[i] = maybePromise; - } else if (((bitField & 33554432) !== 0)) { - isResolved = this._promiseFulfilled(maybePromise._value(), i); - } else if (((bitField & 16777216) !== 0)) { - isResolved = this._promiseRejected(maybePromise._reason(), i); - } else { - isResolved = this._promiseCancelled(i); - } - } else { - isResolved = this._promiseFulfilled(maybePromise, i); - } - } - if (!isResolved) result._setAsyncGuaranteed(); -}; - -PromiseArray.prototype._isResolved = function () { - return this._values === null; -}; - -PromiseArray.prototype._resolve = function (value) { - this._values = null; - this._promise._fulfill(value); -}; - -PromiseArray.prototype._cancel = function() { - if (this._isResolved() || !this._promise._isCancellable()) return; - this._values = null; - this._promise._cancel(); -}; - -PromiseArray.prototype._reject = function (reason) { - this._values = null; - this._promise._rejectCallback(reason, false); -}; - -PromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; - } - return false; -}; - -PromiseArray.prototype._promiseCancelled = function() { - this._cancel(); - return true; -}; - -PromiseArray.prototype._promiseRejected = function (reason) { - this._totalResolved++; - this._reject(reason); - return true; -}; - -PromiseArray.prototype._resultCancelled = function() { - if (this._isResolved()) return; - var values = this._values; - this._cancel(); - if (values instanceof Promise) { - values.cancel(); - } else { - for (var i = 0; i < values.length; ++i) { - if (values[i] instanceof Promise) { - values[i].cancel(); - } - } - } -}; - -PromiseArray.prototype.shouldCopyValues = function () { - return true; -}; - -PromiseArray.prototype.getActualLength = function (len) { - return len; -}; - -return PromiseArray; -}; - -},{"./util":36}],24:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var THIS = {}; -var util = _dereq_("./util"); -var nodebackForPromise = _dereq_("./nodeback"); -var withAppended = util.withAppended; -var maybeWrapAsError = util.maybeWrapAsError; -var canEvaluate = util.canEvaluate; -var TypeError = _dereq_("./errors").TypeError; -var defaultSuffix = "Async"; -var defaultPromisified = {__isPromisified__: true}; -var noCopyProps = [ - "arity", "length", - "name", - "arguments", - "caller", - "callee", - "prototype", - "__isPromisified__" -]; -var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); - -var defaultFilter = function(name) { - return util.isIdentifier(name) && - name.charAt(0) !== "_" && - name !== "constructor"; -}; - -function propsFilter(key) { - return !noCopyPropsPattern.test(key); -} - -function isPromisified(fn) { - try { - return fn.__isPromisified__ === true; - } - catch (e) { - return false; - } -} - -function hasPromisified(obj, key, suffix) { - var val = util.getDataPropertyOrDefault(obj, key + suffix, - defaultPromisified); - return val ? isPromisified(val) : false; -} -function checkValid(ret, suffix, suffixRegexp) { - for (var i = 0; i < ret.length; i += 2) { - var key = ret[i]; - if (suffixRegexp.test(key)) { - var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); - for (var j = 0; j < ret.length; j += 2) { - if (ret[j] === keyWithoutAsyncSuffix) { - throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a" - .replace("%s", suffix)); - } - } - } - } -} - -function promisifiableMethods(obj, suffix, suffixRegexp, filter) { - var keys = util.inheritedDataKeys(obj); - var ret = []; - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var value = obj[key]; - var passesDefaultFilter = filter === defaultFilter - ? true : defaultFilter(key, value, obj); - if (typeof value === "function" && - !isPromisified(value) && - !hasPromisified(obj, key, suffix) && - filter(key, value, obj, passesDefaultFilter)) { - ret.push(key, value); - } - } - checkValid(ret, suffix, suffixRegexp); - return ret; -} - -var escapeIdentRegex = function(str) { - return str.replace(/([$])/, "\\$"); -}; - -var makeNodePromisifiedEval; -if (!true) { -var switchCaseArgumentOrder = function(likelyArgumentCount) { - var ret = [likelyArgumentCount]; - var min = Math.max(0, likelyArgumentCount - 1 - 3); - for(var i = likelyArgumentCount - 1; i >= min; --i) { - ret.push(i); - } - for(var i = likelyArgumentCount + 1; i <= 3; ++i) { - ret.push(i); - } - return ret; -}; - -var argumentSequence = function(argumentCount) { - return util.filledRange(argumentCount, "_arg", ""); -}; - -var parameterDeclaration = function(parameterCount) { - return util.filledRange( - Math.max(parameterCount, 3), "_arg", ""); -}; - -var parameterCount = function(fn) { - if (typeof fn.length === "number") { - return Math.max(Math.min(fn.length, 1023 + 1), 0); - } - return 0; -}; - -makeNodePromisifiedEval = -function(callback, receiver, originalName, fn, _, multiArgs) { - var newParameterCount = Math.max(0, parameterCount(fn) - 1); - var argumentOrder = switchCaseArgumentOrder(newParameterCount); - var shouldProxyThis = typeof callback === "string" || receiver === THIS; - - function generateCallForArgumentCount(count) { - var args = argumentSequence(count).join(", "); - var comma = count > 0 ? ", " : ""; - var ret; - if (shouldProxyThis) { - ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; - } else { - ret = receiver === undefined - ? "ret = callback({{args}}, nodeback); break;\n" - : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; - } - return ret.replace("{{args}}", args).replace(", ", comma); - } - - function generateArgumentSwitchCase() { - var ret = ""; - for (var i = 0; i < argumentOrder.length; ++i) { - ret += "case " + argumentOrder[i] +":" + - generateCallForArgumentCount(argumentOrder[i]); - } - - ret += " \n\ - default: \n\ - var args = new Array(len + 1); \n\ - var i = 0; \n\ - for (var i = 0; i < len; ++i) { \n\ - args[i] = arguments[i]; \n\ - } \n\ - args[i] = nodeback; \n\ - [CodeForCall] \n\ - break; \n\ - ".replace("[CodeForCall]", (shouldProxyThis - ? "ret = callback.apply(this, args);\n" - : "ret = callback.apply(receiver, args);\n")); - return ret; - } - - var getFunctionCode = typeof callback === "string" - ? ("this != null ? this['"+callback+"'] : fn") - : "fn"; - var body = "'use strict'; \n\ - var ret = function (Parameters) { \n\ - 'use strict'; \n\ - var len = arguments.length; \n\ - var promise = new Promise(INTERNAL); \n\ - promise._captureStackTrace(); \n\ - var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\ - var ret; \n\ - var callback = tryCatch([GetFunctionCode]); \n\ - switch(len) { \n\ - [CodeForSwitchCase] \n\ - } \n\ - if (ret === errorObj) { \n\ - promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ - } \n\ - if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ - return promise; \n\ - }; \n\ - notEnumerableProp(ret, '__isPromisified__', true); \n\ - return ret; \n\ - ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) - .replace("[GetFunctionCode]", getFunctionCode); - body = body.replace("Parameters", parameterDeclaration(newParameterCount)); - return new Function("Promise", - "fn", - "receiver", - "withAppended", - "maybeWrapAsError", - "nodebackForPromise", - "tryCatch", - "errorObj", - "notEnumerableProp", - "INTERNAL", - body)( - Promise, - fn, - receiver, - withAppended, - maybeWrapAsError, - nodebackForPromise, - util.tryCatch, - util.errorObj, - util.notEnumerableProp, - INTERNAL); -}; -} - -function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { - var defaultThis = (function() {return this;})(); - var method = callback; - if (typeof method === "string") { - callback = fn; - } - function promisified() { - var _receiver = receiver; - if (receiver === THIS) _receiver = this; - var promise = new Promise(INTERNAL); - promise._captureStackTrace(); - var cb = typeof method === "string" && this !== defaultThis - ? this[method] : callback; - var fn = nodebackForPromise(promise, multiArgs); - try { - cb.apply(_receiver, withAppended(arguments, fn)); - } catch(e) { - promise._rejectCallback(maybeWrapAsError(e), true, true); - } - if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); - return promise; - } - util.notEnumerableProp(promisified, "__isPromisified__", true); - return promisified; -} - -var makeNodePromisified = canEvaluate - ? makeNodePromisifiedEval - : makeNodePromisifiedClosure; - -function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { - var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); - var methods = - promisifiableMethods(obj, suffix, suffixRegexp, filter); - - for (var i = 0, len = methods.length; i < len; i+= 2) { - var key = methods[i]; - var fn = methods[i+1]; - var promisifiedKey = key + suffix; - if (promisifier === makeNodePromisified) { - obj[promisifiedKey] = - makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); - } else { - var promisified = promisifier(fn, function() { - return makeNodePromisified(key, THIS, key, - fn, suffix, multiArgs); - }); - util.notEnumerableProp(promisified, "__isPromisified__", true); - obj[promisifiedKey] = promisified; - } - } - util.toFastProperties(obj); - return obj; -} - -function promisify(callback, receiver, multiArgs) { - return makeNodePromisified(callback, receiver, undefined, - callback, null, multiArgs); -} - -Promise.promisify = function (fn, options) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - if (isPromisified(fn)) { - return fn; - } - options = Object(options); - var receiver = options.context === undefined ? THIS : options.context; - var multiArgs = !!options.multiArgs; - var ret = promisify(fn, receiver, multiArgs); - util.copyDescriptors(fn, ret, propsFilter); - return ret; -}; - -Promise.promisifyAll = function (target, options) { - if (typeof target !== "function" && typeof target !== "object") { - throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - options = Object(options); - var multiArgs = !!options.multiArgs; - var suffix = options.suffix; - if (typeof suffix !== "string") suffix = defaultSuffix; - var filter = options.filter; - if (typeof filter !== "function") filter = defaultFilter; - var promisifier = options.promisifier; - if (typeof promisifier !== "function") promisifier = makeNodePromisified; - - if (!util.isIdentifier(suffix)) { - throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - - var keys = util.inheritedDataKeys(target); - for (var i = 0; i < keys.length; ++i) { - var value = target[keys[i]]; - if (keys[i] !== "constructor" && - util.isClass(value)) { - promisifyAll(value.prototype, suffix, filter, promisifier, - multiArgs); - promisifyAll(value, suffix, filter, promisifier, multiArgs); - } - } - - return promisifyAll(target, suffix, filter, promisifier, multiArgs); -}; -}; - - -},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function( - Promise, PromiseArray, tryConvertToPromise, apiRejection) { -var util = _dereq_("./util"); -var isObject = util.isObject; -var es5 = _dereq_("./es5"); -var Es6Map; -if (typeof Map === "function") Es6Map = Map; - -var mapToEntries = (function() { - var index = 0; - var size = 0; - - function extractEntry(value, key) { - this[index] = value; - this[index + size] = key; - index++; - } - - return function mapToEntries(map) { - size = map.size; - index = 0; - var ret = new Array(map.size * 2); - map.forEach(extractEntry, ret); - return ret; - }; -})(); - -var entriesToMap = function(entries) { - var ret = new Es6Map(); - var length = entries.length / 2 | 0; - for (var i = 0; i < length; ++i) { - var key = entries[length + i]; - var value = entries[i]; - ret.set(key, value); - } - return ret; -}; - -function PropertiesPromiseArray(obj) { - var isMap = false; - var entries; - if (Es6Map !== undefined && obj instanceof Es6Map) { - entries = mapToEntries(obj); - isMap = true; - } else { - var keys = es5.keys(obj); - var len = keys.length; - entries = new Array(len * 2); - for (var i = 0; i < len; ++i) { - var key = keys[i]; - entries[i] = obj[key]; - entries[i + len] = key; - } - } - this.constructor$(entries); - this._isMap = isMap; - this._init$(undefined, isMap ? -6 : -3); -} -util.inherits(PropertiesPromiseArray, PromiseArray); - -PropertiesPromiseArray.prototype._init = function () {}; - -PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - var val; - if (this._isMap) { - val = entriesToMap(this._values); - } else { - val = {}; - var keyOffset = this.length(); - for (var i = 0, len = this.length(); i < len; ++i) { - val[this._values[i + keyOffset]] = this._values[i]; - } - } - this._resolve(val); - return true; - } - return false; -}; - -PropertiesPromiseArray.prototype.shouldCopyValues = function () { - return false; -}; - -PropertiesPromiseArray.prototype.getActualLength = function (len) { - return len >> 1; -}; - -function props(promises) { - var ret; - var castValue = tryConvertToPromise(promises); - - if (!isObject(castValue)) { - return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } else if (castValue instanceof Promise) { - ret = castValue._then( - Promise.props, undefined, undefined, undefined, undefined); - } else { - ret = new PropertiesPromiseArray(castValue).promise(); - } - - if (castValue instanceof Promise) { - ret._propagateFrom(castValue, 2); - } - return ret; -} - -Promise.prototype.props = function () { - return props(this); -}; - -Promise.props = function (promises) { - return props(promises); -}; -}; - -},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){ -"use strict"; -function arrayMove(src, srcIndex, dst, dstIndex, len) { - for (var j = 0; j < len; ++j) { - dst[j + dstIndex] = src[j + srcIndex]; - src[j + srcIndex] = void 0; - } -} - -function Queue(capacity) { - this._capacity = capacity; - this._length = 0; - this._front = 0; -} - -Queue.prototype._willBeOverCapacity = function (size) { - return this._capacity < size; -}; - -Queue.prototype._pushOne = function (arg) { - var length = this.length(); - this._checkCapacity(length + 1); - var i = (this._front + length) & (this._capacity - 1); - this[i] = arg; - this._length = length + 1; -}; - -Queue.prototype.push = function (fn, receiver, arg) { - var length = this.length() + 3; - if (this._willBeOverCapacity(length)) { - this._pushOne(fn); - this._pushOne(receiver); - this._pushOne(arg); - return; - } - var j = this._front + length - 3; - this._checkCapacity(length); - var wrapMask = this._capacity - 1; - this[(j + 0) & wrapMask] = fn; - this[(j + 1) & wrapMask] = receiver; - this[(j + 2) & wrapMask] = arg; - this._length = length; -}; - -Queue.prototype.shift = function () { - var front = this._front, - ret = this[front]; - - this[front] = undefined; - this._front = (front + 1) & (this._capacity - 1); - this._length--; - return ret; -}; - -Queue.prototype.length = function () { - return this._length; -}; - -Queue.prototype._checkCapacity = function (size) { - if (this._capacity < size) { - this._resizeTo(this._capacity << 1); - } -}; - -Queue.prototype._resizeTo = function (capacity) { - var oldCapacity = this._capacity; - this._capacity = capacity; - var front = this._front; - var length = this._length; - var moveItemsCount = (front + length) & (oldCapacity - 1); - arrayMove(this, 0, this, oldCapacity, moveItemsCount); -}; - -module.exports = Queue; - -},{}],27:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function( - Promise, INTERNAL, tryConvertToPromise, apiRejection) { -var util = _dereq_("./util"); - -var raceLater = function (promise) { - return promise.then(function(array) { - return race(array, promise); - }); -}; - -function race(promises, parent) { - var maybePromise = tryConvertToPromise(promises); - - if (maybePromise instanceof Promise) { - return raceLater(maybePromise); - } else { - promises = util.asArray(promises); - if (promises === null) - return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); - } - - var ret = new Promise(INTERNAL); - if (parent !== undefined) { - ret._propagateFrom(parent, 3); - } - var fulfill = ret._fulfill; - var reject = ret._reject; - for (var i = 0, len = promises.length; i < len; ++i) { - var val = promises[i]; - - if (val === undefined && !(i in promises)) { - continue; - } - - Promise.cast(val)._then(fulfill, reject, undefined, ret, null); - } - return ret; -} - -Promise.race = function (promises) { - return race(promises, undefined); -}; - -Promise.prototype.race = function () { - return race(this, undefined); -}; - -}; - -},{"./util":36}],28:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; - -function ReductionPromiseArray(promises, fn, initialValue, _each) { - this.constructor$(promises); - var context = Promise._getContext(); - this._fn = util.contextBind(context, fn); - if (initialValue !== undefined) { - initialValue = Promise.resolve(initialValue); - initialValue._attachCancellationCallback(this); - } - this._initialValue = initialValue; - this._currentCancellable = null; - if(_each === INTERNAL) { - this._eachValues = Array(this._length); - } else if (_each === 0) { - this._eachValues = null; - } else { - this._eachValues = undefined; - } - this._promise._captureStackTrace(); - this._init$(undefined, -5); -} -util.inherits(ReductionPromiseArray, PromiseArray); - -ReductionPromiseArray.prototype._gotAccum = function(accum) { - if (this._eachValues !== undefined && - this._eachValues !== null && - accum !== INTERNAL) { - this._eachValues.push(accum); - } -}; - -ReductionPromiseArray.prototype._eachComplete = function(value) { - if (this._eachValues !== null) { - this._eachValues.push(value); - } - return this._eachValues; -}; - -ReductionPromiseArray.prototype._init = function() {}; - -ReductionPromiseArray.prototype._resolveEmptyArray = function() { - this._resolve(this._eachValues !== undefined ? this._eachValues - : this._initialValue); -}; - -ReductionPromiseArray.prototype.shouldCopyValues = function () { - return false; -}; - -ReductionPromiseArray.prototype._resolve = function(value) { - this._promise._resolveCallback(value); - this._values = null; -}; - -ReductionPromiseArray.prototype._resultCancelled = function(sender) { - if (sender === this._initialValue) return this._cancel(); - if (this._isResolved()) return; - this._resultCancelled$(); - if (this._currentCancellable instanceof Promise) { - this._currentCancellable.cancel(); - } - if (this._initialValue instanceof Promise) { - this._initialValue.cancel(); - } -}; - -ReductionPromiseArray.prototype._iterate = function (values) { - this._values = values; - var value; - var i; - var length = values.length; - if (this._initialValue !== undefined) { - value = this._initialValue; - i = 0; - } else { - value = Promise.resolve(values[0]); - i = 1; - } - - this._currentCancellable = value; - - for (var j = i; j < length; ++j) { - var maybePromise = values[j]; - if (maybePromise instanceof Promise) { - maybePromise.suppressUnhandledRejections(); - } - } - - if (!value.isRejected()) { - for (; i < length; ++i) { - var ctx = { - accum: null, - value: values[i], - index: i, - length: length, - array: this - }; - - value = value._then(gotAccum, undefined, undefined, ctx, undefined); - - if ((i & 127) === 0) { - value._setNoAsyncGuarantee(); - } - } - } - - if (this._eachValues !== undefined) { - value = value - ._then(this._eachComplete, undefined, undefined, this, undefined); - } - value._then(completed, completed, undefined, value, this); -}; - -Promise.prototype.reduce = function (fn, initialValue) { - return reduce(this, fn, initialValue, null); -}; - -Promise.reduce = function (promises, fn, initialValue, _each) { - return reduce(promises, fn, initialValue, _each); -}; - -function completed(valueOrReason, array) { - if (this.isFulfilled()) { - array._resolve(valueOrReason); - } else { - array._reject(valueOrReason); - } -} - -function reduce(promises, fn, initialValue, _each) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var array = new ReductionPromiseArray(promises, fn, initialValue, _each); - return array.promise(); -} - -function gotAccum(accum) { - this.accum = accum; - this.array._gotAccum(accum); - var value = tryConvertToPromise(this.value, this.array._promise); - if (value instanceof Promise) { - this.array._currentCancellable = value; - return value._then(gotValue, undefined, undefined, this, undefined); - } else { - return gotValue.call(this, value); - } -} - -function gotValue(value) { - var array = this.array; - var promise = array._promise; - var fn = tryCatch(array._fn); - promise._pushContext(); - var ret; - if (array._eachValues !== undefined) { - ret = fn.call(promise._boundValue(), value, this.index, this.length); - } else { - ret = fn.call(promise._boundValue(), - this.accum, value, this.index, this.length); - } - if (ret instanceof Promise) { - array._currentCancellable = ret; - } - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", - promise - ); - return ret; -} -}; - -},{"./util":36}],29:[function(_dereq_,module,exports){ -"use strict"; -var util = _dereq_("./util"); -var schedule; -var noAsyncScheduler = function() { - throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); -}; -var NativePromise = util.getNativePromise(); -if (util.isNode && typeof MutationObserver === "undefined") { - var GlobalSetImmediate = global.setImmediate; - var ProcessNextTick = process.nextTick; - schedule = util.isRecentNode - ? function(fn) { GlobalSetImmediate.call(global, fn); } - : function(fn) { ProcessNextTick.call(process, fn); }; -} else if (typeof NativePromise === "function" && - typeof NativePromise.resolve === "function") { - var nativePromise = NativePromise.resolve(); - schedule = function(fn) { - nativePromise.then(fn); - }; -} else if ((typeof MutationObserver !== "undefined") && - !(typeof window !== "undefined" && - window.navigator && - (window.navigator.standalone || window.cordova)) && - ("classList" in document.documentElement)) { - schedule = (function() { - var div = document.createElement("div"); - var opts = {attributes: true}; - var toggleScheduled = false; - var div2 = document.createElement("div"); - var o2 = new MutationObserver(function() { - div.classList.toggle("foo"); - toggleScheduled = false; - }); - o2.observe(div2, opts); - - var scheduleToggle = function() { - if (toggleScheduled) return; - toggleScheduled = true; - div2.classList.toggle("foo"); - }; - - return function schedule(fn) { - var o = new MutationObserver(function() { - o.disconnect(); - fn(); - }); - o.observe(div, opts); - scheduleToggle(); - }; - })(); -} else if (typeof setImmediate !== "undefined") { - schedule = function (fn) { - setImmediate(fn); - }; -} else if (typeof setTimeout !== "undefined") { - schedule = function (fn) { - setTimeout(fn, 0); - }; -} else { - schedule = noAsyncScheduler; -} -module.exports = schedule; - -},{"./util":36}],30:[function(_dereq_,module,exports){ -"use strict"; -module.exports = - function(Promise, PromiseArray, debug) { -var PromiseInspection = Promise.PromiseInspection; -var util = _dereq_("./util"); - -function SettledPromiseArray(values) { - this.constructor$(values); -} -util.inherits(SettledPromiseArray, PromiseArray); - -SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { - this._values[index] = inspection; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; - } - return false; -}; - -SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { - var ret = new PromiseInspection(); - ret._bitField = 33554432; - ret._settledValueField = value; - return this._promiseResolved(index, ret); -}; -SettledPromiseArray.prototype._promiseRejected = function (reason, index) { - var ret = new PromiseInspection(); - ret._bitField = 16777216; - ret._settledValueField = reason; - return this._promiseResolved(index, ret); -}; - -Promise.settle = function (promises) { - debug.deprecated(".settle()", ".reflect()"); - return new SettledPromiseArray(promises).promise(); -}; - -Promise.allSettled = function (promises) { - return new SettledPromiseArray(promises).promise(); -}; - -Promise.prototype.settle = function () { - return Promise.settle(this); -}; -}; - -},{"./util":36}],31:[function(_dereq_,module,exports){ -"use strict"; -module.exports = -function(Promise, PromiseArray, apiRejection) { -var util = _dereq_("./util"); -var RangeError = _dereq_("./errors").RangeError; -var AggregateError = _dereq_("./errors").AggregateError; -var isArray = util.isArray; -var CANCELLATION = {}; - - -function SomePromiseArray(values) { - this.constructor$(values); - this._howMany = 0; - this._unwrap = false; - this._initialized = false; -} -util.inherits(SomePromiseArray, PromiseArray); - -SomePromiseArray.prototype._init = function () { - if (!this._initialized) { - return; - } - if (this._howMany === 0) { - this._resolve([]); - return; - } - this._init$(undefined, -5); - var isArrayResolved = isArray(this._values); - if (!this._isResolved() && - isArrayResolved && - this._howMany > this._canPossiblyFulfill()) { - this._reject(this._getRangeError(this.length())); - } -}; - -SomePromiseArray.prototype.init = function () { - this._initialized = true; - this._init(); -}; - -SomePromiseArray.prototype.setUnwrap = function () { - this._unwrap = true; -}; - -SomePromiseArray.prototype.howMany = function () { - return this._howMany; -}; - -SomePromiseArray.prototype.setHowMany = function (count) { - this._howMany = count; -}; - -SomePromiseArray.prototype._promiseFulfilled = function (value) { - this._addFulfilled(value); - if (this._fulfilled() === this.howMany()) { - this._values.length = this.howMany(); - if (this.howMany() === 1 && this._unwrap) { - this._resolve(this._values[0]); - } else { - this._resolve(this._values); - } - return true; - } - return false; - -}; -SomePromiseArray.prototype._promiseRejected = function (reason) { - this._addRejected(reason); - return this._checkOutcome(); -}; - -SomePromiseArray.prototype._promiseCancelled = function () { - if (this._values instanceof Promise || this._values == null) { - return this._cancel(); - } - this._addRejected(CANCELLATION); - return this._checkOutcome(); -}; - -SomePromiseArray.prototype._checkOutcome = function() { - if (this.howMany() > this._canPossiblyFulfill()) { - var e = new AggregateError(); - for (var i = this.length(); i < this._values.length; ++i) { - if (this._values[i] !== CANCELLATION) { - e.push(this._values[i]); - } - } - if (e.length > 0) { - this._reject(e); - } else { - this._cancel(); - } - return true; - } - return false; -}; - -SomePromiseArray.prototype._fulfilled = function () { - return this._totalResolved; -}; - -SomePromiseArray.prototype._rejected = function () { - return this._values.length - this.length(); -}; - -SomePromiseArray.prototype._addRejected = function (reason) { - this._values.push(reason); -}; - -SomePromiseArray.prototype._addFulfilled = function (value) { - this._values[this._totalResolved++] = value; -}; - -SomePromiseArray.prototype._canPossiblyFulfill = function () { - return this.length() - this._rejected(); -}; - -SomePromiseArray.prototype._getRangeError = function (count) { - var message = "Input array must contain at least " + - this._howMany + " items but contains only " + count + " items"; - return new RangeError(message); -}; - -SomePromiseArray.prototype._resolveEmptyArray = function () { - this._reject(this._getRangeError(0)); -}; - -function some(promises, howMany) { - if ((howMany | 0) !== howMany || howMany < 0) { - return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var ret = new SomePromiseArray(promises); - var promise = ret.promise(); - ret.setHowMany(howMany); - ret.init(); - return promise; -} - -Promise.some = function (promises, howMany) { - return some(promises, howMany); -}; - -Promise.prototype.some = function (howMany) { - return some(this, howMany); -}; - -Promise._SomePromiseArray = SomePromiseArray; -}; - -},{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise) { -function PromiseInspection(promise) { - if (promise !== undefined) { - promise = promise._target(); - this._bitField = promise._bitField; - this._settledValueField = promise._isFateSealed() - ? promise._settledValue() : undefined; - } - else { - this._bitField = 0; - this._settledValueField = undefined; - } -} - -PromiseInspection.prototype._settledValue = function() { - return this._settledValueField; -}; - -var value = PromiseInspection.prototype.value = function () { - if (!this.isFulfilled()) { - throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - return this._settledValue(); -}; - -var reason = PromiseInspection.prototype.error = -PromiseInspection.prototype.reason = function () { - if (!this.isRejected()) { - throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - return this._settledValue(); -}; - -var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { - return (this._bitField & 33554432) !== 0; -}; - -var isRejected = PromiseInspection.prototype.isRejected = function () { - return (this._bitField & 16777216) !== 0; -}; - -var isPending = PromiseInspection.prototype.isPending = function () { - return (this._bitField & 50397184) === 0; -}; - -var isResolved = PromiseInspection.prototype.isResolved = function () { - return (this._bitField & 50331648) !== 0; -}; - -PromiseInspection.prototype.isCancelled = function() { - return (this._bitField & 8454144) !== 0; -}; - -Promise.prototype.__isCancelled = function() { - return (this._bitField & 65536) === 65536; -}; - -Promise.prototype._isCancelled = function() { - return this._target().__isCancelled(); -}; - -Promise.prototype.isCancelled = function() { - return (this._target()._bitField & 8454144) !== 0; -}; - -Promise.prototype.isPending = function() { - return isPending.call(this._target()); -}; - -Promise.prototype.isRejected = function() { - return isRejected.call(this._target()); -}; - -Promise.prototype.isFulfilled = function() { - return isFulfilled.call(this._target()); -}; - -Promise.prototype.isResolved = function() { - return isResolved.call(this._target()); -}; - -Promise.prototype.value = function() { - return value.call(this._target()); -}; - -Promise.prototype.reason = function() { - var target = this._target(); - target._unsetRejectionIsUnhandled(); - return reason.call(target); -}; - -Promise.prototype._value = function() { - return this._settledValue(); -}; - -Promise.prototype._reason = function() { - this._unsetRejectionIsUnhandled(); - return this._settledValue(); -}; - -Promise.PromiseInspection = PromiseInspection; -}; - -},{}],33:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var util = _dereq_("./util"); -var errorObj = util.errorObj; -var isObject = util.isObject; - -function tryConvertToPromise(obj, context) { - if (isObject(obj)) { - if (obj instanceof Promise) return obj; - var then = getThen(obj); - if (then === errorObj) { - if (context) context._pushContext(); - var ret = Promise.reject(then.e); - if (context) context._popContext(); - return ret; - } else if (typeof then === "function") { - if (isAnyBluebirdPromise(obj)) { - var ret = new Promise(INTERNAL); - obj._then( - ret._fulfill, - ret._reject, - undefined, - ret, - null - ); - return ret; - } - return doThenable(obj, then, context); - } - } - return obj; -} - -function doGetThen(obj) { - return obj.then; -} - -function getThen(obj) { - try { - return doGetThen(obj); - } catch (e) { - errorObj.e = e; - return errorObj; - } -} - -var hasProp = {}.hasOwnProperty; -function isAnyBluebirdPromise(obj) { - try { - return hasProp.call(obj, "_promise0"); - } catch (e) { - return false; - } -} - -function doThenable(x, then, context) { - var promise = new Promise(INTERNAL); - var ret = promise; - if (context) context._pushContext(); - promise._captureStackTrace(); - if (context) context._popContext(); - var synchronous = true; - var result = util.tryCatch(then).call(x, resolve, reject); - synchronous = false; - - if (promise && result === errorObj) { - promise._rejectCallback(result.e, true, true); - promise = null; - } - - function resolve(value) { - if (!promise) return; - promise._resolveCallback(value); - promise = null; - } - - function reject(reason) { - if (!promise) return; - promise._rejectCallback(reason, synchronous, true); - promise = null; - } - return ret; -} - -return tryConvertToPromise; -}; - -},{"./util":36}],34:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL, debug) { -var util = _dereq_("./util"); -var TimeoutError = Promise.TimeoutError; - -function HandleWrapper(handle) { - this.handle = handle; -} - -HandleWrapper.prototype._resultCancelled = function() { - clearTimeout(this.handle); -}; - -var afterValue = function(value) { return delay(+this).thenReturn(value); }; -var delay = Promise.delay = function (ms, value) { - var ret; - var handle; - if (value !== undefined) { - ret = Promise.resolve(value) - ._then(afterValue, null, null, ms, undefined); - if (debug.cancellation() && value instanceof Promise) { - ret._setOnCancel(value); - } - } else { - ret = new Promise(INTERNAL); - handle = setTimeout(function() { ret._fulfill(); }, +ms); - if (debug.cancellation()) { - ret._setOnCancel(new HandleWrapper(handle)); - } - ret._captureStackTrace(); - } - ret._setAsyncGuaranteed(); - return ret; -}; - -Promise.prototype.delay = function (ms) { - return delay(ms, this); -}; - -var afterTimeout = function (promise, message, parent) { - var err; - if (typeof message !== "string") { - if (message instanceof Error) { - err = message; - } else { - err = new TimeoutError("operation timed out"); - } - } else { - err = new TimeoutError(message); - } - util.markAsOriginatingFromRejection(err); - promise._attachExtraTrace(err); - promise._reject(err); - - if (parent != null) { - parent.cancel(); - } -}; - -function successClear(value) { - clearTimeout(this.handle); - return value; -} - -function failureClear(reason) { - clearTimeout(this.handle); - throw reason; -} - -Promise.prototype.timeout = function (ms, message) { - ms = +ms; - var ret, parent; - - var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { - if (ret.isPending()) { - afterTimeout(ret, message, parent); - } - }, ms)); - - if (debug.cancellation()) { - parent = this.then(); - ret = parent._then(successClear, failureClear, - undefined, handleWrapper, undefined); - ret._setOnCancel(handleWrapper); - } else { - ret = this._then(successClear, failureClear, - undefined, handleWrapper, undefined); - } - - return ret; -}; - -}; - -},{"./util":36}],35:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function (Promise, apiRejection, tryConvertToPromise, - createContext, INTERNAL, debug) { - var util = _dereq_("./util"); - var TypeError = _dereq_("./errors").TypeError; - var inherits = _dereq_("./util").inherits; - var errorObj = util.errorObj; - var tryCatch = util.tryCatch; - var NULL = {}; - - function thrower(e) { - setTimeout(function(){throw e;}, 0); - } - - function castPreservingDisposable(thenable) { - var maybePromise = tryConvertToPromise(thenable); - if (maybePromise !== thenable && - typeof thenable._isDisposable === "function" && - typeof thenable._getDisposer === "function" && - thenable._isDisposable()) { - maybePromise._setDisposable(thenable._getDisposer()); - } - return maybePromise; - } - function dispose(resources, inspection) { - var i = 0; - var len = resources.length; - var ret = new Promise(INTERNAL); - function iterator() { - if (i >= len) return ret._fulfill(); - var maybePromise = castPreservingDisposable(resources[i++]); - if (maybePromise instanceof Promise && - maybePromise._isDisposable()) { - try { - maybePromise = tryConvertToPromise( - maybePromise._getDisposer().tryDispose(inspection), - resources.promise); - } catch (e) { - return thrower(e); - } - if (maybePromise instanceof Promise) { - return maybePromise._then(iterator, thrower, - null, null, null); - } - } - iterator(); - } - iterator(); - return ret; - } - - function Disposer(data, promise, context) { - this._data = data; - this._promise = promise; - this._context = context; - } - - Disposer.prototype.data = function () { - return this._data; - }; - - Disposer.prototype.promise = function () { - return this._promise; - }; - - Disposer.prototype.resource = function () { - if (this.promise().isFulfilled()) { - return this.promise().value(); - } - return NULL; - }; - - Disposer.prototype.tryDispose = function(inspection) { - var resource = this.resource(); - var context = this._context; - if (context !== undefined) context._pushContext(); - var ret = resource !== NULL - ? this.doDispose(resource, inspection) : null; - if (context !== undefined) context._popContext(); - this._promise._unsetDisposable(); - this._data = null; - return ret; - }; - - Disposer.isDisposer = function (d) { - return (d != null && - typeof d.resource === "function" && - typeof d.tryDispose === "function"); - }; - - function FunctionDisposer(fn, promise, context) { - this.constructor$(fn, promise, context); - } - inherits(FunctionDisposer, Disposer); - - FunctionDisposer.prototype.doDispose = function (resource, inspection) { - var fn = this.data(); - return fn.call(resource, resource, inspection); - }; - - function maybeUnwrapDisposer(value) { - if (Disposer.isDisposer(value)) { - this.resources[this.index]._setDisposable(value); - return value.promise(); - } - return value; - } - - function ResourceList(length) { - this.length = length; - this.promise = null; - this[length-1] = null; - } - - ResourceList.prototype._resultCancelled = function() { - var len = this.length; - for (var i = 0; i < len; ++i) { - var item = this[i]; - if (item instanceof Promise) { - item.cancel(); - } - } - }; - - Promise.using = function () { - var len = arguments.length; - if (len < 2) return apiRejection( - "you must pass at least 2 arguments to Promise.using"); - var fn = arguments[len - 1]; - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var input; - var spreadArgs = true; - if (len === 2 && Array.isArray(arguments[0])) { - input = arguments[0]; - len = input.length; - spreadArgs = false; - } else { - input = arguments; - len--; - } - var resources = new ResourceList(len); - for (var i = 0; i < len; ++i) { - var resource = input[i]; - if (Disposer.isDisposer(resource)) { - var disposer = resource; - resource = resource.promise(); - resource._setDisposable(disposer); - } else { - var maybePromise = tryConvertToPromise(resource); - if (maybePromise instanceof Promise) { - resource = - maybePromise._then(maybeUnwrapDisposer, null, null, { - resources: resources, - index: i - }, undefined); - } - } - resources[i] = resource; - } - - var reflectedResources = new Array(resources.length); - for (var i = 0; i < reflectedResources.length; ++i) { - reflectedResources[i] = Promise.resolve(resources[i]).reflect(); - } - - var resultPromise = Promise.all(reflectedResources) - .then(function(inspections) { - for (var i = 0; i < inspections.length; ++i) { - var inspection = inspections[i]; - if (inspection.isRejected()) { - errorObj.e = inspection.error(); - return errorObj; - } else if (!inspection.isFulfilled()) { - resultPromise.cancel(); - return; - } - inspections[i] = inspection.value(); - } - promise._pushContext(); - - fn = tryCatch(fn); - var ret = spreadArgs - ? fn.apply(undefined, inspections) : fn(inspections); - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, promiseCreated, "Promise.using", promise); - return ret; - }); - - var promise = resultPromise.lastly(function() { - var inspection = new Promise.PromiseInspection(resultPromise); - return dispose(resources, inspection); - }); - resources.promise = promise; - promise._setOnCancel(resources); - return promise; - }; - - Promise.prototype._setDisposable = function (disposer) { - this._bitField = this._bitField | 131072; - this._disposer = disposer; - }; - - Promise.prototype._isDisposable = function () { - return (this._bitField & 131072) > 0; - }; - - Promise.prototype._getDisposer = function () { - return this._disposer; - }; - - Promise.prototype._unsetDisposable = function () { - this._bitField = this._bitField & (~131072); - this._disposer = undefined; - }; - - Promise.prototype.disposer = function (fn) { - if (typeof fn === "function") { - return new FunctionDisposer(fn, this, createContext()); - } - throw new TypeError(); - }; - -}; - -},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){ -"use strict"; -var es5 = _dereq_("./es5"); -var canEvaluate = typeof navigator == "undefined"; - -var errorObj = {e: {}}; -var tryCatchTarget; -var globalObject = typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : - typeof global !== "undefined" ? global : - this !== undefined ? this : null; - -function tryCatcher() { - try { - var target = tryCatchTarget; - tryCatchTarget = null; - return target.apply(this, arguments); - } catch (e) { - errorObj.e = e; - return errorObj; - } -} -function tryCatch(fn) { - tryCatchTarget = fn; - return tryCatcher; -} - -var inherits = function(Child, Parent) { - var hasProp = {}.hasOwnProperty; - - function T() { - this.constructor = Child; - this.constructor$ = Parent; - for (var propertyName in Parent.prototype) { - if (hasProp.call(Parent.prototype, propertyName) && - propertyName.charAt(propertyName.length-1) !== "$" - ) { - this[propertyName + "$"] = Parent.prototype[propertyName]; - } - } - } - T.prototype = Parent.prototype; - Child.prototype = new T(); - return Child.prototype; -}; - - -function isPrimitive(val) { - return val == null || val === true || val === false || - typeof val === "string" || typeof val === "number"; - -} - -function isObject(value) { - return typeof value === "function" || - typeof value === "object" && value !== null; -} - -function maybeWrapAsError(maybeError) { - if (!isPrimitive(maybeError)) return maybeError; - - return new Error(safeToString(maybeError)); -} - -function withAppended(target, appendee) { - var len = target.length; - var ret = new Array(len + 1); - var i; - for (i = 0; i < len; ++i) { - ret[i] = target[i]; - } - ret[i] = appendee; - return ret; -} - -function getDataPropertyOrDefault(obj, key, defaultValue) { - if (es5.isES5) { - var desc = Object.getOwnPropertyDescriptor(obj, key); - - if (desc != null) { - return desc.get == null && desc.set == null - ? desc.value - : defaultValue; - } - } else { - return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; - } -} - -function notEnumerableProp(obj, name, value) { - if (isPrimitive(obj)) return obj; - var descriptor = { - value: value, - configurable: true, - enumerable: false, - writable: true - }; - es5.defineProperty(obj, name, descriptor); - return obj; -} - -function thrower(r) { - throw r; -} - -var inheritedDataKeys = (function() { - var excludedPrototypes = [ - Array.prototype, - Object.prototype, - Function.prototype - ]; - - var isExcludedProto = function(val) { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (excludedPrototypes[i] === val) { - return true; - } - } - return false; - }; - - if (es5.isES5) { - var getKeys = Object.getOwnPropertyNames; - return function(obj) { - var ret = []; - var visitedKeys = Object.create(null); - while (obj != null && !isExcludedProto(obj)) { - var keys; - try { - keys = getKeys(obj); - } catch (e) { - return ret; - } - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (visitedKeys[key]) continue; - visitedKeys[key] = true; - var desc = Object.getOwnPropertyDescriptor(obj, key); - if (desc != null && desc.get == null && desc.set == null) { - ret.push(key); - } - } - obj = es5.getPrototypeOf(obj); - } - return ret; - }; - } else { - var hasProp = {}.hasOwnProperty; - return function(obj) { - if (isExcludedProto(obj)) return []; - var ret = []; - - /*jshint forin:false */ - enumeration: for (var key in obj) { - if (hasProp.call(obj, key)) { - ret.push(key); - } else { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (hasProp.call(excludedPrototypes[i], key)) { - continue enumeration; - } - } - ret.push(key); - } - } - return ret; - }; - } - -})(); - -var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; -function isClass(fn) { - try { - if (typeof fn === "function") { - var keys = es5.names(fn.prototype); - - var hasMethods = es5.isES5 && keys.length > 1; - var hasMethodsOtherThanConstructor = keys.length > 0 && - !(keys.length === 1 && keys[0] === "constructor"); - var hasThisAssignmentAndStaticMethods = - thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; - - if (hasMethods || hasMethodsOtherThanConstructor || - hasThisAssignmentAndStaticMethods) { - return true; - } - } - return false; - } catch (e) { - return false; - } -} - -function toFastProperties(obj) { - /*jshint -W027,-W055,-W031*/ - function FakeConstructor() {} - FakeConstructor.prototype = obj; - var receiver = new FakeConstructor(); - function ic() { - return typeof receiver.foo; - } - ic(); - ic(); - return obj; - eval(obj); -} - -var rident = /^[a-z$_][a-z$_0-9]*$/i; -function isIdentifier(str) { - return rident.test(str); -} - -function filledRange(count, prefix, suffix) { - var ret = new Array(count); - for(var i = 0; i < count; ++i) { - ret[i] = prefix + i + suffix; - } - return ret; -} - -function safeToString(obj) { - try { - return obj + ""; - } catch (e) { - return "[no string representation]"; - } -} - -function isError(obj) { - return obj instanceof Error || - (obj !== null && - typeof obj === "object" && - typeof obj.message === "string" && - typeof obj.name === "string"); -} - -function markAsOriginatingFromRejection(e) { - try { - notEnumerableProp(e, "isOperational", true); - } - catch(ignore) {} -} - -function originatesFromRejection(e) { - if (e == null) return false; - return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || - e["isOperational"] === true); -} - -function canAttachTrace(obj) { - return isError(obj) && es5.propertyIsWritable(obj, "stack"); -} - -var ensureErrorObject = (function() { - if (!("stack" in new Error())) { - return function(value) { - if (canAttachTrace(value)) return value; - try {throw new Error(safeToString(value));} - catch(err) {return err;} - }; - } else { - return function(value) { - if (canAttachTrace(value)) return value; - return new Error(safeToString(value)); - }; - } -})(); - -function classString(obj) { - return {}.toString.call(obj); -} - -function copyDescriptors(from, to, filter) { - var keys = es5.names(from); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (filter(key)) { - try { - es5.defineProperty(to, key, es5.getDescriptor(from, key)); - } catch (ignore) {} - } - } -} - -var asArray = function(v) { - if (es5.isArray(v)) { - return v; - } - return null; -}; - -if (typeof Symbol !== "undefined" && Symbol.iterator) { - var ArrayFrom = typeof Array.from === "function" ? function(v) { - return Array.from(v); - } : function(v) { - var ret = []; - var it = v[Symbol.iterator](); - var itResult; - while (!((itResult = it.next()).done)) { - ret.push(itResult.value); - } - return ret; - }; - - asArray = function(v) { - if (es5.isArray(v)) { - return v; - } else if (v != null && typeof v[Symbol.iterator] === "function") { - return ArrayFrom(v); - } - return null; - }; -} - -var isNode = typeof process !== "undefined" && - classString(process).toLowerCase() === "[object process]"; - -var hasEnvVariables = typeof process !== "undefined" && - typeof process.env !== "undefined"; - -function env(key) { - return hasEnvVariables ? process.env[key] : undefined; -} - -function getNativePromise() { - if (typeof Promise === "function") { - try { - var promise = new Promise(function(){}); - if (classString(promise) === "[object Promise]") { - return Promise; - } - } catch (e) {} - } -} - -var reflectHandler; -function contextBind(ctx, cb) { - if (ctx === null || - typeof cb !== "function" || - cb === reflectHandler) { - return cb; - } - - if (ctx.domain !== null) { - cb = ctx.domain.bind(cb); - } - - var async = ctx.async; - if (async !== null) { - var old = cb; - cb = function() { - var args = (new Array(2)).concat([].slice.call(arguments));; - args[0] = old; - args[1] = this; - return async.runInAsyncScope.apply(async, args); - }; - } - return cb; -} - -var ret = { - setReflectHandler: function(fn) { - reflectHandler = fn; - }, - isClass: isClass, - isIdentifier: isIdentifier, - inheritedDataKeys: inheritedDataKeys, - getDataPropertyOrDefault: getDataPropertyOrDefault, - thrower: thrower, - isArray: es5.isArray, - asArray: asArray, - notEnumerableProp: notEnumerableProp, - isPrimitive: isPrimitive, - isObject: isObject, - isError: isError, - canEvaluate: canEvaluate, - errorObj: errorObj, - tryCatch: tryCatch, - inherits: inherits, - withAppended: withAppended, - maybeWrapAsError: maybeWrapAsError, - toFastProperties: toFastProperties, - filledRange: filledRange, - toString: safeToString, - canAttachTrace: canAttachTrace, - ensureErrorObject: ensureErrorObject, - originatesFromRejection: originatesFromRejection, - markAsOriginatingFromRejection: markAsOriginatingFromRejection, - classString: classString, - copyDescriptors: copyDescriptors, - isNode: isNode, - hasEnvVariables: hasEnvVariables, - env: env, - global: globalObject, - getNativePromise: getNativePromise, - contextBind: contextBind -}; -ret.isRecentNode = ret.isNode && (function() { - var version; - if (process.versions && process.versions.node) { - version = process.versions.node.split(".").map(Number); - } else if (process.version) { - version = process.version.split(".").map(Number); - } - return (version[0] === 0 && version[1] > 10) || (version[0] > 0); -})(); -ret.nodeSupportsAsyncResource = ret.isNode && (function() { - var supportsAsync = false; - try { - var res = _dereq_("async_hooks").AsyncResource; - supportsAsync = typeof res.prototype.runInAsyncScope === "function"; - } catch (e) { - supportsAsync = false; - } - return supportsAsync; -})(); - -if (ret.isNode) ret.toFastProperties(process); - -try {throw new Error(); } catch (e) {ret.lastLineError = e;} -module.exports = ret; - -},{"./es5":13,"async_hooks":undefined}]},{},[4])(4) -}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate) -},{"_process":91,"timers":114}],81:[function(require,module,exports){ -// Browser Request -// -// 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. - -// UMD HEADER START -(function (root, factory) { - if (typeof define === 'function' && define.amd) { - // AMD. Register as an anonymous module. - define([], factory); - } else if (typeof exports === 'object') { - // Node. Does not work with strict CommonJS, but - // only CommonJS-like enviroments that support module.exports, - // like Node. - module.exports = factory(); - } else { - // Browser globals (root is window) - root.returnExports = factory(); - } -}(this, function () { -// UMD HEADER END - -var XHR = XMLHttpRequest -if (!XHR) throw new Error('missing XMLHttpRequest') -request.log = { - 'trace': noop, 'debug': noop, 'info': noop, 'warn': noop, 'error': noop -} - -var DEFAULT_TIMEOUT = 3 * 60 * 1000 // 3 minutes - -// -// request -// - -function request(options, callback) { - // The entry-point to the API: prep the options object and pass the real work to run_xhr. - if(typeof callback !== 'function') - throw new Error('Bad callback given: ' + callback) - - if(!options) - throw new Error('No options given') - - var options_onResponse = options.onResponse; // Save this for later. - - if(typeof options === 'string') - options = {'uri':options}; - else - options = JSON.parse(JSON.stringify(options)); // Use a duplicate for mutating. - - options.onResponse = options_onResponse // And put it back. - - if (options.verbose) request.log = getLogger(); - - if(options.url) { - options.uri = options.url; - delete options.url; - } - - if(!options.uri && options.uri !== "") - throw new Error("options.uri is a required argument"); - - if(typeof options.uri != "string") - throw new Error("options.uri must be a string"); - - var unsupported_options = ['proxy', '_redirectsFollowed', 'maxRedirects', 'followRedirect'] - for (var i = 0; i < unsupported_options.length; i++) - if(options[ unsupported_options[i] ]) - throw new Error("options." + unsupported_options[i] + " is not supported") - - options.callback = callback - options.method = options.method || 'GET'; - options.headers = options.headers || {}; - options.body = options.body || null - options.timeout = options.timeout || request.DEFAULT_TIMEOUT - - if(options.headers.host) - throw new Error("Options.headers.host is not supported"); - - if(options.json) { - options.headers.accept = options.headers.accept || 'application/json' - if(options.method !== 'GET') - options.headers['content-type'] = 'application/json' - - if(typeof options.json !== 'boolean') - options.body = JSON.stringify(options.json) - else if(typeof options.body !== 'string') - options.body = JSON.stringify(options.body) - } - - //BEGIN QS Hack - var serialize = function(obj) { - var str = []; - for(var p in obj) - if (obj.hasOwnProperty(p)) { - str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); - } - return str.join("&"); - } - - if(options.qs){ - var qs = (typeof options.qs == 'string')? options.qs : serialize(options.qs); - if(options.uri.indexOf('?') !== -1){ //no get params - options.uri = options.uri+'&'+qs; - }else{ //existing get params - options.uri = options.uri+'?'+qs; - } - } - //END QS Hack - - //BEGIN FORM Hack - var multipart = function(obj) { - //todo: support file type (useful?) - var result = {}; - result.boundry = '-------------------------------'+Math.floor(Math.random()*1000000000); - var lines = []; - for(var p in obj){ - if (obj.hasOwnProperty(p)) { - lines.push( - '--'+result.boundry+"\n"+ - 'Content-Disposition: form-data; name="'+p+'"'+"\n"+ - "\n"+ - obj[p]+"\n" - ); - } - } - lines.push( '--'+result.boundry+'--' ); - result.body = lines.join(''); - result.length = result.body.length; - result.type = 'multipart/form-data; boundary='+result.boundry; - return result; - } - - if(options.form){ - if(typeof options.form == 'string') throw('form name unsupported'); - if(options.method === 'POST'){ - var encoding = (options.encoding || 'application/x-www-form-urlencoded').toLowerCase(); - options.headers['content-type'] = encoding; - switch(encoding){ - case 'application/x-www-form-urlencoded': - options.body = serialize(options.form).replace(/%20/g, "+"); - break; - case 'multipart/form-data': - var multi = multipart(options.form); - //options.headers['content-length'] = multi.length; - options.body = multi.body; - options.headers['content-type'] = multi.type; - break; - default : throw new Error('unsupported encoding:'+encoding); - } - } - } - //END FORM Hack - - // If onResponse is boolean true, call back immediately when the response is known, - // not when the full request is complete. - options.onResponse = options.onResponse || noop - if(options.onResponse === true) { - options.onResponse = callback - options.callback = noop - } - - // XXX Browsers do not like this. - //if(options.body) - // options.headers['content-length'] = options.body.length; - - // HTTP basic authentication - if(!options.headers.authorization && options.auth) - options.headers.authorization = 'Basic ' + b64_enc(options.auth.username + ':' + options.auth.password); - - return run_xhr(options) -} - -var req_seq = 0 -function run_xhr(options) { - var xhr = new XHR - , timed_out = false - , is_cors = is_crossDomain(options.uri) - , supports_cors = ('withCredentials' in xhr) - - req_seq += 1 - xhr.seq_id = req_seq - xhr.id = req_seq + ': ' + options.method + ' ' + options.uri - xhr._id = xhr.id // I know I will type "_id" from habit all the time. - - if(is_cors && !supports_cors) { - var cors_err = new Error('Browser does not support cross-origin request: ' + options.uri) - cors_err.cors = 'unsupported' - return options.callback(cors_err, xhr) - } - - xhr.timeoutTimer = setTimeout(too_late, options.timeout) - function too_late() { - timed_out = true - var er = new Error('ETIMEDOUT') - er.code = 'ETIMEDOUT' - er.duration = options.timeout - - request.log.error('Timeout', { 'id':xhr._id, 'milliseconds':options.timeout }) - return options.callback(er, xhr) - } - - // Some states can be skipped over, so remember what is still incomplete. - var did = {'response':false, 'loading':false, 'end':false} - - xhr.onreadystatechange = on_state_change - xhr.open(options.method, options.uri, true) // asynchronous - if(is_cors) - xhr.withCredentials = !! options.withCredentials - xhr.send(options.body) - return xhr - - function on_state_change(event) { - if(timed_out) - return request.log.debug('Ignoring timed out state change', {'state':xhr.readyState, 'id':xhr.id}) - - request.log.debug('State change', {'state':xhr.readyState, 'id':xhr.id, 'timed_out':timed_out}) - - if(xhr.readyState === XHR.OPENED) { - request.log.debug('Request started', {'id':xhr.id}) - for (var key in options.headers) - xhr.setRequestHeader(key, options.headers[key]) - } - - else if(xhr.readyState === XHR.HEADERS_RECEIVED) - on_response() - - else if(xhr.readyState === XHR.LOADING) { - on_response() - on_loading() - } - - else if(xhr.readyState === XHR.DONE) { - on_response() - on_loading() - on_end() - } - } - - function on_response() { - if(did.response) - return - - did.response = true - request.log.debug('Got response', {'id':xhr.id, 'status':xhr.status}) - clearTimeout(xhr.timeoutTimer) - xhr.statusCode = xhr.status // Node request compatibility - - // Detect failed CORS requests. - if(is_cors && xhr.statusCode == 0) { - var cors_err = new Error('CORS request rejected: ' + options.uri) - cors_err.cors = 'rejected' - - // Do not process this request further. - did.loading = true - did.end = true - - return options.callback(cors_err, xhr) - } - - options.onResponse(null, xhr) - } - - function on_loading() { - if(did.loading) - return - - did.loading = true - request.log.debug('Response body loading', {'id':xhr.id}) - // TODO: Maybe simulate "data" events by watching xhr.responseText - } - - function on_end() { - if(did.end) - return - - did.end = true - request.log.debug('Request done', {'id':xhr.id}) - - xhr.body = xhr.responseText - if(options.json) { - try { xhr.body = JSON.parse(xhr.responseText) } - catch (er) { return options.callback(er, xhr) } - } - - options.callback(null, xhr, xhr.body) - } - -} // request - -request.withCredentials = false; -request.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT; - -// -// defaults -// - -request.defaults = function(options, requester) { - var def = function (method) { - var d = function (params, callback) { - if(typeof params === 'string') - params = {'uri': params}; - else { - params = JSON.parse(JSON.stringify(params)); - } - for (var i in options) { - if (params[i] === undefined) params[i] = options[i] - } - return method(params, callback) - } - return d - } - var de = def(request) - de.get = def(request.get) - de.post = def(request.post) - de.put = def(request.put) - de.head = def(request.head) - return de -} - -// -// HTTP method shortcuts -// - -var shortcuts = [ 'get', 'put', 'post', 'head' ]; -shortcuts.forEach(function(shortcut) { - var method = shortcut.toUpperCase(); - var func = shortcut.toLowerCase(); - - request[func] = function(opts) { - if(typeof opts === 'string') - opts = {'method':method, 'uri':opts}; - else { - opts = JSON.parse(JSON.stringify(opts)); - opts.method = method; - } - - var args = [opts].concat(Array.prototype.slice.apply(arguments, [1])); - return request.apply(this, args); - } -}) - -// -// CouchDB shortcut -// - -request.couch = function(options, callback) { - if(typeof options === 'string') - options = {'uri':options} - - // Just use the request API to do JSON. - options.json = true - if(options.body) - options.json = options.body - delete options.body - - callback = callback || noop - - var xhr = request(options, couch_handler) - return xhr - - function couch_handler(er, resp, body) { - if(er) - return callback(er, resp, body) - - if((resp.statusCode < 200 || resp.statusCode > 299) && body.error) { - // The body is a Couch JSON object indicating the error. - er = new Error('CouchDB error: ' + (body.error.reason || body.error.error)) - for (var key in body) - er[key] = body[key] - return callback(er, resp, body); - } - - return callback(er, resp, body); - } -} - -// -// Utility -// - -function noop() {} - -function getLogger() { - var logger = {} - , levels = ['trace', 'debug', 'info', 'warn', 'error'] - , level, i - - for(i = 0; i < levels.length; i++) { - level = levels[i] - - logger[level] = noop - if(typeof console !== 'undefined' && console && console[level]) - logger[level] = formatted(console, level) - } - - return logger -} - -function formatted(obj, method) { - return formatted_logger - - function formatted_logger(str, context) { - if(typeof context === 'object') - str += ' ' + JSON.stringify(context) - - return obj[method].call(obj, str) - } -} - -// Return whether a URL is a cross-domain request. -function is_crossDomain(url) { - var rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/ - - // jQuery #8138, IE may throw an exception when accessing - // a field from window.location if document.domain has been set - var ajaxLocation - try { ajaxLocation = location.href } - catch (e) { - // Use the href attribute of an A element since IE will modify it given document.location - ajaxLocation = document.createElement( "a" ); - ajaxLocation.href = ""; - ajaxLocation = ajaxLocation.href; - } - - var ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || [] - , parts = rurl.exec(url.toLowerCase() ) - - var result = !!( - parts && - ( parts[1] != ajaxLocParts[1] - || parts[2] != ajaxLocParts[2] - || (parts[3] || (parts[1] === "http:" ? 80 : 443)) != (ajaxLocParts[3] || (ajaxLocParts[1] === "http:" ? 80 : 443)) - ) - ) - - //console.debug('is_crossDomain('+url+') -> ' + result) - return result -} - -// MIT License from http://phpjs.org/functions/base64_encode:358 -function b64_enc (data) { - // Encodes string using MIME base64 algorithm - var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; - var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = []; - - if (!data) { - return data; - } - - // assume utf8 data - // data = this.utf8_encode(data+''); - - do { // pack three octets into four hexets - o1 = data.charCodeAt(i++); - o2 = data.charCodeAt(i++); - o3 = data.charCodeAt(i++); - - bits = o1<<16 | o2<<8 | o3; - - h1 = bits>>18 & 0x3f; - h2 = bits>>12 & 0x3f; - h3 = bits>>6 & 0x3f; - h4 = bits & 0x3f; - - // use hexets to index into b64, and append result to encoded string - tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); - } while (i < data.length); - - enc = tmp_arr.join(''); - - switch (data.length % 3) { - case 1: - enc = enc.slice(0, -2) + '=='; - break; - case 2: - enc = enc.slice(0, -1) + '='; - break; - } - - return enc; -} - return request; -//UMD FOOTER START -})); -//UMD FOOTER END - -},{}],82:[function(require,module,exports){ - -},{}],83:[function(require,module,exports){ -arguments[4][82][0].apply(exports,arguments) -},{"dup":82}],84:[function(require,module,exports){ -(function (Buffer){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - -'use strict' - -var base64 = require('base64-js') -var ieee754 = require('ieee754') - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -var K_MAX_LENGTH = 0x7fffffff -exports.kMaxLength = K_MAX_LENGTH - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ -Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() - -if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && - typeof console.error === 'function') { - console.error( - 'This browser lacks typed array (Uint8Array) support which is required by ' + - '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' - ) -} - -function typedArraySupport () { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1) - arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } - return arr.foo() === 42 - } catch (e) { - return false - } -} - -Object.defineProperty(Buffer.prototype, 'parent', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.buffer - } -}) - -Object.defineProperty(Buffer.prototype, 'offset', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.byteOffset - } -}) - -function createBuffer (length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('The value "' + length + '" is invalid for option "size"') - } - // Return an augmented `Uint8Array` instance - var buf = new Uint8Array(length) - buf.__proto__ = Buffer.prototype - return buf -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ) - } - return allocUnsafe(arg) - } - return from(arg, encodingOrOffset, length) -} - -// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 -if (typeof Symbol !== 'undefined' && Symbol.species != null && - Buffer[Symbol.species] === Buffer) { - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true, - enumerable: false, - writable: false - }) -} - -Buffer.poolSize = 8192 // not used by this implementation - -function from (value, encodingOrOffset, length) { - if (typeof value === 'string') { - return fromString(value, encodingOrOffset) - } - - if (ArrayBuffer.isView(value)) { - return fromArrayLike(value) - } - - if (value == null) { - throw TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) - } - - if (isInstance(value, ArrayBuffer) || - (value && isInstance(value.buffer, ArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length) - } - - if (typeof value === 'number') { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ) - } - - var valueOf = value.valueOf && value.valueOf() - if (valueOf != null && valueOf !== value) { - return Buffer.from(valueOf, encodingOrOffset, length) - } - - var b = fromObject(value) - if (b) return b - - if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && - typeof value[Symbol.toPrimitive] === 'function') { - return Buffer.from( - value[Symbol.toPrimitive]('string'), encodingOrOffset, length - ) - } - - throw new TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length) -} - -// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: -// https://github.com/feross/buffer/pull/148 -Buffer.prototype.__proto__ = Uint8Array.prototype -Buffer.__proto__ = Uint8Array - -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be of type number') - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } -} - -function alloc (size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(size).fill(fill, encoding) - : createBuffer(size).fill(fill) - } - return createBuffer(size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding) -} - -function allocUnsafe (size) { - assertSize(size) - return createBuffer(size < 0 ? 0 : checked(size) | 0) -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(size) -} - -function fromString (string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - - var length = byteLength(string, encoding) | 0 - var buf = createBuffer(length) - - var actual = buf.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - buf = buf.slice(0, actual) - } - - return buf -} - -function fromArrayLike (array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - var buf = createBuffer(length) - for (var i = 0; i < length; i += 1) { - buf[i] = array[i] & 255 - } - return buf -} - -function fromArrayBuffer (array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds') - } - - var buf - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array) - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset) - } else { - buf = new Uint8Array(array, byteOffset, length) - } - - // Return an augmented `Uint8Array` instance - buf.__proto__ = Buffer.prototype - return buf -} - -function fromObject (obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - var buf = createBuffer(len) - - if (buf.length === 0) { - return buf - } - - obj.copy(buf, 0, 0, len) - return buf - } - - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) - } - return fromArrayLike(obj) - } - - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) - } -} - -function checked (length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= K_MAX_LENGTH) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { - return b != null && b._isBuffer === true && - b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false -} - -Buffer.compare = function compare (a, b) { - if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) - if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ) - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (isInstance(buf, Uint8Array)) { - buf = Buffer.from(buf) - } - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer -} - -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + - 'Received type ' + typeof string - ) - } - - var len = string.length - var mustMatch = (arguments.length > 2 && arguments[2] === true) - if (!mustMatch && len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 - } - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) -// to detect a Buffer instance. It's not possible to use `instanceof Buffer` -// reliably in a browserify context because there could be multiple different -// copies of the 'buffer' package in use. This method works even for Buffer -// instances that were created from another copy of the `buffer` package. -// See: https://github.com/feross/buffer/issues/154 -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} - -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.toLocaleString = Buffer.prototype.toString - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() - if (this.length > max) str += ' ... ' - return '' -} - -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer.from(target, target.offset, target.byteLength) - } - if (!Buffer.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. ' + - 'Received type ' + (typeof target) - ) - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') -} - -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - var strLen = string.length - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 0 - if (isFinite(length)) { - length = length >>> 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf = this.subarray(start, end) - // Return an augmented `Uint8Array` instance - newBuf.__proto__ = Buffer.prototype - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('Index out of range') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - - if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { - // Use built-in when available, missing from IE11 - this.copyWithin(targetStart, start, end) - } else if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (var i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ) - } - - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if ((encoding === 'utf8' && code < 128) || - encoding === 'latin1') { - // Fast path: If `val` fits into a single byte, use that numeric value. - val = code - } - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : Buffer.from(val, encoding) - var len = bytes.length - if (len === 0) { - throw new TypeError('The value "' + val + - '" is invalid for argument "value"') - } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node takes equal signs as end of the Base64 encoding - str = str.split('=')[0] - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = str.trim().replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass -// the `instanceof` check but they should be treated as of that type. -// See: https://github.com/feross/buffer/issues/166 -function isInstance (obj, type) { - return obj instanceof type || - (obj != null && obj.constructor != null && obj.constructor.name != null && - obj.constructor.name === type.name) -} -function numberIsNaN (obj) { - // For IE11 support - return obj !== obj // eslint-disable-line no-self-compare -} - -}).call(this,require("buffer").Buffer) -},{"base64-js":79,"buffer":84,"ieee754":87}],85:[function(require,module,exports){ -(function (Buffer){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. - -function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); - } - return objectToString(arg) === '[object Array]'; -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = Buffer.isBuffer; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - -}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":89}],86:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var objectCreate = Object.create || objectCreatePolyfill -var objectKeys = Object.keys || objectKeysPolyfill -var bind = Function.prototype.bind || functionBindPolyfill - -function EventEmitter() { - if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) { - this._events = objectCreate(null); - this._eventsCount = 0; - } - - this._maxListeners = this._maxListeners || undefined; -} -module.exports = EventEmitter; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -var defaultMaxListeners = 10; - -var hasDefineProperty; -try { - var o = {}; - if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 }); - hasDefineProperty = o.x === 0; -} catch (err) { hasDefineProperty = false } -if (hasDefineProperty) { - Object.defineProperty(EventEmitter, 'defaultMaxListeners', { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - // check whether the input is a positive number (whose value is zero or - // greater and not a NaN). - if (typeof arg !== 'number' || arg < 0 || arg !== arg) - throw new TypeError('"defaultMaxListeners" must be a positive number'); - defaultMaxListeners = arg; - } - }); -} else { - EventEmitter.defaultMaxListeners = defaultMaxListeners; -} - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || isNaN(n)) - throw new TypeError('"n" argument must be a positive number'); - this._maxListeners = n; - return this; -}; - -function $getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; -} - -EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return $getMaxListeners(this); -}; - -// These standalone emit* functions are used to optimize calling of event -// handlers for fast cases because emit() itself often has a variable number of -// arguments and can be deoptimized because of that. These functions always have -// the same number of arguments and thus do not get deoptimized, so the code -// inside them can execute faster. -function emitNone(handler, isFn, self) { - if (isFn) - handler.call(self); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].call(self); - } -} -function emitOne(handler, isFn, self, arg1) { - if (isFn) - handler.call(self, arg1); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].call(self, arg1); - } -} -function emitTwo(handler, isFn, self, arg1, arg2) { - if (isFn) - handler.call(self, arg1, arg2); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].call(self, arg1, arg2); - } -} -function emitThree(handler, isFn, self, arg1, arg2, arg3) { - if (isFn) - handler.call(self, arg1, arg2, arg3); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].call(self, arg1, arg2, arg3); - } -} - -function emitMany(handler, isFn, self, args) { - if (isFn) - handler.apply(self, args); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].apply(self, args); - } -} - -EventEmitter.prototype.emit = function emit(type) { - var er, handler, len, args, i, events; - var doError = (type === 'error'); - - events = this._events; - if (events) - doError = (doError && events.error == null); - else if (!doError) - return false; - - // If there is no 'error' event listener then throw. - if (doError) { - if (arguments.length > 1) - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - // At least give some kind of context to the user - var err = new Error('Unhandled "error" event. (' + er + ')'); - err.context = er; - throw err; - } - return false; - } - - handler = events[type]; - - if (!handler) - return false; - - var isFn = typeof handler === 'function'; - len = arguments.length; - switch (len) { - // fast cases - case 1: - emitNone(handler, isFn, this); - break; - case 2: - emitOne(handler, isFn, this, arguments[1]); - break; - case 3: - emitTwo(handler, isFn, this, arguments[1], arguments[2]); - break; - case 4: - emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); - break; - // slower - default: - args = new Array(len - 1); - for (i = 1; i < len; i++) - args[i - 1] = arguments[i]; - emitMany(handler, isFn, this, args); - } - - return true; -}; - -function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; - - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); - - events = target._events; - if (!events) { - events = target._events = objectCreate(null); - target._eventsCount = 0; - } else { - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (events.newListener) { - target.emit('newListener', type, - listener.listener ? listener.listener : listener); - - // Re-assign `events` because a newListener handler could have caused the - // this._events to be assigned to a new object - events = target._events; - } - existing = events[type]; - } - - if (!existing) { - // Optimize the case of one listener. Don't need the extra array object. - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === 'function') { - // Adding the second element, need to change to array. - existing = events[type] = - prepend ? [listener, existing] : [existing, listener]; - } else { - // If we've already got an array, just append. - if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - } - - // Check for listener leak - if (!existing.warned) { - m = $getMaxListeners(target); - if (m && m > 0 && existing.length > m) { - existing.warned = true; - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' "' + String(type) + '" listeners ' + - 'added. Use emitter.setMaxListeners() to ' + - 'increase limit.'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - if (typeof console === 'object' && console.warn) { - console.warn('%s: %s', w.name, w.message); - } - } - } - } - - return target; -} - -EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; - -function onceWrapper() { - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - switch (arguments.length) { - case 0: - return this.listener.call(this.target); - case 1: - return this.listener.call(this.target, arguments[0]); - case 2: - return this.listener.call(this.target, arguments[0], arguments[1]); - case 3: - return this.listener.call(this.target, arguments[0], arguments[1], - arguments[2]); - default: - var args = new Array(arguments.length); - for (var i = 0; i < args.length; ++i) - args[i] = arguments[i]; - this.listener.apply(this.target, args); - } - } -} - -function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; - var wrapped = bind.call(onceWrapper, state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; -} - -EventEmitter.prototype.once = function once(type, listener) { - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); - this.on(type, _onceWrap(this, type, listener)); - return this; -}; - -EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - -// Emits a 'removeListener' event if and only if the listener was removed. -EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; - - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); - - events = this._events; - if (!events) - return this; - - list = events[type]; - if (!list) - return this; - - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = objectCreate(null); - else { - delete events[type]; - if (events.removeListener) - this.emit('removeListener', type, list.listener || listener); - } - } else if (typeof list !== 'function') { - position = -1; - - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } - } - - if (position < 0) - return this; - - if (position === 0) - list.shift(); - else - spliceOne(list, position); - - if (list.length === 1) - events[type] = list[0]; - - if (events.removeListener) - this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - -EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; - - events = this._events; - if (!events) - return this; - - // not listening for removeListener, no need to emit - if (!events.removeListener) { - if (arguments.length === 0) { - this._events = objectCreate(null); - this._eventsCount = 0; - } else if (events[type]) { - if (--this._eventsCount === 0) - this._events = objectCreate(null); - else - delete events[type]; - } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = objectKeys(events); - var key; - for (i = 0; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = objectCreate(null); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - for (i = listeners.length - 1; i >= 0; i--) { - this.removeListener(type, listeners[i]); - } - } - - return this; - }; - -function _listeners(target, type, unwrap) { - var events = target._events; - - if (!events) - return []; - - var evlistener = events[type]; - if (!evlistener) - return []; - - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - - return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); -} - -EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); -}; - -EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); -}; - -EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); - } -}; - -EventEmitter.prototype.listenerCount = listenerCount; -function listenerCount(type) { - var events = this._events; - - if (events) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener) { - return evlistener.length; - } - } - - return 0; -} - -EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; -}; - -// About 1.5x faster than the two-arg version of Array#splice(). -function spliceOne(list, index) { - for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) - list[i] = list[k]; - list.pop(); -} - -function arrayClone(arr, n) { - var copy = new Array(n); - for (var i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; -} - -function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - return ret; -} - -function objectCreatePolyfill(proto) { - var F = function() {}; - F.prototype = proto; - return new F; -} -function objectKeysPolyfill(obj) { - var keys = []; - for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) { - keys.push(k); - } - return k; -} -function functionBindPolyfill(context) { - var fn = this; - return function () { - return fn.apply(context, arguments); - }; -} - -},{}],87:[function(require,module,exports){ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - -},{}],88:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} - -},{}],89:[function(require,module,exports){ -/*! - * Determine if an object is a Buffer - * - * @author Feross Aboukhadijeh - * @license MIT - */ - -// The _isBuffer check is for Safari 5-7 support, because it's missing -// Object.prototype.constructor. Remove this eventually -module.exports = function (obj) { - return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) -} - -function isBuffer (obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) -} - -// For Node v0.10 support. Remove this eventually. -function isSlowBuffer (obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) -} - -},{}],90:[function(require,module,exports){ -(function (global){ -/** - * @license - * Lodash - * Copyright OpenJS Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ -;(function() { - - /** Used as a safe reference for `undefined` in pre-ES5 environments. */ - var undefined; - - /** Used as the semantic version number. */ - var VERSION = '4.17.20'; - - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; - - /** Error message constants. */ - var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', - FUNC_ERROR_TEXT = 'Expected a function'; - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; - - /** Used as the maximum memoize cache size. */ - var MAX_MEMOIZE_SIZE = 500; - - /** Used as the internal argument placeholder. */ - var PLACEHOLDER = '__lodash_placeholder__'; - - /** Used to compose bitmasks for cloning. */ - var CLONE_DEEP_FLAG = 1, - CLONE_FLAT_FLAG = 2, - CLONE_SYMBOLS_FLAG = 4; - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; - - /** Used to compose bitmasks for function metadata. */ - var WRAP_BIND_FLAG = 1, - WRAP_BIND_KEY_FLAG = 2, - WRAP_CURRY_BOUND_FLAG = 4, - WRAP_CURRY_FLAG = 8, - WRAP_CURRY_RIGHT_FLAG = 16, - WRAP_PARTIAL_FLAG = 32, - WRAP_PARTIAL_RIGHT_FLAG = 64, - WRAP_ARY_FLAG = 128, - WRAP_REARG_FLAG = 256, - WRAP_FLIP_FLAG = 512; - - /** Used as default options for `_.truncate`. */ - var DEFAULT_TRUNC_LENGTH = 30, - DEFAULT_TRUNC_OMISSION = '...'; - - /** Used to detect hot functions by number of calls within a span of milliseconds. */ - var HOT_COUNT = 800, - HOT_SPAN = 16; - - /** Used to indicate the type of lazy iteratees. */ - var LAZY_FILTER_FLAG = 1, - LAZY_MAP_FLAG = 2, - LAZY_WHILE_FLAG = 3; - - /** Used as references for various `Number` constants. */ - var INFINITY = 1 / 0, - MAX_SAFE_INTEGER = 9007199254740991, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; - - /** Used as references for the maximum length and index of an array. */ - var MAX_ARRAY_LENGTH = 4294967295, - MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, - HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; - - /** Used to associate wrap methods with their bit flags. */ - var wrapFlags = [ - ['ary', WRAP_ARY_FLAG], - ['bind', WRAP_BIND_FLAG], - ['bindKey', WRAP_BIND_KEY_FLAG], - ['curry', WRAP_CURRY_FLAG], - ['curryRight', WRAP_CURRY_RIGHT_FLAG], - ['flip', WRAP_FLIP_FLAG], - ['partial', WRAP_PARTIAL_FLAG], - ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], - ['rearg', WRAP_REARG_FLAG] - ]; - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - asyncTag = '[object AsyncFunction]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - domExcTag = '[object DOMException]', - errorTag = '[object Error]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - mapTag = '[object Map]', - numberTag = '[object Number]', - nullTag = '[object Null]', - objectTag = '[object Object]', - promiseTag = '[object Promise]', - proxyTag = '[object Proxy]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - symbolTag = '[object Symbol]', - undefinedTag = '[object Undefined]', - weakMapTag = '[object WeakMap]', - weakSetTag = '[object WeakSet]'; - - var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - - /** Used to match empty string literals in compiled template source. */ - var reEmptyStringLeading = /\b__p \+= '';/g, - reEmptyStringMiddle = /\b(__p \+=) '' \+/g, - reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; - - /** Used to match HTML entities and HTML characters. */ - var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, - reUnescapedHtml = /[&<>"']/g, - reHasEscapedHtml = RegExp(reEscapedHtml.source), - reHasUnescapedHtml = RegExp(reUnescapedHtml.source); - - /** Used to match template delimiters. */ - var reEscape = /<%-([\s\S]+?)%>/g, - reEvaluate = /<%([\s\S]+?)%>/g, - reInterpolate = /<%=([\s\S]+?)%>/g; - - /** Used to match property names within property paths. */ - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/, - rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, - reHasRegExpChar = RegExp(reRegExpChar.source); - - /** Used to match leading and trailing whitespace. */ - var reTrim = /^\s+|\s+$/g, - reTrimStart = /^\s+/, - reTrimEnd = /\s+$/; - - /** Used to match wrap detail comments. */ - var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, - reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, - reSplitDetails = /,? & /; - - /** Used to match words composed of alphanumeric characters. */ - var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; - - /** Used to match backslashes in property paths. */ - var reEscapeChar = /\\(\\)?/g; - - /** - * Used to match - * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). - */ - var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; - - /** Used to match `RegExp` flags from their coerced string values. */ - var reFlags = /\w*$/; - - /** Used to detect bad signed hexadecimal string values. */ - var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - - /** Used to detect binary string values. */ - var reIsBinary = /^0b[01]+$/i; - - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; - - /** Used to detect octal string values. */ - var reIsOctal = /^0o[0-7]+$/i; - - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; - - /** Used to match Latin Unicode letters (excluding mathematical operators). */ - var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; - - /** Used to ensure capturing order of template delimiters. */ - var reNoMatch = /($^)/; - - /** Used to match unescaped characters in compiled string literals. */ - var reUnescapedString = /['\n\r\u2028\u2029\\]/g; - - /** Used to compose unicode character classes. */ - var rsAstralRange = '\\ud800-\\udfff', - rsComboMarksRange = '\\u0300-\\u036f', - reComboHalfMarksRange = '\\ufe20-\\ufe2f', - rsComboSymbolsRange = '\\u20d0-\\u20ff', - rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, - rsDingbatRange = '\\u2700-\\u27bf', - rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', - rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', - rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', - rsPunctuationRange = '\\u2000-\\u206f', - rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', - rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', - rsVarRange = '\\ufe0e\\ufe0f', - rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; - - /** Used to compose unicode capture groups. */ - var rsApos = "['\u2019]", - rsAstral = '[' + rsAstralRange + ']', - rsBreak = '[' + rsBreakRange + ']', - rsCombo = '[' + rsComboRange + ']', - rsDigits = '\\d+', - rsDingbat = '[' + rsDingbatRange + ']', - rsLower = '[' + rsLowerRange + ']', - rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', - rsFitz = '\\ud83c[\\udffb-\\udfff]', - rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', - rsNonAstral = '[^' + rsAstralRange + ']', - rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', - rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', - rsUpper = '[' + rsUpperRange + ']', - rsZWJ = '\\u200d'; - - /** Used to compose unicode regexes. */ - var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', - rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', - rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', - rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', - reOptMod = rsModifier + '?', - rsOptVar = '[' + rsVarRange + ']?', - rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', - rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', - rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', - rsSeq = rsOptVar + reOptMod + rsOptJoin, - rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, - rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - - /** Used to match apostrophes. */ - var reApos = RegExp(rsApos, 'g'); - - /** - * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and - * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). - */ - var reComboMark = RegExp(rsCombo, 'g'); - - /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ - var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - - /** Used to match complex or compound words. */ - var reUnicodeWord = RegExp([ - rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', - rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', - rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, - rsUpper + '+' + rsOptContrUpper, - rsOrdUpper, - rsOrdLower, - rsDigits, - rsEmoji - ].join('|'), 'g'); - - /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ - var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); - - /** Used to detect strings that need a more robust regexp to match words. */ - var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; - - /** Used to assign default `context` object properties. */ - var contextProps = [ - 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', - 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', - 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', - 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', - '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' - ]; - - /** Used to make template sourceURLs easier to identify. */ - var templateCounter = -1; - - /** Used to identify `toStringTag` values of typed arrays. */ - var typedArrayTags = {}; - typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = - typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = - typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = - typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = - typedArrayTags[uint32Tag] = true; - typedArrayTags[argsTag] = typedArrayTags[arrayTag] = - typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = - typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = - typedArrayTags[errorTag] = typedArrayTags[funcTag] = - typedArrayTags[mapTag] = typedArrayTags[numberTag] = - typedArrayTags[objectTag] = typedArrayTags[regexpTag] = - typedArrayTags[setTag] = typedArrayTags[stringTag] = - typedArrayTags[weakMapTag] = false; - - /** Used to identify `toStringTag` values supported by `_.clone`. */ - var cloneableTags = {}; - cloneableTags[argsTag] = cloneableTags[arrayTag] = - cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = - cloneableTags[boolTag] = cloneableTags[dateTag] = - cloneableTags[float32Tag] = cloneableTags[float64Tag] = - cloneableTags[int8Tag] = cloneableTags[int16Tag] = - cloneableTags[int32Tag] = cloneableTags[mapTag] = - cloneableTags[numberTag] = cloneableTags[objectTag] = - cloneableTags[regexpTag] = cloneableTags[setTag] = - cloneableTags[stringTag] = cloneableTags[symbolTag] = - cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = - cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; - cloneableTags[errorTag] = cloneableTags[funcTag] = - cloneableTags[weakMapTag] = false; - - /** Used to map Latin Unicode letters to basic Latin letters. */ - var deburredLetters = { - // Latin-1 Supplement block. - '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', - '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', - '\xc7': 'C', '\xe7': 'c', - '\xd0': 'D', '\xf0': 'd', - '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', - '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', - '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', - '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', - '\xd1': 'N', '\xf1': 'n', - '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', - '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', - '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', - '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', - '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', - '\xc6': 'Ae', '\xe6': 'ae', - '\xde': 'Th', '\xfe': 'th', - '\xdf': 'ss', - // Latin Extended-A block. - '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', - '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', - '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', - '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', - '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', - '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', - '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', - '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', - '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', - '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', - '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', - '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', - '\u0134': 'J', '\u0135': 'j', - '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', - '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', - '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', - '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', - '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', - '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', - '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', - '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', - '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', - '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', - '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', - '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', - '\u0163': 't', '\u0165': 't', '\u0167': 't', - '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', - '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', - '\u0174': 'W', '\u0175': 'w', - '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', - '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', - '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', - '\u0132': 'IJ', '\u0133': 'ij', - '\u0152': 'Oe', '\u0153': 'oe', - '\u0149': "'n", '\u017f': 's' - }; - - /** Used to map characters to HTML entities. */ - var htmlEscapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''' - }; - - /** Used to map HTML entities to characters. */ - var htmlUnescapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - ''': "'" - }; - - /** Used to escape characters for inclusion in compiled string literals. */ - var stringEscapes = { - '\\': '\\', - "'": "'", - '\n': 'n', - '\r': 'r', - '\u2028': 'u2028', - '\u2029': 'u2029' - }; - - /** Built-in method references without a dependency on `root`. */ - var freeParseFloat = parseFloat, - freeParseInt = parseInt; - - /** Detect free variable `global` from Node.js. */ - var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - - /** Detect free variable `self`. */ - var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - - /** Used as a reference to the global object. */ - var root = freeGlobal || freeSelf || Function('return this')(); - - /** Detect free variable `exports`. */ - var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; - - /** Detect free variable `process` from Node.js. */ - var freeProcess = moduleExports && freeGlobal.process; - - /** Used to access faster Node.js helpers. */ - var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule && freeModule.require && freeModule.require('util').types; - - if (types) { - return types; - } - - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} - }()); - - /* Node.js helper references. */ - var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, - nodeIsDate = nodeUtil && nodeUtil.isDate, - nodeIsMap = nodeUtil && nodeUtil.isMap, - nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, - nodeIsSet = nodeUtil && nodeUtil.isSet, - nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - - /*--------------------------------------------------------------------------*/ - - /** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ - function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); - } - - /** - * A specialized version of `baseAggregator` for arrays. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform keys. - * @param {Object} accumulator The initial aggregated object. - * @returns {Function} Returns `accumulator`. - */ - function arrayAggregator(array, setter, iteratee, accumulator) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - var value = array[index]; - setter(accumulator, value, iteratee(value), array); - } - return accumulator; - } - - /** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEach(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; - } - - /** - * A specialized version of `_.forEachRight` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEachRight(array, iteratee) { - var length = array == null ? 0 : array.length; - - while (length--) { - if (iteratee(array[length], length, array) === false) { - break; - } - } - return array; - } - - /** - * A specialized version of `_.every` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - */ - function arrayEvery(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (!predicate(array[index], index, array)) { - return false; - } - } - return true; - } - - /** - * A specialized version of `_.filter` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function arrayFilter(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } - } - return result; - } - - /** - * A specialized version of `_.includes` for arrays without support for - * specifying an index to search from. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ - function arrayIncludes(array, value) { - var length = array == null ? 0 : array.length; - return !!length && baseIndexOf(array, value, 0) > -1; - } - - /** - * This function is like `arrayIncludes` except that it accepts a comparator. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @param {Function} comparator The comparator invoked per element. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ - function arrayIncludesWith(array, value, comparator) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (comparator(value, array[index])) { - return true; - } - } - return false; - } - - /** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function arrayMap(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); - - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; - } - - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } - - /** - * A specialized version of `_.reduce` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the first element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, - length = array == null ? 0 : array.length; - - if (initAccum && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; - } - - /** - * A specialized version of `_.reduceRight` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the last element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduceRight(array, iteratee, accumulator, initAccum) { - var length = array == null ? 0 : array.length; - if (initAccum && length) { - accumulator = array[--length]; - } - while (length--) { - accumulator = iteratee(accumulator, array[length], length, array); - } - return accumulator; - } - - /** - * A specialized version of `_.some` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function arraySome(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; - } - - /** - * Gets the size of an ASCII `string`. - * - * @private - * @param {string} string The string inspect. - * @returns {number} Returns the string size. - */ - var asciiSize = baseProperty('length'); - - /** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function asciiToArray(string) { - return string.split(''); - } - - /** - * Splits an ASCII `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ - function asciiWords(string) { - return string.match(reAsciiWord) || []; - } - - /** - * The base implementation of methods like `_.findKey` and `_.findLastKey`, - * without support for iteratee shorthands, which iterates over `collection` - * using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the found element or its key, else `undefined`. - */ - function baseFindKey(collection, predicate, eachFunc) { - var result; - eachFunc(collection, function(value, key, collection) { - if (predicate(value, key, collection)) { - result = key; - return false; - } - }); - return result; - } - - /** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); - - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; - } - - /** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseIndexOf(array, value, fromIndex) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex(array, baseIsNaN, fromIndex); - } - - /** - * This function is like `baseIndexOf` except that it accepts a comparator. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @param {Function} comparator The comparator invoked per element. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseIndexOfWith(array, value, fromIndex, comparator) { - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (comparator(array[index], value)) { - return index; - } - } - return -1; - } - - /** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ - function baseIsNaN(value) { - return value !== value; - } - - /** - * The base implementation of `_.mean` and `_.meanBy` without support for - * iteratee shorthands. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {number} Returns the mean. - */ - function baseMean(array, iteratee) { - var length = array == null ? 0 : array.length; - return length ? (baseSum(array, iteratee) / length) : NAN; - } - - /** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; - } - - /** - * The base implementation of `_.propertyOf` without support for deep paths. - * - * @private - * @param {Object} object The object to query. - * @returns {Function} Returns the new accessor function. - */ - function basePropertyOf(object) { - return function(key) { - return object == null ? undefined : object[key]; - }; - } - - /** - * The base implementation of `_.reduce` and `_.reduceRight`, without support - * for iteratee shorthands, which iterates over `collection` using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} accumulator The initial value. - * @param {boolean} initAccum Specify using the first or last element of - * `collection` as the initial value. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the accumulated value. - */ - function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { - eachFunc(collection, function(value, index, collection) { - accumulator = initAccum - ? (initAccum = false, value) - : iteratee(accumulator, value, index, collection); - }); - return accumulator; - } - - /** - * The base implementation of `_.sortBy` which uses `comparer` to define the - * sort order of `array` and replaces criteria objects with their corresponding - * values. - * - * @private - * @param {Array} array The array to sort. - * @param {Function} comparer The function to define sort order. - * @returns {Array} Returns `array`. - */ - function baseSortBy(array, comparer) { - var length = array.length; - - array.sort(comparer); - while (length--) { - array[length] = array[length].value; - } - return array; - } - - /** - * The base implementation of `_.sum` and `_.sumBy` without support for - * iteratee shorthands. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {number} Returns the sum. - */ - function baseSum(array, iteratee) { - var result, - index = -1, - length = array.length; - - while (++index < length) { - var current = iteratee(array[index]); - if (current !== undefined) { - result = result === undefined ? current : (result + current); - } - } - return result; - } - - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ - function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; - } - - /** - * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array - * of key-value pairs for `object` corresponding to the property names of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the key-value pairs. - */ - function baseToPairs(object, props) { - return arrayMap(props, function(key) { - return [key, object[key]]; - }); - } - - /** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ - function baseUnary(func) { - return function(value) { - return func(value); - }; - } - - /** - * The base implementation of `_.values` and `_.valuesIn` which creates an - * array of `object` property values corresponding to the property names - * of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the array of property values. - */ - function baseValues(object, props) { - return arrayMap(props, function(key) { - return object[key]; - }); - } - - /** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function cacheHas(cache, key) { - return cache.has(key); - } - - /** - * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the first unmatched string symbol. - */ - function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, - length = strSymbols.length; - - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } - - /** - * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the last unmatched string symbol. - */ - function charsEndIndex(strSymbols, chrSymbols) { - var index = strSymbols.length; - - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } - - /** - * Gets the number of `placeholder` occurrences in `array`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} placeholder The placeholder to search for. - * @returns {number} Returns the placeholder count. - */ - function countHolders(array, placeholder) { - var length = array.length, - result = 0; - - while (length--) { - if (array[length] === placeholder) { - ++result; - } - } - return result; - } - - /** - * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A - * letters to basic Latin letters. - * - * @private - * @param {string} letter The matched letter to deburr. - * @returns {string} Returns the deburred letter. - */ - var deburrLetter = basePropertyOf(deburredLetters); - - /** - * Used by `_.escape` to convert characters to HTML entities. - * - * @private - * @param {string} chr The matched character to escape. - * @returns {string} Returns the escaped character. - */ - var escapeHtmlChar = basePropertyOf(htmlEscapes); - - /** - * Used by `_.template` to escape characters for inclusion in compiled string literals. - * - * @private - * @param {string} chr The matched character to escape. - * @returns {string} Returns the escaped character. - */ - function escapeStringChar(chr) { - return '\\' + stringEscapes[chr]; - } - - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function getValue(object, key) { - return object == null ? undefined : object[key]; - } - - /** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ - function hasUnicode(string) { - return reHasUnicode.test(string); - } - - /** - * Checks if `string` contains a word composed of Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a word is found, else `false`. - */ - function hasUnicodeWord(string) { - return reHasUnicodeWord.test(string); - } - - /** - * Converts `iterator` to an array. - * - * @private - * @param {Object} iterator The iterator to convert. - * @returns {Array} Returns the converted array. - */ - function iteratorToArray(iterator) { - var data, - result = []; - - while (!(data = iterator.next()).done) { - result.push(data.value); - } - return result; - } - - /** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ - function mapToArray(map) { - var index = -1, - result = Array(map.size); - - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } - - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - - /** - * Replaces all `placeholder` elements in `array` with an internal placeholder - * and returns an array of their indexes. - * - * @private - * @param {Array} array The array to modify. - * @param {*} placeholder The placeholder to replace. - * @returns {Array} Returns the new array of placeholder indexes. - */ - function replaceHolders(array, placeholder) { - var index = -1, - length = array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (value === placeholder || value === PLACEHOLDER) { - array[index] = PLACEHOLDER; - result[resIndex++] = index; - } - } - return result; - } - - /** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ - function setToArray(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } - - /** - * Converts `set` to its value-value pairs. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the value-value pairs. - */ - function setToPairs(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = [value, value]; - }); - return result; - } - - /** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; - } - - /** - * A specialized version of `_.lastIndexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function strictLastIndexOf(array, value, fromIndex) { - var index = fromIndex + 1; - while (index--) { - if (array[index] === value) { - return index; - } - } - return index; - } - - /** - * Gets the number of symbols in `string`. - * - * @private - * @param {string} string The string to inspect. - * @returns {number} Returns the string size. - */ - function stringSize(string) { - return hasUnicode(string) - ? unicodeSize(string) - : asciiSize(string); - } - - /** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function stringToArray(string) { - return hasUnicode(string) - ? unicodeToArray(string) - : asciiToArray(string); - } - - /** - * Used by `_.unescape` to convert HTML entities to characters. - * - * @private - * @param {string} chr The matched character to unescape. - * @returns {string} Returns the unescaped character. - */ - var unescapeHtmlChar = basePropertyOf(htmlUnescapes); - - /** - * Gets the size of a Unicode `string`. - * - * @private - * @param {string} string The string inspect. - * @returns {number} Returns the string size. - */ - function unicodeSize(string) { - var result = reUnicode.lastIndex = 0; - while (reUnicode.test(string)) { - ++result; - } - return result; - } - - /** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function unicodeToArray(string) { - return string.match(reUnicode) || []; - } - - /** - * Splits a Unicode `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ - function unicodeWords(string) { - return string.match(reUnicodeWord) || []; - } - - /*--------------------------------------------------------------------------*/ - - /** - * Create a new pristine `lodash` function using the `context` object. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Util - * @param {Object} [context=root] The context object. - * @returns {Function} Returns a new `lodash` function. - * @example - * - * _.mixin({ 'foo': _.constant('foo') }); - * - * var lodash = _.runInContext(); - * lodash.mixin({ 'bar': lodash.constant('bar') }); - * - * _.isFunction(_.foo); - * // => true - * _.isFunction(_.bar); - * // => false - * - * lodash.isFunction(lodash.foo); - * // => false - * lodash.isFunction(lodash.bar); - * // => true - * - * // Create a suped-up `defer` in Node.js. - * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; - */ - var runInContext = (function runInContext(context) { - context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); - - /** Built-in constructor references. */ - var Array = context.Array, - Date = context.Date, - Error = context.Error, - Function = context.Function, - Math = context.Math, - Object = context.Object, - RegExp = context.RegExp, - String = context.String, - TypeError = context.TypeError; - - /** Used for built-in method references. */ - var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; - - /** Used to detect overreaching core-js shims. */ - var coreJsData = context['__core-js_shared__']; - - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** Used to generate unique IDs. */ - var idCounter = 0; - - /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var nativeObjectToString = objectProto.toString; - - /** Used to infer the `Object` constructor. */ - var objectCtorString = funcToString.call(Object); - - /** Used to restore the original `_` reference in `_.noConflict`. */ - var oldDash = root._; - - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); - - /** Built-in value references. */ - var Buffer = moduleExports ? context.Buffer : undefined, - Symbol = context.Symbol, - Uint8Array = context.Uint8Array, - allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, - getPrototype = overArg(Object.getPrototypeOf, Object), - objectCreate = Object.create, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice, - spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, - symIterator = Symbol ? Symbol.iterator : undefined, - symToStringTag = Symbol ? Symbol.toStringTag : undefined; - - var defineProperty = (function() { - try { - var func = getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} - }()); - - /** Mocked built-ins. */ - var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, - ctxNow = Date && Date.now !== root.Date.now && Date.now, - ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeCeil = Math.ceil, - nativeFloor = Math.floor, - nativeGetSymbols = Object.getOwnPropertySymbols, - nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, - nativeIsFinite = context.isFinite, - nativeJoin = arrayProto.join, - nativeKeys = overArg(Object.keys, Object), - nativeMax = Math.max, - nativeMin = Math.min, - nativeNow = Date.now, - nativeParseInt = context.parseInt, - nativeRandom = Math.random, - nativeReverse = arrayProto.reverse; - - /* Built-in method references that are verified to be native. */ - var DataView = getNative(context, 'DataView'), - Map = getNative(context, 'Map'), - Promise = getNative(context, 'Promise'), - Set = getNative(context, 'Set'), - WeakMap = getNative(context, 'WeakMap'), - nativeCreate = getNative(Object, 'create'); - - /** Used to store function metadata. */ - var metaMap = WeakMap && new WeakMap; - - /** Used to lookup unminified function names. */ - var realNames = {}; - - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map), - promiseCtorString = toSource(Promise), - setCtorString = toSource(Set), - weakMapCtorString = toSource(WeakMap); - - /** Used to convert symbols to primitives and strings. */ - var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, - symbolToString = symbolProto ? symbolProto.toString : undefined; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a `lodash` object which wraps `value` to enable implicit method - * chain sequences. Methods that operate on and return arrays, collections, - * and functions can be chained together. Methods that retrieve a single value - * or may return a primitive value will automatically end the chain sequence - * and return the unwrapped value. Otherwise, the value must be unwrapped - * with `_#value`. - * - * Explicit chain sequences, which must be unwrapped with `_#value`, may be - * enabled using `_.chain`. - * - * The execution of chained methods is lazy, that is, it's deferred until - * `_#value` is implicitly or explicitly called. - * - * Lazy evaluation allows several methods to support shortcut fusion. - * Shortcut fusion is an optimization to merge iteratee calls; this avoids - * the creation of intermediate arrays and can greatly reduce the number of - * iteratee executions. Sections of a chain sequence qualify for shortcut - * fusion if the section is applied to an array and iteratees accept only - * one argument. The heuristic for whether a section qualifies for shortcut - * fusion is subject to change. - * - * Chaining is supported in custom builds as long as the `_#value` method is - * directly or indirectly included in the build. - * - * In addition to lodash methods, wrappers have `Array` and `String` methods. - * - * The wrapper `Array` methods are: - * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` - * - * The wrapper `String` methods are: - * `replace` and `split` - * - * The wrapper methods that support shortcut fusion are: - * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, - * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, - * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` - * - * The chainable wrapper methods are: - * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, - * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, - * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, - * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, - * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, - * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, - * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, - * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, - * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, - * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, - * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, - * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, - * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, - * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, - * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, - * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, - * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, - * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, - * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, - * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, - * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, - * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, - * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, - * `zipObject`, `zipObjectDeep`, and `zipWith` - * - * The wrapper methods that are **not** chainable by default are: - * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, - * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, - * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, - * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, - * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, - * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, - * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, - * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, - * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, - * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, - * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, - * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, - * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, - * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, - * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, - * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, - * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, - * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, - * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, - * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, - * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, - * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, - * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, - * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, - * `upperFirst`, `value`, and `words` - * - * @name _ - * @constructor - * @category Seq - * @param {*} value The value to wrap in a `lodash` instance. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * function square(n) { - * return n * n; - * } - * - * var wrapped = _([1, 2, 3]); - * - * // Returns an unwrapped value. - * wrapped.reduce(_.add); - * // => 6 - * - * // Returns a wrapped value. - * var squares = wrapped.map(square); - * - * _.isArray(squares); - * // => false - * - * _.isArray(squares.value()); - * // => true - */ - function lodash(value) { - if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { - if (value instanceof LodashWrapper) { - return value; - } - if (hasOwnProperty.call(value, '__wrapped__')) { - return wrapperClone(value); - } - } - return new LodashWrapper(value); - } - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} proto The object to inherit from. - * @returns {Object} Returns the new object. - */ - var baseCreate = (function() { - function object() {} - return function(proto) { - if (!isObject(proto)) { - return {}; - } - if (objectCreate) { - return objectCreate(proto); - } - object.prototype = proto; - var result = new object; - object.prototype = undefined; - return result; - }; - }()); - - /** - * The function whose prototype chain sequence wrappers inherit from. - * - * @private - */ - function baseLodash() { - // No operation performed. - } - - /** - * The base constructor for creating `lodash` wrapper objects. - * - * @private - * @param {*} value The value to wrap. - * @param {boolean} [chainAll] Enable explicit method chain sequences. - */ - function LodashWrapper(value, chainAll) { - this.__wrapped__ = value; - this.__actions__ = []; - this.__chain__ = !!chainAll; - this.__index__ = 0; - this.__values__ = undefined; - } - - /** - * By default, the template delimiters used by lodash are like those in - * embedded Ruby (ERB) as well as ES2015 template strings. Change the - * following template settings to use alternative delimiters. - * - * @static - * @memberOf _ - * @type {Object} - */ - lodash.templateSettings = { - - /** - * Used to detect `data` property values to be HTML-escaped. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'escape': reEscape, - - /** - * Used to detect code to be evaluated. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'evaluate': reEvaluate, - - /** - * Used to detect `data` property values to inject. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'interpolate': reInterpolate, - - /** - * Used to reference the data object in the template text. - * - * @memberOf _.templateSettings - * @type {string} - */ - 'variable': '', - - /** - * Used to import variables into the compiled template. - * - * @memberOf _.templateSettings - * @type {Object} - */ - 'imports': { - - /** - * A reference to the `lodash` function. - * - * @memberOf _.templateSettings.imports - * @type {Function} - */ - '_': lodash - } - }; - - // Ensure wrappers are instances of `baseLodash`. - lodash.prototype = baseLodash.prototype; - lodash.prototype.constructor = lodash; - - LodashWrapper.prototype = baseCreate(baseLodash.prototype); - LodashWrapper.prototype.constructor = LodashWrapper; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. - * - * @private - * @constructor - * @param {*} value The value to wrap. - */ - function LazyWrapper(value) { - this.__wrapped__ = value; - this.__actions__ = []; - this.__dir__ = 1; - this.__filtered__ = false; - this.__iteratees__ = []; - this.__takeCount__ = MAX_ARRAY_LENGTH; - this.__views__ = []; - } - - /** - * Creates a clone of the lazy wrapper object. - * - * @private - * @name clone - * @memberOf LazyWrapper - * @returns {Object} Returns the cloned `LazyWrapper` object. - */ - function lazyClone() { - var result = new LazyWrapper(this.__wrapped__); - result.__actions__ = copyArray(this.__actions__); - result.__dir__ = this.__dir__; - result.__filtered__ = this.__filtered__; - result.__iteratees__ = copyArray(this.__iteratees__); - result.__takeCount__ = this.__takeCount__; - result.__views__ = copyArray(this.__views__); - return result; - } - - /** - * Reverses the direction of lazy iteration. - * - * @private - * @name reverse - * @memberOf LazyWrapper - * @returns {Object} Returns the new reversed `LazyWrapper` object. - */ - function lazyReverse() { - if (this.__filtered__) { - var result = new LazyWrapper(this); - result.__dir__ = -1; - result.__filtered__ = true; - } else { - result = this.clone(); - result.__dir__ *= -1; - } - return result; - } - - /** - * Extracts the unwrapped value from its lazy wrapper. - * - * @private - * @name value - * @memberOf LazyWrapper - * @returns {*} Returns the unwrapped value. - */ - function lazyValue() { - var array = this.__wrapped__.value(), - dir = this.__dir__, - isArr = isArray(array), - isRight = dir < 0, - arrLength = isArr ? array.length : 0, - view = getView(0, arrLength, this.__views__), - start = view.start, - end = view.end, - length = end - start, - index = isRight ? end : (start - 1), - iteratees = this.__iteratees__, - iterLength = iteratees.length, - resIndex = 0, - takeCount = nativeMin(length, this.__takeCount__); - - if (!isArr || (!isRight && arrLength == length && takeCount == length)) { - return baseWrapperValue(array, this.__actions__); - } - var result = []; - - outer: - while (length-- && resIndex < takeCount) { - index += dir; - - var iterIndex = -1, - value = array[index]; - - while (++iterIndex < iterLength) { - var data = iteratees[iterIndex], - iteratee = data.iteratee, - type = data.type, - computed = iteratee(value); - - if (type == LAZY_MAP_FLAG) { - value = computed; - } else if (!computed) { - if (type == LAZY_FILTER_FLAG) { - continue outer; - } else { - break outer; - } - } - } - result[resIndex++] = value; - } - return result; - } - - // Ensure `LazyWrapper` is an instance of `baseLodash`. - LazyWrapper.prototype = baseCreate(baseLodash.prototype); - LazyWrapper.prototype.constructor = LazyWrapper; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; - } - - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; - } - - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty.call(data, key) ? data[key] : undefined; - } - - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); - } - - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; - } - - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - - /*------------------------------------------------------------------------*/ - - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - this.size = 0; - } - - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; - } - - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; - } - - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ - function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } - - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function MapCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear() { - this.size = 0; - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; - } - - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete(key) { - var result = getMapData(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; - } - - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet(key, value) { - var data = getMapData(this, key), - size = data.size; - - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; - } - - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - - /*------------------------------------------------------------------------*/ - - /** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ - function SetCache(values) { - var index = -1, - length = values == null ? 0 : values.length; - - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); - } - } - - /** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ - function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; - } - - /** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ - function setCacheHas(value) { - return this.__data__.has(value); - } - - // Add methods to `SetCache`. - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Stack(entries) { - var data = this.__data__ = new ListCache(entries); - this.size = data.size; - } - - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - this.size = 0; - } - - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function stackDelete(key) { - var data = this.__data__, - result = data['delete'](key); - - this.size = data.size; - return result; - } - - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function stackGet(key) { - return this.__data__.get(key); - } - - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function stackHas(key) { - return this.__data__.has(key); - } - - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ - function stackSet(key, value) { - var data = this.__data__; - if (data instanceof ListCache) { - var pairs = data.__data__; - if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache(pairs); - } - data.set(key, value); - this.size = data.size; - return this; - } - - // Add methods to `Stack`. - Stack.prototype.clear = stackClear; - Stack.prototype['delete'] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - - /*------------------------------------------------------------------------*/ - - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; - - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); - } - } - return result; - } - - /** - * A specialized version of `_.sample` for arrays. - * - * @private - * @param {Array} array The array to sample. - * @returns {*} Returns the random element. - */ - function arraySample(array) { - var length = array.length; - return length ? array[baseRandom(0, length - 1)] : undefined; - } - - /** - * A specialized version of `_.sampleSize` for arrays. - * - * @private - * @param {Array} array The array to sample. - * @param {number} n The number of elements to sample. - * @returns {Array} Returns the random elements. - */ - function arraySampleSize(array, n) { - return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); - } - - /** - * A specialized version of `_.shuffle` for arrays. - * - * @private - * @param {Array} array The array to shuffle. - * @returns {Array} Returns the new shuffled array. - */ - function arrayShuffle(array) { - return shuffleSelf(copyArray(array)); - } - - /** - * This function is like `assignValue` except that it doesn't assign - * `undefined` values. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignMergeValue(object, key, value) { - if ((value !== undefined && !eq(object[key], value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } - - /** - * Aggregates elements of `collection` on `accumulator` with keys transformed - * by `iteratee` and values set by `setter`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform keys. - * @param {Object} accumulator The initial aggregated object. - * @returns {Function} Returns `accumulator`. - */ - function baseAggregator(collection, setter, iteratee, accumulator) { - baseEach(collection, function(value, key, collection) { - setter(accumulator, value, iteratee(value), collection); - }); - return accumulator; - } - - /** - * The base implementation of `_.assign` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssign(object, source) { - return object && copyObject(source, keys(source), object); - } - - /** - * The base implementation of `_.assignIn` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssignIn(object, source) { - return object && copyObject(source, keysIn(source), object); - } - - /** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function baseAssignValue(object, key, value) { - if (key == '__proto__' && defineProperty) { - defineProperty(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } - } - - /** - * The base implementation of `_.at` without support for individual paths. - * - * @private - * @param {Object} object The object to iterate over. - * @param {string[]} paths The property paths to pick. - * @returns {Array} Returns the picked elements. - */ - function baseAt(object, paths) { - var index = -1, - length = paths.length, - result = Array(length), - skip = object == null; - - while (++index < length) { - result[index] = skip ? undefined : get(object, paths[index]); - } - return result; - } - - /** - * The base implementation of `_.clamp` which doesn't coerce arguments. - * - * @private - * @param {number} number The number to clamp. - * @param {number} [lower] The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the clamped number. - */ - function baseClamp(number, lower, upper) { - if (number === number) { - if (upper !== undefined) { - number = number <= upper ? number : upper; - } - if (lower !== undefined) { - number = number >= lower ? number : lower; - } - } - return number; - } - - /** - * The base implementation of `_.clone` and `_.cloneDeep` which tracks - * traversed objects. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} bitmask The bitmask flags. - * 1 - Deep clone - * 2 - Flatten inherited properties - * 4 - Clone symbols - * @param {Function} [customizer] The function to customize cloning. - * @param {string} [key] The key of `value`. - * @param {Object} [object] The parent object of `value`. - * @param {Object} [stack] Tracks traversed objects and their clone counterparts. - * @returns {*} Returns the cloned value. - */ - function baseClone(value, bitmask, customizer, key, object, stack) { - var result, - isDeep = bitmask & CLONE_DEEP_FLAG, - isFlat = bitmask & CLONE_FLAT_FLAG, - isFull = bitmask & CLONE_SYMBOLS_FLAG; - - if (customizer) { - result = object ? customizer(value, key, object, stack) : customizer(value); - } - if (result !== undefined) { - return result; - } - if (!isObject(value)) { - return value; - } - var isArr = isArray(value); - if (isArr) { - result = initCloneArray(value); - if (!isDeep) { - return copyArray(value, result); - } - } else { - var tag = getTag(value), - isFunc = tag == funcTag || tag == genTag; - - if (isBuffer(value)) { - return cloneBuffer(value, isDeep); - } - if (tag == objectTag || tag == argsTag || (isFunc && !object)) { - result = (isFlat || isFunc) ? {} : initCloneObject(value); - if (!isDeep) { - return isFlat - ? copySymbolsIn(value, baseAssignIn(result, value)) - : copySymbols(value, baseAssign(result, value)); - } - } else { - if (!cloneableTags[tag]) { - return object ? value : {}; - } - result = initCloneByTag(value, tag, isDeep); - } - } - // Check for circular references and return its corresponding clone. - stack || (stack = new Stack); - var stacked = stack.get(value); - if (stacked) { - return stacked; - } - stack.set(value, result); - - if (isSet(value)) { - value.forEach(function(subValue) { - result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); - }); - } else if (isMap(value)) { - value.forEach(function(subValue, key) { - result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); - }); - } - - var keysFunc = isFull - ? (isFlat ? getAllKeysIn : getAllKeys) - : (isFlat ? keysIn : keys); - - var props = isArr ? undefined : keysFunc(value); - arrayEach(props || value, function(subValue, key) { - if (props) { - key = subValue; - subValue = value[key]; - } - // Recursively populate clone (susceptible to call stack limits). - assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); - }); - return result; - } - - /** - * The base implementation of `_.conforms` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property predicates to conform to. - * @returns {Function} Returns the new spec function. - */ - function baseConforms(source) { - var props = keys(source); - return function(object) { - return baseConformsTo(object, source, props); - }; - } - - /** - * The base implementation of `_.conformsTo` which accepts `props` to check. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property predicates to conform to. - * @returns {boolean} Returns `true` if `object` conforms, else `false`. - */ - function baseConformsTo(object, source, props) { - var length = props.length; - if (object == null) { - return !length; - } - object = Object(object); - while (length--) { - var key = props[length], - predicate = source[key], - value = object[key]; - - if ((value === undefined && !(key in object)) || !predicate(value)) { - return false; - } - } - return true; - } - - /** - * The base implementation of `_.delay` and `_.defer` which accepts `args` - * to provide to `func`. - * - * @private - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {Array} args The arguments to provide to `func`. - * @returns {number|Object} Returns the timer id or timeout object. - */ - function baseDelay(func, wait, args) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return setTimeout(function() { func.apply(undefined, args); }, wait); - } - - /** - * The base implementation of methods like `_.difference` without support - * for excluding multiple arrays or iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Array} values The values to exclude. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - */ - function baseDifference(array, values, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - isCommon = true, - length = array.length, - result = [], - valuesLength = values.length; - - if (!length) { - return result; - } - if (iteratee) { - values = arrayMap(values, baseUnary(iteratee)); - } - if (comparator) { - includes = arrayIncludesWith; - isCommon = false; - } - else if (values.length >= LARGE_ARRAY_SIZE) { - includes = cacheHas; - isCommon = false; - values = new SetCache(values); - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee == null ? value : iteratee(value); - - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var valuesIndex = valuesLength; - while (valuesIndex--) { - if (values[valuesIndex] === computed) { - continue outer; - } - } - result.push(value); - } - else if (!includes(values, computed, comparator)) { - result.push(value); - } - } - return result; - } - - /** - * The base implementation of `_.forEach` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ - var baseEach = createBaseEach(baseForOwn); - - /** - * The base implementation of `_.forEachRight` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ - var baseEachRight = createBaseEach(baseForOwnRight, true); - - /** - * The base implementation of `_.every` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false` - */ - function baseEvery(collection, predicate) { - var result = true; - baseEach(collection, function(value, index, collection) { - result = !!predicate(value, index, collection); - return result; - }); - return result; - } - - /** - * The base implementation of methods like `_.max` and `_.min` which accepts a - * `comparator` to determine the extremum value. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The iteratee invoked per iteration. - * @param {Function} comparator The comparator used to compare values. - * @returns {*} Returns the extremum value. - */ - function baseExtremum(array, iteratee, comparator) { - var index = -1, - length = array.length; - - while (++index < length) { - var value = array[index], - current = iteratee(value); - - if (current != null && (computed === undefined - ? (current === current && !isSymbol(current)) - : comparator(current, computed) - )) { - var computed = current, - result = value; - } - } - return result; - } - - /** - * The base implementation of `_.fill` without an iteratee call guard. - * - * @private - * @param {Array} array The array to fill. - * @param {*} value The value to fill `array` with. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns `array`. - */ - function baseFill(array, value, start, end) { - var length = array.length; - - start = toInteger(start); - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = (end === undefined || end > length) ? length : toInteger(end); - if (end < 0) { - end += length; - } - end = start > end ? 0 : toLength(end); - while (start < end) { - array[start++] = value; - } - return array; - } - - /** - * The base implementation of `_.filter` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function baseFilter(collection, predicate) { - var result = []; - baseEach(collection, function(value, index, collection) { - if (predicate(value, index, collection)) { - result.push(value); - } - }); - return result; - } - - /** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ - function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; - - predicate || (predicate = isFlattenable); - result || (result = []); - - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, depth - 1, predicate, isStrict, result); - } else { - arrayPush(result, value); - } - } else if (!isStrict) { - result[result.length] = value; - } - } - return result; - } - - /** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseFor = createBaseFor(); - - /** - * This function is like `baseFor` except that it iterates over properties - * in the opposite order. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseForRight = createBaseFor(true); - - /** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); - } - - /** - * The base implementation of `_.forOwnRight` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwnRight(object, iteratee) { - return object && baseForRight(object, iteratee, keys); - } - - /** - * The base implementation of `_.functions` which creates an array of - * `object` function property names filtered from `props`. - * - * @private - * @param {Object} object The object to inspect. - * @param {Array} props The property names to filter. - * @returns {Array} Returns the function names. - */ - function baseFunctions(object, props) { - return arrayFilter(props, function(key) { - return isFunction(object[key]); - }); - } - - /** - * The base implementation of `_.get` without support for default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @returns {*} Returns the resolved value. - */ - function baseGet(object, path) { - path = castPath(path, object); - - var index = 0, - length = path.length; - - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - return (index && index == length) ? object : undefined; - } - - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); - } - - /** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag && symToStringTag in Object(value)) - ? getRawTag(value) - : objectToString(value); - } - - /** - * The base implementation of `_.gt` which doesn't coerce arguments. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than `other`, - * else `false`. - */ - function baseGt(value, other) { - return value > other; - } - - /** - * The base implementation of `_.has` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHas(object, key) { - return object != null && hasOwnProperty.call(object, key); - } - - /** - * The base implementation of `_.hasIn` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHasIn(object, key) { - return object != null && key in Object(object); - } - - /** - * The base implementation of `_.inRange` which doesn't coerce arguments. - * - * @private - * @param {number} number The number to check. - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @returns {boolean} Returns `true` if `number` is in the range, else `false`. - */ - function baseInRange(number, start, end) { - return number >= nativeMin(start, end) && number < nativeMax(start, end); - } - - /** - * The base implementation of methods like `_.intersection`, without support - * for iteratee shorthands, that accepts an array of arrays to inspect. - * - * @private - * @param {Array} arrays The arrays to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of shared values. - */ - function baseIntersection(arrays, iteratee, comparator) { - var includes = comparator ? arrayIncludesWith : arrayIncludes, - length = arrays[0].length, - othLength = arrays.length, - othIndex = othLength, - caches = Array(othLength), - maxLength = Infinity, - result = []; - - while (othIndex--) { - var array = arrays[othIndex]; - if (othIndex && iteratee) { - array = arrayMap(array, baseUnary(iteratee)); - } - maxLength = nativeMin(array.length, maxLength); - caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) - ? new SetCache(othIndex && array) - : undefined; - } - array = arrays[0]; - - var index = -1, - seen = caches[0]; - - outer: - while (++index < length && result.length < maxLength) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; - - value = (comparator || value !== 0) ? value : 0; - if (!(seen - ? cacheHas(seen, computed) - : includes(result, computed, comparator) - )) { - othIndex = othLength; - while (--othIndex) { - var cache = caches[othIndex]; - if (!(cache - ? cacheHas(cache, computed) - : includes(arrays[othIndex], computed, comparator)) - ) { - continue outer; - } - } - if (seen) { - seen.push(computed); - } - result.push(value); - } - } - return result; - } - - /** - * The base implementation of `_.invert` and `_.invertBy` which inverts - * `object` with values transformed by `iteratee` and set by `setter`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform values. - * @param {Object} accumulator The initial inverted object. - * @returns {Function} Returns `accumulator`. - */ - function baseInverter(object, setter, iteratee, accumulator) { - baseForOwn(object, function(value, key, object) { - setter(accumulator, iteratee(value), key, object); - }); - return accumulator; - } - - /** - * The base implementation of `_.invoke` without support for individual - * method arguments. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the method to invoke. - * @param {Array} args The arguments to invoke the method with. - * @returns {*} Returns the result of the invoked method. - */ - function baseInvoke(object, path, args) { - path = castPath(path, object); - object = parent(object, path); - var func = object == null ? object : object[toKey(last(path))]; - return func == null ? undefined : apply(func, object, args); - } - - /** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ - function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; - } - - /** - * The base implementation of `_.isArrayBuffer` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. - */ - function baseIsArrayBuffer(value) { - return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; - } - - /** - * The base implementation of `_.isDate` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a date object, else `false`. - */ - function baseIsDate(value) { - return isObjectLike(value) && baseGetTag(value) == dateTag; - } - - /** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {boolean} bitmask The bitmask flags. - * 1 - Unordered comparison - * 2 - Partial comparison - * @param {Function} [customizer] The function to customize comparisons. - * @param {Object} [stack] Tracks traversed `value` and `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ - function baseIsEqual(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); - } - - /** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} [stack] Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray(object), - othIsArr = isArray(other), - objTag = objIsArr ? arrayTag : getTag(object), - othTag = othIsArr ? arrayTag : getTag(other); - - objTag = objTag == argsTag ? objectTag : objTag; - othTag = othTag == argsTag ? objectTag : othTag; - - var objIsObj = objTag == objectTag, - othIsObj = othTag == objectTag, - isSameTag = objTag == othTag; - - if (isSameTag && isBuffer(object)) { - if (!isBuffer(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack); - return (objIsArr || isTypedArray(object)) - ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) - : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG)) { - var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); - - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; - - stack || (stack = new Stack); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); - } - - /** - * The base implementation of `_.isMap` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. - */ - function baseIsMap(value) { - return isObjectLike(value) && getTag(value) == mapTag; - } - - /** - * The base implementation of `_.isMatch` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Array} matchData The property names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ - function baseIsMatch(object, source, matchData, customizer) { - var index = matchData.length, - length = index, - noCustomizer = !customizer; - - if (object == null) { - return !length; - } - object = Object(object); - while (index--) { - var data = matchData[index]; - if ((noCustomizer && data[2]) - ? data[1] !== object[data[0]] - : !(data[0] in object) - ) { - return false; - } - } - while (++index < length) { - data = matchData[index]; - var key = data[0], - objValue = object[key], - srcValue = data[1]; - - if (noCustomizer && data[2]) { - if (objValue === undefined && !(key in object)) { - return false; - } - } else { - var stack = new Stack; - if (customizer) { - var result = customizer(objValue, srcValue, key, object, source, stack); - } - if (!(result === undefined - ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) - : result - )) { - return false; - } - } - } - return true; - } - - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - - /** - * The base implementation of `_.isRegExp` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - */ - function baseIsRegExp(value) { - return isObjectLike(value) && baseGetTag(value) == regexpTag; - } - - /** - * The base implementation of `_.isSet` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. - */ - function baseIsSet(value) { - return isObjectLike(value) && getTag(value) == setTag; - } - - /** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ - function baseIsTypedArray(value) { - return isObjectLike(value) && - isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; - } - - /** - * The base implementation of `_.iteratee`. - * - * @private - * @param {*} [value=_.identity] The value to convert to an iteratee. - * @returns {Function} Returns the iteratee. - */ - function baseIteratee(value) { - // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. - // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. - if (typeof value == 'function') { - return value; - } - if (value == null) { - return identity; - } - if (typeof value == 'object') { - return isArray(value) - ? baseMatchesProperty(value[0], value[1]) - : baseMatches(value); - } - return property(value); - } - - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; - } - - /** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeysIn(object) { - if (!isObject(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype(object), - result = []; - - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); - } - } - return result; - } - - /** - * The base implementation of `_.lt` which doesn't coerce arguments. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than `other`, - * else `false`. - */ - function baseLt(value, other) { - return value < other; - } - - /** - * The base implementation of `_.map` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function baseMap(collection, iteratee) { - var index = -1, - result = isArrayLike(collection) ? Array(collection.length) : []; - - baseEach(collection, function(value, key, collection) { - result[++index] = iteratee(value, key, collection); - }); - return result; - } - - /** - * The base implementation of `_.matches` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatches(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - return matchesStrictComparable(matchData[0][0], matchData[0][1]); - } - return function(object) { - return object === source || baseIsMatch(object, source, matchData); - }; - } - - /** - * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. - * - * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatchesProperty(path, srcValue) { - if (isKey(path) && isStrictComparable(srcValue)) { - return matchesStrictComparable(toKey(path), srcValue); - } - return function(object) { - var objValue = get(object, path); - return (objValue === undefined && objValue === srcValue) - ? hasIn(object, path) - : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); - }; - } - - /** - * The base implementation of `_.merge` without support for multiple sources. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {number} srcIndex The index of `source`. - * @param {Function} [customizer] The function to customize merged values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMerge(object, source, srcIndex, customizer, stack) { - if (object === source) { - return; - } - baseFor(source, function(srcValue, key) { - stack || (stack = new Stack); - if (isObject(srcValue)) { - baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); - } - else { - var newValue = customizer - ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) - : undefined; - - if (newValue === undefined) { - newValue = srcValue; - } - assignMergeValue(object, key, newValue); - } - }, keysIn); - } - - /** - * A specialized version of `baseMerge` for arrays and objects which performs - * deep merges and tracks traversed objects enabling objects with circular - * references to be merged. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {string} key The key of the value to merge. - * @param {number} srcIndex The index of `source`. - * @param {Function} mergeFunc The function to merge values. - * @param {Function} [customizer] The function to customize assigned values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { - var objValue = safeGet(object, key), - srcValue = safeGet(source, key), - stacked = stack.get(srcValue); - - if (stacked) { - assignMergeValue(object, key, stacked); - return; - } - var newValue = customizer - ? customizer(objValue, srcValue, (key + ''), object, source, stack) - : undefined; - - var isCommon = newValue === undefined; - - if (isCommon) { - var isArr = isArray(srcValue), - isBuff = !isArr && isBuffer(srcValue), - isTyped = !isArr && !isBuff && isTypedArray(srcValue); - - newValue = srcValue; - if (isArr || isBuff || isTyped) { - if (isArray(objValue)) { - newValue = objValue; - } - else if (isArrayLikeObject(objValue)) { - newValue = copyArray(objValue); - } - else if (isBuff) { - isCommon = false; - newValue = cloneBuffer(srcValue, true); - } - else if (isTyped) { - isCommon = false; - newValue = cloneTypedArray(srcValue, true); - } - else { - newValue = []; - } - } - else if (isPlainObject(srcValue) || isArguments(srcValue)) { - newValue = objValue; - if (isArguments(objValue)) { - newValue = toPlainObject(objValue); - } - else if (!isObject(objValue) || isFunction(objValue)) { - newValue = initCloneObject(srcValue); - } - } - else { - isCommon = false; - } - } - if (isCommon) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, newValue); - mergeFunc(newValue, srcValue, srcIndex, customizer, stack); - stack['delete'](srcValue); - } - assignMergeValue(object, key, newValue); - } - - /** - * The base implementation of `_.nth` which doesn't coerce arguments. - * - * @private - * @param {Array} array The array to query. - * @param {number} n The index of the element to return. - * @returns {*} Returns the nth element of `array`. - */ - function baseNth(array, n) { - var length = array.length; - if (!length) { - return; - } - n += n < 0 ? length : 0; - return isIndex(n, length) ? array[n] : undefined; - } - - /** - * The base implementation of `_.orderBy` without param guards. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. - * @param {string[]} orders The sort orders of `iteratees`. - * @returns {Array} Returns the new sorted array. - */ - function baseOrderBy(collection, iteratees, orders) { - if (iteratees.length) { - iteratees = arrayMap(iteratees, function(iteratee) { - if (isArray(iteratee)) { - return function(value) { - return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); - } - } - return iteratee; - }); - } else { - iteratees = [identity]; - } - - var index = -1; - iteratees = arrayMap(iteratees, baseUnary(getIteratee())); - - var result = baseMap(collection, function(value, key, collection) { - var criteria = arrayMap(iteratees, function(iteratee) { - return iteratee(value); - }); - return { 'criteria': criteria, 'index': ++index, 'value': value }; - }); - - return baseSortBy(result, function(object, other) { - return compareMultiple(object, other, orders); - }); - } - - /** - * The base implementation of `_.pick` without support for individual - * property identifiers. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @returns {Object} Returns the new object. - */ - function basePick(object, paths) { - return basePickBy(object, paths, function(value, path) { - return hasIn(object, path); - }); - } - - /** - * The base implementation of `_.pickBy` without support for iteratee shorthands. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @param {Function} predicate The function invoked per property. - * @returns {Object} Returns the new object. - */ - function basePickBy(object, paths, predicate) { - var index = -1, - length = paths.length, - result = {}; - - while (++index < length) { - var path = paths[index], - value = baseGet(object, path); - - if (predicate(value, path)) { - baseSet(result, castPath(path, object), value); - } - } - return result; - } - - /** - * A specialized version of `baseProperty` which supports deep paths. - * - * @private - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function basePropertyDeep(path) { - return function(object) { - return baseGet(object, path); - }; - } - - /** - * The base implementation of `_.pullAllBy` without support for iteratee - * shorthands. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns `array`. - */ - function basePullAll(array, values, iteratee, comparator) { - var indexOf = comparator ? baseIndexOfWith : baseIndexOf, - index = -1, - length = values.length, - seen = array; - - if (array === values) { - values = copyArray(values); - } - if (iteratee) { - seen = arrayMap(array, baseUnary(iteratee)); - } - while (++index < length) { - var fromIndex = 0, - value = values[index], - computed = iteratee ? iteratee(value) : value; - - while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { - if (seen !== array) { - splice.call(seen, fromIndex, 1); - } - splice.call(array, fromIndex, 1); - } - } - return array; - } - - /** - * The base implementation of `_.pullAt` without support for individual - * indexes or capturing the removed elements. - * - * @private - * @param {Array} array The array to modify. - * @param {number[]} indexes The indexes of elements to remove. - * @returns {Array} Returns `array`. - */ - function basePullAt(array, indexes) { - var length = array ? indexes.length : 0, - lastIndex = length - 1; - - while (length--) { - var index = indexes[length]; - if (length == lastIndex || index !== previous) { - var previous = index; - if (isIndex(index)) { - splice.call(array, index, 1); - } else { - baseUnset(array, index); - } - } - } - return array; - } - - /** - * The base implementation of `_.random` without support for returning - * floating-point numbers. - * - * @private - * @param {number} lower The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the random number. - */ - function baseRandom(lower, upper) { - return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); - } - - /** - * The base implementation of `_.range` and `_.rangeRight` which doesn't - * coerce arguments. - * - * @private - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @param {number} step The value to increment or decrement by. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the range of numbers. - */ - function baseRange(start, end, step, fromRight) { - var index = -1, - length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), - result = Array(length); - - while (length--) { - result[fromRight ? length : ++index] = start; - start += step; - } - return result; - } - - /** - * The base implementation of `_.repeat` which doesn't coerce arguments. - * - * @private - * @param {string} string The string to repeat. - * @param {number} n The number of times to repeat the string. - * @returns {string} Returns the repeated string. - */ - function baseRepeat(string, n) { - var result = ''; - if (!string || n < 1 || n > MAX_SAFE_INTEGER) { - return result; - } - // Leverage the exponentiation by squaring algorithm for a faster repeat. - // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. - do { - if (n % 2) { - result += string; - } - n = nativeFloor(n / 2); - if (n) { - string += string; - } - } while (n); - - return result; - } - - /** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ - function baseRest(func, start) { - return setToString(overRest(func, start, identity), func + ''); - } - - /** - * The base implementation of `_.sample`. - * - * @private - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. - */ - function baseSample(collection) { - return arraySample(values(collection)); - } - - /** - * The base implementation of `_.sampleSize` without param guards. - * - * @private - * @param {Array|Object} collection The collection to sample. - * @param {number} n The number of elements to sample. - * @returns {Array} Returns the random elements. - */ - function baseSampleSize(collection, n) { - var array = values(collection); - return shuffleSelf(array, baseClamp(n, 0, array.length)); - } - - /** - * The base implementation of `_.set`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ - function baseSet(object, path, value, customizer) { - if (!isObject(object)) { - return object; - } - path = castPath(path, object); - - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; - - while (nested != null && ++index < length) { - var key = toKey(path[index]), - newValue = value; - - if (key === '__proto__' || key === 'constructor' || key === 'prototype') { - return object; - } - - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined; - if (newValue === undefined) { - newValue = isObject(objValue) - ? objValue - : (isIndex(path[index + 1]) ? [] : {}); - } - } - assignValue(nested, key, newValue); - nested = nested[key]; - } - return object; - } - - /** - * The base implementation of `setData` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. - */ - var baseSetData = !metaMap ? identity : function(func, data) { - metaMap.set(func, data); - return func; - }; - - /** - * The base implementation of `setToString` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var baseSetToString = !defineProperty ? identity : function(func, string) { - return defineProperty(func, 'toString', { - 'configurable': true, - 'enumerable': false, - 'value': constant(string), - 'writable': true - }); - }; - - /** - * The base implementation of `_.shuffle`. - * - * @private - * @param {Array|Object} collection The collection to shuffle. - * @returns {Array} Returns the new shuffled array. - */ - function baseShuffle(collection) { - return shuffleSelf(values(collection)); - } - - /** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ - function baseSlice(array, start, end) { - var index = -1, - length = array.length; - - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; - - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; - } - - /** - * The base implementation of `_.some` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function baseSome(collection, predicate) { - var result; - - baseEach(collection, function(value, index, collection) { - result = predicate(value, index, collection); - return !result; - }); - return !!result; - } - - /** - * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which - * performs a binary search of `array` to determine the index at which `value` - * should be inserted into `array` in order to maintain its sort order. - * - * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - */ - function baseSortedIndex(array, value, retHighest) { - var low = 0, - high = array == null ? low : array.length; - - if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { - while (low < high) { - var mid = (low + high) >>> 1, - computed = array[mid]; - - if (computed !== null && !isSymbol(computed) && - (retHighest ? (computed <= value) : (computed < value))) { - low = mid + 1; - } else { - high = mid; - } - } - return high; - } - return baseSortedIndexBy(array, value, identity, retHighest); - } - - /** - * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` - * which invokes `iteratee` for `value` and each element of `array` to compute - * their sort ranking. The iteratee is invoked with one argument; (value). - * - * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} iteratee The iteratee invoked per element. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - */ - function baseSortedIndexBy(array, value, iteratee, retHighest) { - var low = 0, - high = array == null ? 0 : array.length; - if (high === 0) { - return 0; - } - - value = iteratee(value); - var valIsNaN = value !== value, - valIsNull = value === null, - valIsSymbol = isSymbol(value), - valIsUndefined = value === undefined; - - while (low < high) { - var mid = nativeFloor((low + high) / 2), - computed = iteratee(array[mid]), - othIsDefined = computed !== undefined, - othIsNull = computed === null, - othIsReflexive = computed === computed, - othIsSymbol = isSymbol(computed); - - if (valIsNaN) { - var setLow = retHighest || othIsReflexive; - } else if (valIsUndefined) { - setLow = othIsReflexive && (retHighest || othIsDefined); - } else if (valIsNull) { - setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); - } else if (valIsSymbol) { - setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); - } else if (othIsNull || othIsSymbol) { - setLow = false; - } else { - setLow = retHighest ? (computed <= value) : (computed < value); - } - if (setLow) { - low = mid + 1; - } else { - high = mid; - } - } - return nativeMin(high, MAX_ARRAY_INDEX); - } - - /** - * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - */ - function baseSortedUniq(array, iteratee) { - var index = -1, - length = array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; - - if (!index || !eq(computed, seen)) { - var seen = computed; - result[resIndex++] = value === 0 ? 0 : value; - } - } - return result; - } - - /** - * The base implementation of `_.toNumber` which doesn't ensure correct - * conversions of binary, hexadecimal, or octal string values. - * - * @private - * @param {*} value The value to process. - * @returns {number} Returns the number. - */ - function baseToNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - return +value; - } - - /** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ - function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap(value, baseToString) + ''; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; - } - - /** - * The base implementation of `_.uniqBy` without support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - */ - function baseUniq(array, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - length = array.length, - isCommon = true, - result = [], - seen = result; - - if (comparator) { - isCommon = false; - includes = arrayIncludesWith; - } - else if (length >= LARGE_ARRAY_SIZE) { - var set = iteratee ? null : createSet(array); - if (set) { - return setToArray(set); - } - isCommon = false; - includes = cacheHas; - seen = new SetCache; - } - else { - seen = iteratee ? [] : result; - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; - - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var seenIndex = seen.length; - while (seenIndex--) { - if (seen[seenIndex] === computed) { - continue outer; - } - } - if (iteratee) { - seen.push(computed); - } - result.push(value); - } - else if (!includes(seen, computed, comparator)) { - if (seen !== result) { - seen.push(computed); - } - result.push(value); - } - } - return result; - } - - /** - * The base implementation of `_.unset`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The property path to unset. - * @returns {boolean} Returns `true` if the property is deleted, else `false`. - */ - function baseUnset(object, path) { - path = castPath(path, object); - object = parent(object, path); - return object == null || delete object[toKey(last(path))]; - } - - /** - * The base implementation of `_.update`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to update. - * @param {Function} updater The function to produce the updated value. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ - function baseUpdate(object, path, updater, customizer) { - return baseSet(object, path, updater(baseGet(object, path)), customizer); - } - - /** - * The base implementation of methods like `_.dropWhile` and `_.takeWhile` - * without support for iteratee shorthands. - * - * @private - * @param {Array} array The array to query. - * @param {Function} predicate The function invoked per iteration. - * @param {boolean} [isDrop] Specify dropping elements instead of taking them. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the slice of `array`. - */ - function baseWhile(array, predicate, isDrop, fromRight) { - var length = array.length, - index = fromRight ? length : -1; - - while ((fromRight ? index-- : ++index < length) && - predicate(array[index], index, array)) {} - - return isDrop - ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) - : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); - } - - /** - * The base implementation of `wrapperValue` which returns the result of - * performing a sequence of actions on the unwrapped `value`, where each - * successive action is supplied the return value of the previous. - * - * @private - * @param {*} value The unwrapped value. - * @param {Array} actions Actions to perform to resolve the unwrapped value. - * @returns {*} Returns the resolved value. - */ - function baseWrapperValue(value, actions) { - var result = value; - if (result instanceof LazyWrapper) { - result = result.value(); - } - return arrayReduce(actions, function(result, action) { - return action.func.apply(action.thisArg, arrayPush([result], action.args)); - }, result); - } - - /** - * The base implementation of methods like `_.xor`, without support for - * iteratee shorthands, that accepts an array of arrays to inspect. - * - * @private - * @param {Array} arrays The arrays to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of values. - */ - function baseXor(arrays, iteratee, comparator) { - var length = arrays.length; - if (length < 2) { - return length ? baseUniq(arrays[0]) : []; - } - var index = -1, - result = Array(length); - - while (++index < length) { - var array = arrays[index], - othIndex = -1; - - while (++othIndex < length) { - if (othIndex != index) { - result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); - } - } - } - return baseUniq(baseFlatten(result, 1), iteratee, comparator); - } - - /** - * This base implementation of `_.zipObject` which assigns values using `assignFunc`. - * - * @private - * @param {Array} props The property identifiers. - * @param {Array} values The property values. - * @param {Function} assignFunc The function to assign values. - * @returns {Object} Returns the new object. - */ - function baseZipObject(props, values, assignFunc) { - var index = -1, - length = props.length, - valsLength = values.length, - result = {}; - - while (++index < length) { - var value = index < valsLength ? values[index] : undefined; - assignFunc(result, props[index], value); - } - return result; - } - - /** - * Casts `value` to an empty array if it's not an array like object. - * - * @private - * @param {*} value The value to inspect. - * @returns {Array|Object} Returns the cast array-like object. - */ - function castArrayLikeObject(value) { - return isArrayLikeObject(value) ? value : []; - } - - /** - * Casts `value` to `identity` if it's not a function. - * - * @private - * @param {*} value The value to inspect. - * @returns {Function} Returns cast function. - */ - function castFunction(value) { - return typeof value == 'function' ? value : identity; - } - - /** - * Casts `value` to a path array if it's not one. - * - * @private - * @param {*} value The value to inspect. - * @param {Object} [object] The object to query keys on. - * @returns {Array} Returns the cast property path array. - */ - function castPath(value, object) { - if (isArray(value)) { - return value; - } - return isKey(value, object) ? [value] : stringToPath(toString(value)); - } - - /** - * A `baseRest` alias which can be replaced with `identity` by module - * replacement plugins. - * - * @private - * @type {Function} - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. - */ - var castRest = baseRest; - - /** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ - function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); - } - - /** - * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). - * - * @private - * @param {number|Object} id The timer id or timeout object of the timer to clear. - */ - var clearTimeout = ctxClearTimeout || function(id) { - return root.clearTimeout(id); - }; - - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var length = buffer.length, - result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); - - buffer.copy(result); - return result; - } - - /** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array(result).set(new Uint8Array(arrayBuffer)); - return result; - } - - /** - * Creates a clone of `dataView`. - * - * @private - * @param {Object} dataView The data view to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned data view. - */ - function cloneDataView(dataView, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; - return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); - } - - /** - * Creates a clone of `regexp`. - * - * @private - * @param {Object} regexp The regexp to clone. - * @returns {Object} Returns the cloned regexp. - */ - function cloneRegExp(regexp) { - var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); - result.lastIndex = regexp.lastIndex; - return result; - } - - /** - * Creates a clone of the `symbol` object. - * - * @private - * @param {Object} symbol The symbol object to clone. - * @returns {Object} Returns the cloned symbol object. - */ - function cloneSymbol(symbol) { - return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; - } - - /** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } - - /** - * Compares values to sort them in ascending order. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {number} Returns the sort order indicator for `value`. - */ - function compareAscending(value, other) { - if (value !== other) { - var valIsDefined = value !== undefined, - valIsNull = value === null, - valIsReflexive = value === value, - valIsSymbol = isSymbol(value); - - var othIsDefined = other !== undefined, - othIsNull = other === null, - othIsReflexive = other === other, - othIsSymbol = isSymbol(other); - - if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || - (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || - (valIsNull && othIsDefined && othIsReflexive) || - (!valIsDefined && othIsReflexive) || - !valIsReflexive) { - return 1; - } - if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || - (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || - (othIsNull && valIsDefined && valIsReflexive) || - (!othIsDefined && valIsReflexive) || - !othIsReflexive) { - return -1; - } - } - return 0; - } - - /** - * Used by `_.orderBy` to compare multiple properties of a value to another - * and stable sort them. - * - * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, - * specify an order of "desc" for descending or "asc" for ascending sort order - * of corresponding values. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {boolean[]|string[]} orders The order to sort by for each property. - * @returns {number} Returns the sort order indicator for `object`. - */ - function compareMultiple(object, other, orders) { - var index = -1, - objCriteria = object.criteria, - othCriteria = other.criteria, - length = objCriteria.length, - ordersLength = orders.length; - - while (++index < length) { - var result = compareAscending(objCriteria[index], othCriteria[index]); - if (result) { - if (index >= ordersLength) { - return result; - } - var order = orders[index]; - return result * (order == 'desc' ? -1 : 1); - } - } - // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications - // that causes it, under certain circumstances, to provide the same value for - // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 - // for more details. - // - // This also ensures a stable sort in V8 and other engines. - // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. - return object.index - other.index; - } - - /** - * Creates an array that is the composition of partially applied arguments, - * placeholders, and provided arguments into a single array of arguments. - * - * @private - * @param {Array} args The provided arguments. - * @param {Array} partials The arguments to prepend to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @params {boolean} [isCurried] Specify composing for a curried function. - * @returns {Array} Returns the new array of composed arguments. - */ - function composeArgs(args, partials, holders, isCurried) { - var argsIndex = -1, - argsLength = args.length, - holdersLength = holders.length, - leftIndex = -1, - leftLength = partials.length, - rangeLength = nativeMax(argsLength - holdersLength, 0), - result = Array(leftLength + rangeLength), - isUncurried = !isCurried; - - while (++leftIndex < leftLength) { - result[leftIndex] = partials[leftIndex]; - } - while (++argsIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result[holders[argsIndex]] = args[argsIndex]; - } - } - while (rangeLength--) { - result[leftIndex++] = args[argsIndex++]; - } - return result; - } - - /** - * This function is like `composeArgs` except that the arguments composition - * is tailored for `_.partialRight`. - * - * @private - * @param {Array} args The provided arguments. - * @param {Array} partials The arguments to append to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @params {boolean} [isCurried] Specify composing for a curried function. - * @returns {Array} Returns the new array of composed arguments. - */ - function composeArgsRight(args, partials, holders, isCurried) { - var argsIndex = -1, - argsLength = args.length, - holdersIndex = -1, - holdersLength = holders.length, - rightIndex = -1, - rightLength = partials.length, - rangeLength = nativeMax(argsLength - holdersLength, 0), - result = Array(rangeLength + rightLength), - isUncurried = !isCurried; - - while (++argsIndex < rangeLength) { - result[argsIndex] = args[argsIndex]; - } - var offset = argsIndex; - while (++rightIndex < rightLength) { - result[offset + rightIndex] = partials[rightIndex]; - } - while (++holdersIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result[offset + holders[holdersIndex]] = args[argsIndex++]; - } - } - return result; - } - - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function copyArray(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } - - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ - function copyObject(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; - - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object, key, newValue); - } else { - assignValue(object, key, newValue); - } - } - return object; - } - - /** - * Copies own symbols of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ - function copySymbols(source, object) { - return copyObject(source, getSymbols(source), object); - } - - /** - * Copies own and inherited symbols of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ - function copySymbolsIn(source, object) { - return copyObject(source, getSymbolsIn(source), object); - } - - /** - * Creates a function like `_.groupBy`. - * - * @private - * @param {Function} setter The function to set accumulator values. - * @param {Function} [initializer] The accumulator object initializer. - * @returns {Function} Returns the new aggregator function. - */ - function createAggregator(setter, initializer) { - return function(collection, iteratee) { - var func = isArray(collection) ? arrayAggregator : baseAggregator, - accumulator = initializer ? initializer() : {}; - - return func(collection, setter, getIteratee(iteratee, 2), accumulator); - }; - } - - /** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ - function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; - - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); - } - - /** - * Creates a `baseEach` or `baseEachRight` function. - * - * @private - * @param {Function} eachFunc The function to iterate over a collection. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseEach(eachFunc, fromRight) { - return function(collection, iteratee) { - if (collection == null) { - return collection; - } - if (!isArrayLike(collection)) { - return eachFunc(collection, iteratee); - } - var length = collection.length, - index = fromRight ? length : -1, - iterable = Object(collection); - - while ((fromRight ? index-- : ++index < length)) { - if (iteratee(iterable[index], index, iterable) === false) { - break; - } - } - return collection; - }; - } - - /** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; - - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; - } - - /** - * Creates a function that wraps `func` to invoke it with the optional `this` - * binding of `thisArg`. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} [thisArg] The `this` binding of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createBind(func, bitmask, thisArg) { - var isBind = bitmask & WRAP_BIND_FLAG, - Ctor = createCtor(func); - - function wrapper() { - var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - return fn.apply(isBind ? thisArg : this, arguments); - } - return wrapper; - } - - /** - * Creates a function like `_.lowerFirst`. - * - * @private - * @param {string} methodName The name of the `String` case method to use. - * @returns {Function} Returns the new case function. - */ - function createCaseFirst(methodName) { - return function(string) { - string = toString(string); - - var strSymbols = hasUnicode(string) - ? stringToArray(string) - : undefined; - - var chr = strSymbols - ? strSymbols[0] - : string.charAt(0); - - var trailing = strSymbols - ? castSlice(strSymbols, 1).join('') - : string.slice(1); - - return chr[methodName]() + trailing; - }; - } - - /** - * Creates a function like `_.camelCase`. - * - * @private - * @param {Function} callback The function to combine each word. - * @returns {Function} Returns the new compounder function. - */ - function createCompounder(callback) { - return function(string) { - return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); - }; - } - - /** - * Creates a function that produces an instance of `Ctor` regardless of - * whether it was invoked as part of a `new` expression or by `call` or `apply`. - * - * @private - * @param {Function} Ctor The constructor to wrap. - * @returns {Function} Returns the new wrapped function. - */ - function createCtor(Ctor) { - return function() { - // Use a `switch` statement to work with class constructors. See - // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist - // for more details. - var args = arguments; - switch (args.length) { - case 0: return new Ctor; - case 1: return new Ctor(args[0]); - case 2: return new Ctor(args[0], args[1]); - case 3: return new Ctor(args[0], args[1], args[2]); - case 4: return new Ctor(args[0], args[1], args[2], args[3]); - case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); - case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); - case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - } - var thisBinding = baseCreate(Ctor.prototype), - result = Ctor.apply(thisBinding, args); - - // Mimic the constructor's `return` behavior. - // See https://es5.github.io/#x13.2.2 for more details. - return isObject(result) ? result : thisBinding; - }; - } - - /** - * Creates a function that wraps `func` to enable currying. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {number} arity The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createCurry(func, bitmask, arity) { - var Ctor = createCtor(func); - - function wrapper() { - var length = arguments.length, - args = Array(length), - index = length, - placeholder = getHolder(wrapper); - - while (index--) { - args[index] = arguments[index]; - } - var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) - ? [] - : replaceHolders(args, placeholder); - - length -= holders.length; - if (length < arity) { - return createRecurry( - func, bitmask, createHybrid, wrapper.placeholder, undefined, - args, holders, undefined, undefined, arity - length); - } - var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - return apply(fn, this, args); - } - return wrapper; - } - - /** - * Creates a `_.find` or `_.findLast` function. - * - * @private - * @param {Function} findIndexFunc The function to find the collection index. - * @returns {Function} Returns the new find function. - */ - function createFind(findIndexFunc) { - return function(collection, predicate, fromIndex) { - var iterable = Object(collection); - if (!isArrayLike(collection)) { - var iteratee = getIteratee(predicate, 3); - collection = keys(collection); - predicate = function(key) { return iteratee(iterable[key], key, iterable); }; - } - var index = findIndexFunc(collection, predicate, fromIndex); - return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; - }; - } - - /** - * Creates a `_.flow` or `_.flowRight` function. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new flow function. - */ - function createFlow(fromRight) { - return flatRest(function(funcs) { - var length = funcs.length, - index = length, - prereq = LodashWrapper.prototype.thru; - - if (fromRight) { - funcs.reverse(); - } - while (index--) { - var func = funcs[index]; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - if (prereq && !wrapper && getFuncName(func) == 'wrapper') { - var wrapper = new LodashWrapper([], true); - } - } - index = wrapper ? index : length; - while (++index < length) { - func = funcs[index]; - - var funcName = getFuncName(func), - data = funcName == 'wrapper' ? getData(func) : undefined; - - if (data && isLaziable(data[0]) && - data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && - !data[4].length && data[9] == 1 - ) { - wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); - } else { - wrapper = (func.length == 1 && isLaziable(func)) - ? wrapper[funcName]() - : wrapper.thru(func); - } - } - return function() { - var args = arguments, - value = args[0]; - - if (wrapper && args.length == 1 && isArray(value)) { - return wrapper.plant(value).value(); - } - var index = 0, - result = length ? funcs[index].apply(this, args) : value; - - while (++index < length) { - result = funcs[index].call(this, result); - } - return result; - }; - }); - } - - /** - * Creates a function that wraps `func` to invoke it with optional `this` - * binding of `thisArg`, partial application, and currying. - * - * @private - * @param {Function|string} func The function or method name to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to prepend to those provided to - * the new function. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [partialsRight] The arguments to append to those provided - * to the new function. - * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { - var isAry = bitmask & WRAP_ARY_FLAG, - isBind = bitmask & WRAP_BIND_FLAG, - isBindKey = bitmask & WRAP_BIND_KEY_FLAG, - isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), - isFlip = bitmask & WRAP_FLIP_FLAG, - Ctor = isBindKey ? undefined : createCtor(func); - - function wrapper() { - var length = arguments.length, - args = Array(length), - index = length; - - while (index--) { - args[index] = arguments[index]; - } - if (isCurried) { - var placeholder = getHolder(wrapper), - holdersCount = countHolders(args, placeholder); - } - if (partials) { - args = composeArgs(args, partials, holders, isCurried); - } - if (partialsRight) { - args = composeArgsRight(args, partialsRight, holdersRight, isCurried); - } - length -= holdersCount; - if (isCurried && length < arity) { - var newHolders = replaceHolders(args, placeholder); - return createRecurry( - func, bitmask, createHybrid, wrapper.placeholder, thisArg, - args, newHolders, argPos, ary, arity - length - ); - } - var thisBinding = isBind ? thisArg : this, - fn = isBindKey ? thisBinding[func] : func; - - length = args.length; - if (argPos) { - args = reorder(args, argPos); - } else if (isFlip && length > 1) { - args.reverse(); - } - if (isAry && ary < length) { - args.length = ary; - } - if (this && this !== root && this instanceof wrapper) { - fn = Ctor || createCtor(fn); - } - return fn.apply(thisBinding, args); - } - return wrapper; - } - - /** - * Creates a function like `_.invertBy`. - * - * @private - * @param {Function} setter The function to set accumulator values. - * @param {Function} toIteratee The function to resolve iteratees. - * @returns {Function} Returns the new inverter function. - */ - function createInverter(setter, toIteratee) { - return function(object, iteratee) { - return baseInverter(object, setter, toIteratee(iteratee), {}); - }; - } - - /** - * Creates a function that performs a mathematical operation on two values. - * - * @private - * @param {Function} operator The function to perform the operation. - * @param {number} [defaultValue] The value used for `undefined` arguments. - * @returns {Function} Returns the new mathematical operation function. - */ - function createMathOperation(operator, defaultValue) { - return function(value, other) { - var result; - if (value === undefined && other === undefined) { - return defaultValue; - } - if (value !== undefined) { - result = value; - } - if (other !== undefined) { - if (result === undefined) { - return other; - } - if (typeof value == 'string' || typeof other == 'string') { - value = baseToString(value); - other = baseToString(other); - } else { - value = baseToNumber(value); - other = baseToNumber(other); - } - result = operator(value, other); - } - return result; - }; - } - - /** - * Creates a function like `_.over`. - * - * @private - * @param {Function} arrayFunc The function to iterate over iteratees. - * @returns {Function} Returns the new over function. - */ - function createOver(arrayFunc) { - return flatRest(function(iteratees) { - iteratees = arrayMap(iteratees, baseUnary(getIteratee())); - return baseRest(function(args) { - var thisArg = this; - return arrayFunc(iteratees, function(iteratee) { - return apply(iteratee, thisArg, args); - }); - }); - }); - } - - /** - * Creates the padding for `string` based on `length`. The `chars` string - * is truncated if the number of characters exceeds `length`. - * - * @private - * @param {number} length The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padding for `string`. - */ - function createPadding(length, chars) { - chars = chars === undefined ? ' ' : baseToString(chars); - - var charsLength = chars.length; - if (charsLength < 2) { - return charsLength ? baseRepeat(chars, length) : chars; - } - var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); - return hasUnicode(chars) - ? castSlice(stringToArray(result), 0, length).join('') - : result.slice(0, length); - } - - /** - * Creates a function that wraps `func` to invoke it with the `this` binding - * of `thisArg` and `partials` prepended to the arguments it receives. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} partials The arguments to prepend to those provided to - * the new function. - * @returns {Function} Returns the new wrapped function. - */ - function createPartial(func, bitmask, thisArg, partials) { - var isBind = bitmask & WRAP_BIND_FLAG, - Ctor = createCtor(func); - - function wrapper() { - var argsIndex = -1, - argsLength = arguments.length, - leftIndex = -1, - leftLength = partials.length, - args = Array(leftLength + argsLength), - fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - - while (++leftIndex < leftLength) { - args[leftIndex] = partials[leftIndex]; - } - while (argsLength--) { - args[leftIndex++] = arguments[++argsIndex]; - } - return apply(fn, isBind ? thisArg : this, args); - } - return wrapper; - } - - /** - * Creates a `_.range` or `_.rangeRight` function. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new range function. - */ - function createRange(fromRight) { - return function(start, end, step) { - if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { - end = step = undefined; - } - // Ensure the sign of `-0` is preserved. - start = toFinite(start); - if (end === undefined) { - end = start; - start = 0; - } else { - end = toFinite(end); - } - step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); - return baseRange(start, end, step, fromRight); - }; - } - - /** - * Creates a function that performs a relational operation on two values. - * - * @private - * @param {Function} operator The function to perform the operation. - * @returns {Function} Returns the new relational operation function. - */ - function createRelationalOperation(operator) { - return function(value, other) { - if (!(typeof value == 'string' && typeof other == 'string')) { - value = toNumber(value); - other = toNumber(other); - } - return operator(value, other); - }; - } - - /** - * Creates a function that wraps `func` to continue currying. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {Function} wrapFunc The function to create the `func` wrapper. - * @param {*} placeholder The placeholder value. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to prepend to those provided to - * the new function. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { - var isCurry = bitmask & WRAP_CURRY_FLAG, - newHolders = isCurry ? holders : undefined, - newHoldersRight = isCurry ? undefined : holders, - newPartials = isCurry ? partials : undefined, - newPartialsRight = isCurry ? undefined : partials; - - bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); - bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); - - if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { - bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); - } - var newData = [ - func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, - newHoldersRight, argPos, ary, arity - ]; - - var result = wrapFunc.apply(undefined, newData); - if (isLaziable(func)) { - setData(result, newData); - } - result.placeholder = placeholder; - return setWrapToString(result, func, bitmask); - } - - /** - * Creates a function like `_.round`. - * - * @private - * @param {string} methodName The name of the `Math` method to use when rounding. - * @returns {Function} Returns the new round function. - */ - function createRound(methodName) { - var func = Math[methodName]; - return function(number, precision) { - number = toNumber(number); - precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); - if (precision && nativeIsFinite(number)) { - // Shift with exponential notation to avoid floating-point issues. - // See [MDN](https://mdn.io/round#Examples) for more details. - var pair = (toString(number) + 'e').split('e'), - value = func(pair[0] + 'e' + (+pair[1] + precision)); - - pair = (toString(value) + 'e').split('e'); - return +(pair[0] + 'e' + (+pair[1] - precision)); - } - return func(number); - }; - } - - /** - * Creates a set object of `values`. - * - * @private - * @param {Array} values The values to add to the set. - * @returns {Object} Returns the new set. - */ - var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { - return new Set(values); - }; - - /** - * Creates a `_.toPairs` or `_.toPairsIn` function. - * - * @private - * @param {Function} keysFunc The function to get the keys of a given object. - * @returns {Function} Returns the new pairs function. - */ - function createToPairs(keysFunc) { - return function(object) { - var tag = getTag(object); - if (tag == mapTag) { - return mapToArray(object); - } - if (tag == setTag) { - return setToPairs(object); - } - return baseToPairs(object, keysFunc(object)); - }; - } - - /** - * Creates a function that either curries or invokes `func` with optional - * `this` binding and partially applied arguments. - * - * @private - * @param {Function|string} func The function or method name to wrap. - * @param {number} bitmask The bitmask flags. - * 1 - `_.bind` - * 2 - `_.bindKey` - * 4 - `_.curry` or `_.curryRight` of a bound function - * 8 - `_.curry` - * 16 - `_.curryRight` - * 32 - `_.partial` - * 64 - `_.partialRight` - * 128 - `_.rearg` - * 256 - `_.ary` - * 512 - `_.flip` - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to be partially applied. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { - var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; - if (!isBindKey && typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - var length = partials ? partials.length : 0; - if (!length) { - bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); - partials = holders = undefined; - } - ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); - arity = arity === undefined ? arity : toInteger(arity); - length -= holders ? holders.length : 0; - - if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { - var partialsRight = partials, - holdersRight = holders; - - partials = holders = undefined; - } - var data = isBindKey ? undefined : getData(func); - - var newData = [ - func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, - argPos, ary, arity - ]; - - if (data) { - mergeData(newData, data); - } - func = newData[0]; - bitmask = newData[1]; - thisArg = newData[2]; - partials = newData[3]; - holders = newData[4]; - arity = newData[9] = newData[9] === undefined - ? (isBindKey ? 0 : func.length) - : nativeMax(newData[9] - length, 0); - - if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { - bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); - } - if (!bitmask || bitmask == WRAP_BIND_FLAG) { - var result = createBind(func, bitmask, thisArg); - } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { - result = createCurry(func, bitmask, arity); - } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { - result = createPartial(func, bitmask, thisArg, partials); - } else { - result = createHybrid.apply(undefined, newData); - } - var setter = data ? baseSetData : setData; - return setWrapToString(setter(result, newData), func, bitmask); - } - - /** - * Used by `_.defaults` to customize its `_.assignIn` use to assign properties - * of source objects to the destination object for all destination properties - * that resolve to `undefined`. - * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to assign. - * @param {Object} object The parent object of `objValue`. - * @returns {*} Returns the value to assign. - */ - function customDefaultsAssignIn(objValue, srcValue, key, object) { - if (objValue === undefined || - (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { - return srcValue; - } - return objValue; - } - - /** - * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source - * objects into destination objects that are passed thru. - * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to merge. - * @param {Object} object The parent object of `objValue`. - * @param {Object} source The parent object of `srcValue`. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - * @returns {*} Returns the value to assign. - */ - function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { - if (isObject(objValue) && isObject(srcValue)) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, objValue); - baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); - stack['delete'](srcValue); - } - return objValue; - } - - /** - * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain - * objects. - * - * @private - * @param {*} value The value to inspect. - * @param {string} key The key of the property to inspect. - * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. - */ - function customOmitClone(value) { - return isPlainObject(value) ? undefined : value; - } - - /** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `array` and `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ - function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - arrLength = array.length, - othLength = other.length; - - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - // Check that cyclic values are equal. - var arrStacked = stack.get(array); - var othStacked = stack.get(other); - if (arrStacked && othStacked) { - return arrStacked == other && othStacked == array; - } - var index = -1, - result = true, - seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; - - stack.set(array, other); - stack.set(other, array); - - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, arrValue, index, other, array, stack) - : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== undefined) { - if (compared) { - continue; - } - result = false; - break; - } - // Recursively compare arrays (susceptible to call stack limits). - if (seen) { - if (!arraySome(other, function(othValue, othIndex) { - if (!cacheHas(seen, othIndex) && - (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; - } - } else if (!( - arrValue === othValue || - equalFunc(arrValue, othValue, bitmask, customizer, stack) - )) { - result = false; - break; - } - } - stack['delete'](array); - stack['delete'](other); - return result; - } - - /** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag: - if ((object.byteLength != other.byteLength) || - (object.byteOffset != other.byteOffset)) { - return false; - } - object = object.buffer; - other = other.buffer; - - case arrayBufferTag: - if ((object.byteLength != other.byteLength) || - !equalFunc(new Uint8Array(object), new Uint8Array(other))) { - return false; - } - return true; - - case boolTag: - case dateTag: - case numberTag: - // Coerce booleans to `1` or `0` and dates to milliseconds. - // Invalid dates are coerced to `NaN`. - return eq(+object, +other); - - case errorTag: - return object.name == other.name && object.message == other.message; - - case regexpTag: - case stringTag: - // Coerce regexes to strings and treat strings, primitives and objects, - // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring - // for more details. - return object == (other + ''); - - case mapTag: - var convert = mapToArray; - - case setTag: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG; - convert || (convert = setToArray); - - if (object.size != other.size && !isPartial) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG; - - // Recursively compare objects (susceptible to call stack limits). - stack.set(object, other); - var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack['delete'](object); - return result; - - case symbolTag: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; - } - - /** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - objProps = getAllKeys(object), - objLength = objProps.length, - othProps = getAllKeys(other), - othLength = othProps.length; - - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { - return false; - } - } - // Check that cyclic values are equal. - var objStacked = stack.get(object); - var othStacked = stack.get(other); - if (objStacked && othStacked) { - return objStacked == other && othStacked == object; - } - var result = true; - stack.set(object, other); - stack.set(other, object); - - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, objValue, key, other, object, stack) - : customizer(objValue, othValue, key, object, other, stack); - } - // Recursively compare objects (susceptible to call stack limits). - if (!(compared === undefined - ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) - : compared - )) { - result = false; - break; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (result && !skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; - - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - result = false; - } - } - stack['delete'](object); - stack['delete'](other); - return result; - } - - /** - * A specialized version of `baseRest` which flattens the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. - */ - function flatRest(func) { - return setToString(overRest(func, undefined, flatten), func + ''); - } - - /** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); - } - - /** - * Creates an array of own and inherited enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeysIn(object) { - return baseGetAllKeys(object, keysIn, getSymbolsIn); - } - - /** - * Gets metadata for `func`. - * - * @private - * @param {Function} func The function to query. - * @returns {*} Returns the metadata for `func`. - */ - var getData = !metaMap ? noop : function(func) { - return metaMap.get(func); - }; - - /** - * Gets the name of `func`. - * - * @private - * @param {Function} func The function to query. - * @returns {string} Returns the function name. - */ - function getFuncName(func) { - var result = (func.name + ''), - array = realNames[result], - length = hasOwnProperty.call(realNames, result) ? array.length : 0; - - while (length--) { - var data = array[length], - otherFunc = data.func; - if (otherFunc == null || otherFunc == func) { - return data.name; - } - } - return result; - } - - /** - * Gets the argument placeholder value for `func`. - * - * @private - * @param {Function} func The function to inspect. - * @returns {*} Returns the placeholder value. - */ - function getHolder(func) { - var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; - return object.placeholder; - } - - /** - * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, - * this function returns the custom method, otherwise it returns `baseIteratee`. - * If arguments are provided, the chosen function is invoked with them and - * its result is returned. - * - * @private - * @param {*} [value] The value to convert to an iteratee. - * @param {number} [arity] The arity of the created iteratee. - * @returns {Function} Returns the chosen function or its result. - */ - function getIteratee() { - var result = lodash.iteratee || iteratee; - result = result === iteratee ? baseIteratee : result; - return arguments.length ? result(arguments[0], arguments[1]) : result; - } - - /** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; - } - - /** - * Gets the property names, values, and compare flags of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the match data of `object`. - */ - function getMatchData(object) { - var result = keys(object), - length = result.length; - - while (length--) { - var key = result[length], - value = object[key]; - - result[length] = [key, value, isStrictComparable(value)]; - } - return result; - } - - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; - } - - /** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ - function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), - tag = value[symToStringTag]; - - try { - value[symToStringTag] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } else { - delete value[symToStringTag]; - } - } - return result; - } - - /** - * Creates an array of the own enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbols = !nativeGetSymbols ? stubArray : function(object) { - if (object == null) { - return []; - } - object = Object(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable.call(object, symbol); - }); - }; - - /** - * Creates an array of the own and inherited enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { - var result = []; - while (object) { - arrayPush(result, getSymbols(object)); - object = getPrototype(object); - } - return result; - }; - - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - var getTag = baseGetTag; - - // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. - if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || - (Map && getTag(new Map) != mapTag) || - (Promise && getTag(Promise.resolve()) != promiseTag) || - (Set && getTag(new Set) != setTag) || - (WeakMap && getTag(new WeakMap) != weakMapTag)) { - getTag = function(value) { - var result = baseGetTag(value), - Ctor = result == objectTag ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : ''; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag; - case mapCtorString: return mapTag; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag; - case weakMapCtorString: return weakMapTag; - } - } - return result; - }; - } - - /** - * Gets the view, applying any `transforms` to the `start` and `end` positions. - * - * @private - * @param {number} start The start of the view. - * @param {number} end The end of the view. - * @param {Array} transforms The transformations to apply to the view. - * @returns {Object} Returns an object containing the `start` and `end` - * positions of the view. - */ - function getView(start, end, transforms) { - var index = -1, - length = transforms.length; - - while (++index < length) { - var data = transforms[index], - size = data.size; - - switch (data.type) { - case 'drop': start += size; break; - case 'dropRight': end -= size; break; - case 'take': end = nativeMin(end, start + size); break; - case 'takeRight': start = nativeMax(start, end - size); break; - } - } - return { 'start': start, 'end': end }; - } - - /** - * Extracts wrapper details from the `source` body comment. - * - * @private - * @param {string} source The source to inspect. - * @returns {Array} Returns the wrapper details. - */ - function getWrapDetails(source) { - var match = source.match(reWrapDetails); - return match ? match[1].split(reSplitDetails) : []; - } - - /** - * Checks if `path` exists on `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @param {Function} hasFunc The function to check properties. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - */ - function hasPath(object, path, hasFunc) { - path = castPath(path, object); - - var index = -1, - length = path.length, - result = false; - - while (++index < length) { - var key = toKey(path[index]); - if (!(result = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result || ++index != length) { - return result; - } - length = object == null ? 0 : object.length; - return !!length && isLength(length) && isIndex(key, length) && - (isArray(object) || isArguments(object)); - } - - /** - * Initializes an array clone. - * - * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. - */ - function initCloneArray(array) { - var length = array.length, - result = new array.constructor(length); - - // Add properties assigned by `RegExp#exec`. - if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { - result.index = array.index; - result.input = array.input; - } - return result; - } - - /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; - } - - /** - * Initializes an object clone based on its `toStringTag`. - * - * **Note:** This function only supports cloning values with tags of - * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. - * - * @private - * @param {Object} object The object to clone. - * @param {string} tag The `toStringTag` of the object to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneByTag(object, tag, isDeep) { - var Ctor = object.constructor; - switch (tag) { - case arrayBufferTag: - return cloneArrayBuffer(object); - - case boolTag: - case dateTag: - return new Ctor(+object); - - case dataViewTag: - return cloneDataView(object, isDeep); - - case float32Tag: case float64Tag: - case int8Tag: case int16Tag: case int32Tag: - case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: - return cloneTypedArray(object, isDeep); - - case mapTag: - return new Ctor; - - case numberTag: - case stringTag: - return new Ctor(object); - - case regexpTag: - return cloneRegExp(object); - - case setTag: - return new Ctor; - - case symbolTag: - return cloneSymbol(object); - } - } - - /** - * Inserts wrapper `details` in a comment at the top of the `source` body. - * - * @private - * @param {string} source The source to modify. - * @returns {Array} details The details to insert. - * @returns {string} Returns the modified source. - */ - function insertWrapDetails(source, details) { - var length = details.length; - if (!length) { - return source; - } - var lastIndex = length - 1; - details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; - details = details.join(length > 2 ? ', ' : ' '); - return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); - } - - /** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. - */ - function isFlattenable(value) { - return isArray(value) || isArguments(value) || - !!(spreadableSymbol && value && value[spreadableSymbol]); - } - - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); - } - - /** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ - function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike(object) && isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq(object[index], value); - } - return false; - } - - /** - * Checks if `value` is a property name and not a property path. - * - * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. - */ - function isKey(value, object) { - if (isArray(value)) { - return false; - } - var type = typeof value; - if (type == 'number' || type == 'symbol' || type == 'boolean' || - value == null || isSymbol(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)); - } - - /** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); - } - - /** - * Checks if `func` has a lazy counterpart. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` has a lazy counterpart, - * else `false`. - */ - function isLaziable(func) { - var funcName = getFuncName(func), - other = lodash[funcName]; - - if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { - return false; - } - if (func === other) { - return true; - } - var data = getData(other); - return !!data && func === data[0]; - } - - /** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); - } - - /** - * Checks if `func` is capable of being masked. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `func` is maskable, else `false`. - */ - var isMaskable = coreJsData ? isFunction : stubFalse; - - /** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ - function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - - return value === proto; - } - - /** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. - */ - function isStrictComparable(value) { - return value === value && !isObject(value); - } - - /** - * A specialized version of `matchesProperty` for source values suitable - * for strict equality comparisons, i.e. `===`. - * - * @private - * @param {string} key The key of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function matchesStrictComparable(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && - (srcValue !== undefined || (key in Object(object))); - }; - } - - /** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. - * - * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. - */ - function memoizeCapped(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); - - var cache = result.cache; - return result; - } - - /** - * Merges the function metadata of `source` into `data`. - * - * Merging metadata reduces the number of wrappers used to invoke a function. - * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` - * may be applied regardless of execution order. Methods like `_.ary` and - * `_.rearg` modify function arguments, making the order in which they are - * executed important, preventing the merging of metadata. However, we make - * an exception for a safe combined case where curried functions have `_.ary` - * and or `_.rearg` applied. - * - * @private - * @param {Array} data The destination metadata. - * @param {Array} source The source metadata. - * @returns {Array} Returns `data`. - */ - function mergeData(data, source) { - var bitmask = data[1], - srcBitmask = source[1], - newBitmask = bitmask | srcBitmask, - isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); - - var isCombo = - ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || - ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || - ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); - - // Exit early if metadata can't be merged. - if (!(isCommon || isCombo)) { - return data; - } - // Use source `thisArg` if available. - if (srcBitmask & WRAP_BIND_FLAG) { - data[2] = source[2]; - // Set when currying a bound function. - newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; - } - // Compose partial arguments. - var value = source[3]; - if (value) { - var partials = data[3]; - data[3] = partials ? composeArgs(partials, value, source[4]) : value; - data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; - } - // Compose partial right arguments. - value = source[5]; - if (value) { - partials = data[5]; - data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; - data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; - } - // Use source `argPos` if available. - value = source[7]; - if (value) { - data[7] = value; - } - // Use source `ary` if it's smaller. - if (srcBitmask & WRAP_ARY_FLAG) { - data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); - } - // Use source `arity` if one is not provided. - if (data[9] == null) { - data[9] = source[9]; - } - // Use source `func` and merge bitmasks. - data[0] = source[0]; - data[1] = newBitmask; - - return data; - } - - /** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; - } - - /** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ - function objectToString(value) { - return nativeObjectToString.call(value); - } - - /** - * A specialized version of `baseRest` which transforms the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ - function overRest(func, start, transform) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return apply(func, this, otherArgs); - }; - } - - /** - * Gets the parent value at `path` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} path The path to get the parent value of. - * @returns {*} Returns the parent value. - */ - function parent(object, path) { - return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); - } - - /** - * Reorder `array` according to the specified indexes where the element at - * the first index is assigned as the first element, the element at - * the second index is assigned as the second element, and so on. - * - * @private - * @param {Array} array The array to reorder. - * @param {Array} indexes The arranged array indexes. - * @returns {Array} Returns `array`. - */ - function reorder(array, indexes) { - var arrLength = array.length, - length = nativeMin(indexes.length, arrLength), - oldArray = copyArray(array); - - while (length--) { - var index = indexes[length]; - array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; - } - return array; - } - - /** - * Gets the value at `key`, unless `key` is "__proto__" or "constructor". - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function safeGet(object, key) { - if (key === 'constructor' && typeof object[key] === 'function') { - return; - } - - if (key == '__proto__') { - return; - } - - return object[key]; - } - - /** - * Sets metadata for `func`. - * - * **Note:** If this function becomes hot, i.e. is invoked a lot in a short - * period of time, it will trip its breaker and transition to an identity - * function to avoid garbage collection pauses in V8. See - * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) - * for more details. - * - * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. - */ - var setData = shortOut(baseSetData); - - /** - * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). - * - * @private - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @returns {number|Object} Returns the timer id or timeout object. - */ - var setTimeout = ctxSetTimeout || function(func, wait) { - return root.setTimeout(func, wait); - }; - - /** - * Sets the `toString` method of `func` to return `string`. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var setToString = shortOut(baseSetToString); - - /** - * Sets the `toString` method of `wrapper` to mimic the source of `reference` - * with wrapper details in a comment at the top of the source body. - * - * @private - * @param {Function} wrapper The function to modify. - * @param {Function} reference The reference function. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @returns {Function} Returns `wrapper`. - */ - function setWrapToString(wrapper, reference, bitmask) { - var source = (reference + ''); - return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); - } - - /** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. - * - * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. - */ - function shortOut(func) { - var count = 0, - lastCalled = 0; - - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); - - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; - } - - /** - * A specialized version of `_.shuffle` which mutates and sets the size of `array`. - * - * @private - * @param {Array} array The array to shuffle. - * @param {number} [size=array.length] The size of `array`. - * @returns {Array} Returns `array`. - */ - function shuffleSelf(array, size) { - var index = -1, - length = array.length, - lastIndex = length - 1; - - size = size === undefined ? length : size; - while (++index < size) { - var rand = baseRandom(index, lastIndex), - value = array[rand]; - - array[rand] = array[index]; - array[index] = value; - } - array.length = size; - return array; - } - - /** - * Converts `string` to a property path array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. - */ - var stringToPath = memoizeCapped(function(string) { - var result = []; - if (string.charCodeAt(0) === 46 /* . */) { - result.push(''); - } - string.replace(rePropName, function(match, number, quote, subString) { - result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; - }); - - /** - * Converts `value` to a string key if it's not a string or symbol. - * - * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. - */ - function toKey(value) { - if (typeof value == 'string' || isSymbol(value)) { - return value; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; - } - - /** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. - */ - function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; - } - - /** - * Updates wrapper `details` based on `bitmask` flags. - * - * @private - * @returns {Array} details The details to modify. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @returns {Array} Returns `details`. - */ - function updateWrapDetails(details, bitmask) { - arrayEach(wrapFlags, function(pair) { - var value = '_.' + pair[0]; - if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { - details.push(value); - } - }); - return details.sort(); - } - - /** - * Creates a clone of `wrapper`. - * - * @private - * @param {Object} wrapper The wrapper to clone. - * @returns {Object} Returns the cloned wrapper. - */ - function wrapperClone(wrapper) { - if (wrapper instanceof LazyWrapper) { - return wrapper.clone(); - } - var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); - result.__actions__ = copyArray(wrapper.__actions__); - result.__index__ = wrapper.__index__; - result.__values__ = wrapper.__values__; - return result; - } - - /*------------------------------------------------------------------------*/ - - /** - * Creates an array of elements split into groups the length of `size`. - * If `array` can't be split evenly, the final chunk will be the remaining - * elements. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to process. - * @param {number} [size=1] The length of each chunk - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the new array of chunks. - * @example - * - * _.chunk(['a', 'b', 'c', 'd'], 2); - * // => [['a', 'b'], ['c', 'd']] - * - * _.chunk(['a', 'b', 'c', 'd'], 3); - * // => [['a', 'b', 'c'], ['d']] - */ - function chunk(array, size, guard) { - if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { - size = 1; - } else { - size = nativeMax(toInteger(size), 0); - } - var length = array == null ? 0 : array.length; - if (!length || size < 1) { - return []; - } - var index = 0, - resIndex = 0, - result = Array(nativeCeil(length / size)); - - while (index < length) { - result[resIndex++] = baseSlice(array, index, (index += size)); - } - return result; - } - - /** - * Creates an array with all falsey values removed. The values `false`, `null`, - * `0`, `""`, `undefined`, and `NaN` are falsey. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to compact. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.compact([0, 1, false, 2, '', 3]); - * // => [1, 2, 3] - */ - function compact(array) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (value) { - result[resIndex++] = value; - } - } - return result; - } - - /** - * Creates a new array concatenating `array` with any additional arrays - * and/or values. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to concatenate. - * @param {...*} [values] The values to concatenate. - * @returns {Array} Returns the new concatenated array. - * @example - * - * var array = [1]; - * var other = _.concat(array, 2, [3], [[4]]); - * - * console.log(other); - * // => [1, 2, 3, [4]] - * - * console.log(array); - * // => [1] - */ - function concat() { - var length = arguments.length; - if (!length) { - return []; - } - var args = Array(length - 1), - array = arguments[0], - index = length; - - while (index--) { - args[index - 1] = arguments[index]; - } - return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); - } - - /** - * Creates an array of `array` values not included in the other given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. - * - * **Note:** Unlike `_.pullAll`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.without, _.xor - * @example - * - * _.difference([2, 1], [2, 3]); - * // => [1] - */ - var difference = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) - : []; - }); - - /** - * This method is like `_.difference` except that it accepts `iteratee` which - * is invoked for each element of `array` and `values` to generate the criterion - * by which they're compared. The order and references of result values are - * determined by the first array. The iteratee is invoked with one argument: - * (value). - * - * **Note:** Unlike `_.pullAllBy`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [1.2] - * - * // The `_.property` iteratee shorthand. - * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); - * // => [{ 'x': 2 }] - */ - var differenceBy = baseRest(function(array, values) { - var iteratee = last(values); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) - : []; - }); - - /** - * This method is like `_.difference` except that it accepts `comparator` - * which is invoked to compare elements of `array` to `values`. The order and - * references of result values are determined by the first array. The comparator - * is invoked with two arguments: (arrVal, othVal). - * - * **Note:** Unlike `_.pullAllWith`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * - * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); - * // => [{ 'x': 2, 'y': 1 }] - */ - var differenceWith = baseRest(function(array, values) { - var comparator = last(values); - if (isArrayLikeObject(comparator)) { - comparator = undefined; - } - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) - : []; - }); - - /** - * Creates a slice of `array` with `n` elements dropped from the beginning. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.drop([1, 2, 3]); - * // => [2, 3] - * - * _.drop([1, 2, 3], 2); - * // => [3] - * - * _.drop([1, 2, 3], 5); - * // => [] - * - * _.drop([1, 2, 3], 0); - * // => [1, 2, 3] - */ - function drop(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - return baseSlice(array, n < 0 ? 0 : n, length); - } - - /** - * Creates a slice of `array` with `n` elements dropped from the end. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.dropRight([1, 2, 3]); - * // => [1, 2] - * - * _.dropRight([1, 2, 3], 2); - * // => [1] - * - * _.dropRight([1, 2, 3], 5); - * // => [] - * - * _.dropRight([1, 2, 3], 0); - * // => [1, 2, 3] - */ - function dropRight(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - n = length - n; - return baseSlice(array, 0, n < 0 ? 0 : n); - } - - /** - * Creates a slice of `array` excluding elements dropped from the end. - * Elements are dropped until `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.dropRightWhile(users, function(o) { return !o.active; }); - * // => objects for ['barney'] - * - * // The `_.matches` iteratee shorthand. - * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); - * // => objects for ['barney', 'fred'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.dropRightWhile(users, ['active', false]); - * // => objects for ['barney'] - * - * // The `_.property` iteratee shorthand. - * _.dropRightWhile(users, 'active'); - * // => objects for ['barney', 'fred', 'pebbles'] - */ - function dropRightWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), true, true) - : []; - } - - /** - * Creates a slice of `array` excluding elements dropped from the beginning. - * Elements are dropped until `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.dropWhile(users, function(o) { return !o.active; }); - * // => objects for ['pebbles'] - * - * // The `_.matches` iteratee shorthand. - * _.dropWhile(users, { 'user': 'barney', 'active': false }); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.dropWhile(users, ['active', false]); - * // => objects for ['pebbles'] - * - * // The `_.property` iteratee shorthand. - * _.dropWhile(users, 'active'); - * // => objects for ['barney', 'fred', 'pebbles'] - */ - function dropWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), true) - : []; - } - - /** - * Fills elements of `array` with `value` from `start` up to, but not - * including, `end`. - * - * **Note:** This method mutates `array`. - * - * @static - * @memberOf _ - * @since 3.2.0 - * @category Array - * @param {Array} array The array to fill. - * @param {*} value The value to fill `array` with. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3]; - * - * _.fill(array, 'a'); - * console.log(array); - * // => ['a', 'a', 'a'] - * - * _.fill(Array(3), 2); - * // => [2, 2, 2] - * - * _.fill([4, 6, 8, 10], '*', 1, 3); - * // => [4, '*', '*', 10] - */ - function fill(array, value, start, end) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { - start = 0; - end = length; - } - return baseFill(array, value, start, end); - } - - /** - * This method is like `_.find` except that it returns the index of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.findIndex(users, function(o) { return o.user == 'barney'; }); - * // => 0 - * - * // The `_.matches` iteratee shorthand. - * _.findIndex(users, { 'user': 'fred', 'active': false }); - * // => 1 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findIndex(users, ['active', false]); - * // => 0 - * - * // The `_.property` iteratee shorthand. - * _.findIndex(users, 'active'); - * // => 2 - */ - function findIndex(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); - } - return baseFindIndex(array, getIteratee(predicate, 3), index); - } - - /** - * This method is like `_.findIndex` except that it iterates over elements - * of `collection` from right to left. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=array.length-1] The index to search from. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); - * // => 2 - * - * // The `_.matches` iteratee shorthand. - * _.findLastIndex(users, { 'user': 'barney', 'active': true }); - * // => 0 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findLastIndex(users, ['active', false]); - * // => 2 - * - * // The `_.property` iteratee shorthand. - * _.findLastIndex(users, 'active'); - * // => 0 - */ - function findLastIndex(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = length - 1; - if (fromIndex !== undefined) { - index = toInteger(fromIndex); - index = fromIndex < 0 - ? nativeMax(length + index, 0) - : nativeMin(index, length - 1); - } - return baseFindIndex(array, getIteratee(predicate, 3), index, true); - } - - /** - * Flattens `array` a single level deep. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flatten([1, [2, [3, [4]], 5]]); - * // => [1, 2, [3, [4]], 5] - */ - function flatten(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, 1) : []; - } - - /** - * Recursively flattens `array`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flattenDeep([1, [2, [3, [4]], 5]]); - * // => [1, 2, 3, 4, 5] - */ - function flattenDeep(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, INFINITY) : []; - } - - /** - * Recursively flatten `array` up to `depth` times. - * - * @static - * @memberOf _ - * @since 4.4.0 - * @category Array - * @param {Array} array The array to flatten. - * @param {number} [depth=1] The maximum recursion depth. - * @returns {Array} Returns the new flattened array. - * @example - * - * var array = [1, [2, [3, [4]], 5]]; - * - * _.flattenDepth(array, 1); - * // => [1, 2, [3, [4]], 5] - * - * _.flattenDepth(array, 2); - * // => [1, 2, 3, [4], 5] - */ - function flattenDepth(array, depth) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(array, depth); - } - - /** - * The inverse of `_.toPairs`; this method returns an object composed - * from key-value `pairs`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} pairs The key-value pairs. - * @returns {Object} Returns the new object. - * @example - * - * _.fromPairs([['a', 1], ['b', 2]]); - * // => { 'a': 1, 'b': 2 } - */ - function fromPairs(pairs) { - var index = -1, - length = pairs == null ? 0 : pairs.length, - result = {}; - - while (++index < length) { - var pair = pairs[index]; - result[pair[0]] = pair[1]; - } - return result; - } - - /** - * Gets the first element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias first - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the first element of `array`. - * @example - * - * _.head([1, 2, 3]); - * // => 1 - * - * _.head([]); - * // => undefined - */ - function head(array) { - return (array && array.length) ? array[0] : undefined; - } - - /** - * Gets the index at which the first occurrence of `value` is found in `array` - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. If `fromIndex` is negative, it's used as the - * offset from the end of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.indexOf([1, 2, 1, 2], 2); - * // => 1 - * - * // Search from the `fromIndex`. - * _.indexOf([1, 2, 1, 2], 2, 2); - * // => 3 - */ - function indexOf(array, value, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); - } - return baseIndexOf(array, value, index); - } - - /** - * Gets all but the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.initial([1, 2, 3]); - * // => [1, 2] - */ - function initial(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 0, -1) : []; - } - - /** - * Creates an array of unique values that are included in all given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * _.intersection([2, 1], [2, 3]); - * // => [2] - */ - var intersection = baseRest(function(arrays) { - var mapped = arrayMap(arrays, castArrayLikeObject); - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped) - : []; - }); - - /** - * This method is like `_.intersection` except that it accepts `iteratee` - * which is invoked for each element of each `arrays` to generate the criterion - * by which they're compared. The order and references of result values are - * determined by the first array. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [2.1] - * - * // The `_.property` iteratee shorthand. - * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }] - */ - var intersectionBy = baseRest(function(arrays) { - var iteratee = last(arrays), - mapped = arrayMap(arrays, castArrayLikeObject); - - if (iteratee === last(mapped)) { - iteratee = undefined; - } else { - mapped.pop(); - } - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped, getIteratee(iteratee, 2)) - : []; - }); - - /** - * This method is like `_.intersection` except that it accepts `comparator` - * which is invoked to compare elements of `arrays`. The order and references - * of result values are determined by the first array. The comparator is - * invoked with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.intersectionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }] - */ - var intersectionWith = baseRest(function(arrays) { - var comparator = last(arrays), - mapped = arrayMap(arrays, castArrayLikeObject); - - comparator = typeof comparator == 'function' ? comparator : undefined; - if (comparator) { - mapped.pop(); - } - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped, undefined, comparator) - : []; - }); - - /** - * Converts all elements in `array` into a string separated by `separator`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to convert. - * @param {string} [separator=','] The element separator. - * @returns {string} Returns the joined string. - * @example - * - * _.join(['a', 'b', 'c'], '~'); - * // => 'a~b~c' - */ - function join(array, separator) { - return array == null ? '' : nativeJoin.call(array, separator); - } - - /** - * Gets the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the last element of `array`. - * @example - * - * _.last([1, 2, 3]); - * // => 3 - */ - function last(array) { - var length = array == null ? 0 : array.length; - return length ? array[length - 1] : undefined; - } - - /** - * This method is like `_.indexOf` except that it iterates over elements of - * `array` from right to left. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=array.length-1] The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.lastIndexOf([1, 2, 1, 2], 2); - * // => 3 - * - * // Search from the `fromIndex`. - * _.lastIndexOf([1, 2, 1, 2], 2, 2); - * // => 1 - */ - function lastIndexOf(array, value, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = length; - if (fromIndex !== undefined) { - index = toInteger(fromIndex); - index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); - } - return value === value - ? strictLastIndexOf(array, value, index) - : baseFindIndex(array, baseIsNaN, index, true); - } - - /** - * Gets the element at index `n` of `array`. If `n` is negative, the nth - * element from the end is returned. - * - * @static - * @memberOf _ - * @since 4.11.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=0] The index of the element to return. - * @returns {*} Returns the nth element of `array`. - * @example - * - * var array = ['a', 'b', 'c', 'd']; - * - * _.nth(array, 1); - * // => 'b' - * - * _.nth(array, -2); - * // => 'c'; - */ - function nth(array, n) { - return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; - } - - /** - * Removes all given values from `array` using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` - * to remove elements from an array by predicate. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {...*} [values] The values to remove. - * @returns {Array} Returns `array`. - * @example - * - * var array = ['a', 'b', 'c', 'a', 'b', 'c']; - * - * _.pull(array, 'a', 'c'); - * console.log(array); - * // => ['b', 'b'] - */ - var pull = baseRest(pullAll); - - /** - * This method is like `_.pull` except that it accepts an array of values to remove. - * - * **Note:** Unlike `_.difference`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @returns {Array} Returns `array`. - * @example - * - * var array = ['a', 'b', 'c', 'a', 'b', 'c']; - * - * _.pullAll(array, ['a', 'c']); - * console.log(array); - * // => ['b', 'b'] - */ - function pullAll(array, values) { - return (array && array.length && values && values.length) - ? basePullAll(array, values) - : array; - } - - /** - * This method is like `_.pullAll` except that it accepts `iteratee` which is - * invoked for each element of `array` and `values` to generate the criterion - * by which they're compared. The iteratee is invoked with one argument: (value). - * - * **Note:** Unlike `_.differenceBy`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns `array`. - * @example - * - * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; - * - * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); - * console.log(array); - * // => [{ 'x': 2 }] - */ - function pullAllBy(array, values, iteratee) { - return (array && array.length && values && values.length) - ? basePullAll(array, values, getIteratee(iteratee, 2)) - : array; - } - - /** - * This method is like `_.pullAll` except that it accepts `comparator` which - * is invoked to compare elements of `array` to `values`. The comparator is - * invoked with two arguments: (arrVal, othVal). - * - * **Note:** Unlike `_.differenceWith`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.6.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns `array`. - * @example - * - * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; - * - * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); - * console.log(array); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] - */ - function pullAllWith(array, values, comparator) { - return (array && array.length && values && values.length) - ? basePullAll(array, values, undefined, comparator) - : array; - } - - /** - * Removes elements from `array` corresponding to `indexes` and returns an - * array of removed elements. - * - * **Note:** Unlike `_.at`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {...(number|number[])} [indexes] The indexes of elements to remove. - * @returns {Array} Returns the new array of removed elements. - * @example - * - * var array = ['a', 'b', 'c', 'd']; - * var pulled = _.pullAt(array, [1, 3]); - * - * console.log(array); - * // => ['a', 'c'] - * - * console.log(pulled); - * // => ['b', 'd'] - */ - var pullAt = flatRest(function(array, indexes) { - var length = array == null ? 0 : array.length, - result = baseAt(array, indexes); - - basePullAt(array, arrayMap(indexes, function(index) { - return isIndex(index, length) ? +index : index; - }).sort(compareAscending)); - - return result; - }); - - /** - * Removes all elements from `array` that `predicate` returns truthy for - * and returns an array of the removed elements. The predicate is invoked - * with three arguments: (value, index, array). - * - * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` - * to pull elements from an array by value. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new array of removed elements. - * @example - * - * var array = [1, 2, 3, 4]; - * var evens = _.remove(array, function(n) { - * return n % 2 == 0; - * }); - * - * console.log(array); - * // => [1, 3] - * - * console.log(evens); - * // => [2, 4] - */ - function remove(array, predicate) { - var result = []; - if (!(array && array.length)) { - return result; - } - var index = -1, - indexes = [], - length = array.length; - - predicate = getIteratee(predicate, 3); - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result.push(value); - indexes.push(index); - } - } - basePullAt(array, indexes); - return result; - } - - /** - * Reverses `array` so that the first element becomes the last, the second - * element becomes the second to last, and so on. - * - * **Note:** This method mutates `array` and is based on - * [`Array#reverse`](https://mdn.io/Array/reverse). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3]; - * - * _.reverse(array); - * // => [3, 2, 1] - * - * console.log(array); - * // => [3, 2, 1] - */ - function reverse(array) { - return array == null ? array : nativeReverse.call(array); - } - - /** - * Creates a slice of `array` from `start` up to, but not including, `end`. - * - * **Note:** This method is used instead of - * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are - * returned. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ - function slice(array, start, end) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { - start = 0; - end = length; - } - else { - start = start == null ? 0 : toInteger(start); - end = end === undefined ? length : toInteger(end); - } - return baseSlice(array, start, end); - } - - /** - * Uses a binary search to determine the lowest index at which `value` - * should be inserted into `array` in order to maintain its sort order. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * _.sortedIndex([30, 50], 40); - * // => 1 - */ - function sortedIndex(array, value) { - return baseSortedIndex(array, value); - } - - /** - * This method is like `_.sortedIndex` except that it accepts `iteratee` - * which is invoked for `value` and each element of `array` to compute their - * sort ranking. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; - * - * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 0 - * - * // The `_.property` iteratee shorthand. - * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); - * // => 0 - */ - function sortedIndexBy(array, value, iteratee) { - return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); - } - - /** - * This method is like `_.indexOf` except that it performs a binary - * search on a sorted `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.sortedIndexOf([4, 5, 5, 5, 6], 5); - * // => 1 - */ - function sortedIndexOf(array, value) { - var length = array == null ? 0 : array.length; - if (length) { - var index = baseSortedIndex(array, value); - if (index < length && eq(array[index], value)) { - return index; - } - } - return -1; - } - - /** - * This method is like `_.sortedIndex` except that it returns the highest - * index at which `value` should be inserted into `array` in order to - * maintain its sort order. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * _.sortedLastIndex([4, 5, 5, 5, 6], 5); - * // => 4 - */ - function sortedLastIndex(array, value) { - return baseSortedIndex(array, value, true); - } - - /** - * This method is like `_.sortedLastIndex` except that it accepts `iteratee` - * which is invoked for `value` and each element of `array` to compute their - * sort ranking. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; - * - * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 1 - * - * // The `_.property` iteratee shorthand. - * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); - * // => 1 - */ - function sortedLastIndexBy(array, value, iteratee) { - return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); - } - - /** - * This method is like `_.lastIndexOf` except that it performs a binary - * search on a sorted `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); - * // => 3 - */ - function sortedLastIndexOf(array, value) { - var length = array == null ? 0 : array.length; - if (length) { - var index = baseSortedIndex(array, value, true) - 1; - if (eq(array[index], value)) { - return index; - } - } - return -1; - } - - /** - * This method is like `_.uniq` except that it's designed and optimized - * for sorted arrays. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.sortedUniq([1, 1, 2]); - * // => [1, 2] - */ - function sortedUniq(array) { - return (array && array.length) - ? baseSortedUniq(array) - : []; - } - - /** - * This method is like `_.uniqBy` except that it's designed and optimized - * for sorted arrays. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); - * // => [1.1, 2.3] - */ - function sortedUniqBy(array, iteratee) { - return (array && array.length) - ? baseSortedUniq(array, getIteratee(iteratee, 2)) - : []; - } - - /** - * Gets all but the first element of `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.tail([1, 2, 3]); - * // => [2, 3] - */ - function tail(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 1, length) : []; - } - - /** - * Creates a slice of `array` with `n` elements taken from the beginning. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to take. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.take([1, 2, 3]); - * // => [1] - * - * _.take([1, 2, 3], 2); - * // => [1, 2] - * - * _.take([1, 2, 3], 5); - * // => [1, 2, 3] - * - * _.take([1, 2, 3], 0); - * // => [] - */ - function take(array, n, guard) { - if (!(array && array.length)) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - return baseSlice(array, 0, n < 0 ? 0 : n); - } - - /** - * Creates a slice of `array` with `n` elements taken from the end. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to take. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.takeRight([1, 2, 3]); - * // => [3] - * - * _.takeRight([1, 2, 3], 2); - * // => [2, 3] - * - * _.takeRight([1, 2, 3], 5); - * // => [1, 2, 3] - * - * _.takeRight([1, 2, 3], 0); - * // => [] - */ - function takeRight(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - n = length - n; - return baseSlice(array, n < 0 ? 0 : n, length); - } - - /** - * Creates a slice of `array` with elements taken from the end. Elements are - * taken until `predicate` returns falsey. The predicate is invoked with - * three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.takeRightWhile(users, function(o) { return !o.active; }); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.matches` iteratee shorthand. - * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); - * // => objects for ['pebbles'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.takeRightWhile(users, ['active', false]); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.property` iteratee shorthand. - * _.takeRightWhile(users, 'active'); - * // => [] - */ - function takeRightWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), false, true) - : []; - } - - /** - * Creates a slice of `array` with elements taken from the beginning. Elements - * are taken until `predicate` returns falsey. The predicate is invoked with - * three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.takeWhile(users, function(o) { return !o.active; }); - * // => objects for ['barney', 'fred'] - * - * // The `_.matches` iteratee shorthand. - * _.takeWhile(users, { 'user': 'barney', 'active': false }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.takeWhile(users, ['active', false]); - * // => objects for ['barney', 'fred'] - * - * // The `_.property` iteratee shorthand. - * _.takeWhile(users, 'active'); - * // => [] - */ - function takeWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3)) - : []; - } - - /** - * Creates an array of unique values, in order, from all given arrays using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of combined values. - * @example - * - * _.union([2], [1, 2]); - * // => [2, 1] - */ - var union = baseRest(function(arrays) { - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); - }); - - /** - * This method is like `_.union` except that it accepts `iteratee` which is - * invoked for each element of each `arrays` to generate the criterion by - * which uniqueness is computed. Result values are chosen from the first - * array in which the value occurs. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of combined values. - * @example - * - * _.unionBy([2.1], [1.2, 2.3], Math.floor); - * // => [2.1, 1.2] - * - * // The `_.property` iteratee shorthand. - * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] - */ - var unionBy = baseRest(function(arrays) { - var iteratee = last(arrays); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); - }); - - /** - * This method is like `_.union` except that it accepts `comparator` which - * is invoked to compare elements of `arrays`. Result values are chosen from - * the first array in which the value occurs. The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of combined values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.unionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] - */ - var unionWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == 'function' ? comparator : undefined; - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); - }); - - /** - * Creates a duplicate-free version of an array, using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons, in which only the first occurrence of each element - * is kept. The order of result values is determined by the order they occur - * in the array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.uniq([2, 1, 2]); - * // => [2, 1] - */ - function uniq(array) { - return (array && array.length) ? baseUniq(array) : []; - } - - /** - * This method is like `_.uniq` except that it accepts `iteratee` which is - * invoked for each element in `array` to generate the criterion by which - * uniqueness is computed. The order of result values is determined by the - * order they occur in the array. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.uniqBy([2.1, 1.2, 2.3], Math.floor); - * // => [2.1, 1.2] - * - * // The `_.property` iteratee shorthand. - * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] - */ - function uniqBy(array, iteratee) { - return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; - } - - /** - * This method is like `_.uniq` except that it accepts `comparator` which - * is invoked to compare elements of `array`. The order of result values is - * determined by the order they occur in the array.The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.uniqWith(objects, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] - */ - function uniqWith(array, comparator) { - comparator = typeof comparator == 'function' ? comparator : undefined; - return (array && array.length) ? baseUniq(array, undefined, comparator) : []; - } - - /** - * This method is like `_.zip` except that it accepts an array of grouped - * elements and creates an array regrouping the elements to their pre-zip - * configuration. - * - * @static - * @memberOf _ - * @since 1.2.0 - * @category Array - * @param {Array} array The array of grouped elements to process. - * @returns {Array} Returns the new array of regrouped elements. - * @example - * - * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] - * - * _.unzip(zipped); - * // => [['a', 'b'], [1, 2], [true, false]] - */ - function unzip(array) { - if (!(array && array.length)) { - return []; - } - var length = 0; - array = arrayFilter(array, function(group) { - if (isArrayLikeObject(group)) { - length = nativeMax(group.length, length); - return true; - } - }); - return baseTimes(length, function(index) { - return arrayMap(array, baseProperty(index)); - }); - } - - /** - * This method is like `_.unzip` except that it accepts `iteratee` to specify - * how regrouped values should be combined. The iteratee is invoked with the - * elements of each group: (...group). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Array - * @param {Array} array The array of grouped elements to process. - * @param {Function} [iteratee=_.identity] The function to combine - * regrouped values. - * @returns {Array} Returns the new array of regrouped elements. - * @example - * - * var zipped = _.zip([1, 2], [10, 20], [100, 200]); - * // => [[1, 10, 100], [2, 20, 200]] - * - * _.unzipWith(zipped, _.add); - * // => [3, 30, 300] - */ - function unzipWith(array, iteratee) { - if (!(array && array.length)) { - return []; - } - var result = unzip(array); - if (iteratee == null) { - return result; - } - return arrayMap(result, function(group) { - return apply(iteratee, undefined, group); - }); - } - - /** - * Creates an array excluding all given values using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * **Note:** Unlike `_.pull`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...*} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.difference, _.xor - * @example - * - * _.without([2, 1, 2, 3], 1, 2); - * // => [3] - */ - var without = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, values) - : []; - }); - - /** - * Creates an array of unique values that is the - * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) - * of the given arrays. The order of result values is determined by the order - * they occur in the arrays. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of filtered values. - * @see _.difference, _.without - * @example - * - * _.xor([2, 1], [2, 3]); - * // => [1, 3] - */ - var xor = baseRest(function(arrays) { - return baseXor(arrayFilter(arrays, isArrayLikeObject)); - }); - - /** - * This method is like `_.xor` except that it accepts `iteratee` which is - * invoked for each element of each `arrays` to generate the criterion by - * which by which they're compared. The order of result values is determined - * by the order they occur in the arrays. The iteratee is invoked with one - * argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [1.2, 3.4] - * - * // The `_.property` iteratee shorthand. - * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 2 }] - */ - var xorBy = baseRest(function(arrays) { - var iteratee = last(arrays); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); - }); - - /** - * This method is like `_.xor` except that it accepts `comparator` which is - * invoked to compare elements of `arrays`. The order of result values is - * determined by the order they occur in the arrays. The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.xorWith(objects, others, _.isEqual); - * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] - */ - var xorWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == 'function' ? comparator : undefined; - return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); - }); - - /** - * Creates an array of grouped elements, the first of which contains the - * first elements of the given arrays, the second of which contains the - * second elements of the given arrays, and so on. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to process. - * @returns {Array} Returns the new array of grouped elements. - * @example - * - * _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] - */ - var zip = baseRest(unzip); - - /** - * This method is like `_.fromPairs` except that it accepts two arrays, - * one of property identifiers and one of corresponding values. - * - * @static - * @memberOf _ - * @since 0.4.0 - * @category Array - * @param {Array} [props=[]] The property identifiers. - * @param {Array} [values=[]] The property values. - * @returns {Object} Returns the new object. - * @example - * - * _.zipObject(['a', 'b'], [1, 2]); - * // => { 'a': 1, 'b': 2 } - */ - function zipObject(props, values) { - return baseZipObject(props || [], values || [], assignValue); - } - - /** - * This method is like `_.zipObject` except that it supports property paths. - * - * @static - * @memberOf _ - * @since 4.1.0 - * @category Array - * @param {Array} [props=[]] The property identifiers. - * @param {Array} [values=[]] The property values. - * @returns {Object} Returns the new object. - * @example - * - * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); - * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } - */ - function zipObjectDeep(props, values) { - return baseZipObject(props || [], values || [], baseSet); - } - - /** - * This method is like `_.zip` except that it accepts `iteratee` to specify - * how grouped values should be combined. The iteratee is invoked with the - * elements of each group: (...group). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Array - * @param {...Array} [arrays] The arrays to process. - * @param {Function} [iteratee=_.identity] The function to combine - * grouped values. - * @returns {Array} Returns the new array of grouped elements. - * @example - * - * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { - * return a + b + c; - * }); - * // => [111, 222] - */ - var zipWith = baseRest(function(arrays) { - var length = arrays.length, - iteratee = length > 1 ? arrays[length - 1] : undefined; - - iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; - return unzipWith(arrays, iteratee); - }); - - /*------------------------------------------------------------------------*/ - - /** - * Creates a `lodash` wrapper instance that wraps `value` with explicit method - * chain sequences enabled. The result of such sequences must be unwrapped - * with `_#value`. - * - * @static - * @memberOf _ - * @since 1.3.0 - * @category Seq - * @param {*} value The value to wrap. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'pebbles', 'age': 1 } - * ]; - * - * var youngest = _ - * .chain(users) - * .sortBy('age') - * .map(function(o) { - * return o.user + ' is ' + o.age; - * }) - * .head() - * .value(); - * // => 'pebbles is 1' - */ - function chain(value) { - var result = lodash(value); - result.__chain__ = true; - return result; - } - - /** - * This method invokes `interceptor` and returns `value`. The interceptor - * is invoked with one argument; (value). The purpose of this method is to - * "tap into" a method chain sequence in order to modify intermediate results. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns `value`. - * @example - * - * _([1, 2, 3]) - * .tap(function(array) { - * // Mutate input array. - * array.pop(); - * }) - * .reverse() - * .value(); - * // => [2, 1] - */ - function tap(value, interceptor) { - interceptor(value); - return value; - } - - /** - * This method is like `_.tap` except that it returns the result of `interceptor`. - * The purpose of this method is to "pass thru" values replacing intermediate - * results in a method chain sequence. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns the result of `interceptor`. - * @example - * - * _(' abc ') - * .chain() - * .trim() - * .thru(function(value) { - * return [value]; - * }) - * .value(); - * // => ['abc'] - */ - function thru(value, interceptor) { - return interceptor(value); - } - - /** - * This method is the wrapper version of `_.at`. - * - * @name at - * @memberOf _ - * @since 1.0.0 - * @category Seq - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; - * - * _(object).at(['a[0].b.c', 'a[1]']).value(); - * // => [3, 4] - */ - var wrapperAt = flatRest(function(paths) { - var length = paths.length, - start = length ? paths[0] : 0, - value = this.__wrapped__, - interceptor = function(object) { return baseAt(object, paths); }; - - if (length > 1 || this.__actions__.length || - !(value instanceof LazyWrapper) || !isIndex(start)) { - return this.thru(interceptor); - } - value = value.slice(start, +start + (length ? 1 : 0)); - value.__actions__.push({ - 'func': thru, - 'args': [interceptor], - 'thisArg': undefined - }); - return new LodashWrapper(value, this.__chain__).thru(function(array) { - if (length && !array.length) { - array.push(undefined); - } - return array; - }); - }); - - /** - * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. - * - * @name chain - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 } - * ]; - * - * // A sequence without explicit chaining. - * _(users).head(); - * // => { 'user': 'barney', 'age': 36 } - * - * // A sequence with explicit chaining. - * _(users) - * .chain() - * .head() - * .pick('user') - * .value(); - * // => { 'user': 'barney' } - */ - function wrapperChain() { - return chain(this); - } - - /** - * Executes the chain sequence and returns the wrapped result. - * - * @name commit - * @memberOf _ - * @since 3.2.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var array = [1, 2]; - * var wrapped = _(array).push(3); - * - * console.log(array); - * // => [1, 2] - * - * wrapped = wrapped.commit(); - * console.log(array); - * // => [1, 2, 3] - * - * wrapped.last(); - * // => 3 - * - * console.log(array); - * // => [1, 2, 3] - */ - function wrapperCommit() { - return new LodashWrapper(this.value(), this.__chain__); - } - - /** - * Gets the next value on a wrapped object following the - * [iterator protocol](https://mdn.io/iteration_protocols#iterator). - * - * @name next - * @memberOf _ - * @since 4.0.0 - * @category Seq - * @returns {Object} Returns the next iterator value. - * @example - * - * var wrapped = _([1, 2]); - * - * wrapped.next(); - * // => { 'done': false, 'value': 1 } - * - * wrapped.next(); - * // => { 'done': false, 'value': 2 } - * - * wrapped.next(); - * // => { 'done': true, 'value': undefined } - */ - function wrapperNext() { - if (this.__values__ === undefined) { - this.__values__ = toArray(this.value()); - } - var done = this.__index__ >= this.__values__.length, - value = done ? undefined : this.__values__[this.__index__++]; - - return { 'done': done, 'value': value }; - } - - /** - * Enables the wrapper to be iterable. - * - * @name Symbol.iterator - * @memberOf _ - * @since 4.0.0 - * @category Seq - * @returns {Object} Returns the wrapper object. - * @example - * - * var wrapped = _([1, 2]); - * - * wrapped[Symbol.iterator]() === wrapped; - * // => true - * - * Array.from(wrapped); - * // => [1, 2] - */ - function wrapperToIterator() { - return this; - } - - /** - * Creates a clone of the chain sequence planting `value` as the wrapped value. - * - * @name plant - * @memberOf _ - * @since 3.2.0 - * @category Seq - * @param {*} value The value to plant. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * function square(n) { - * return n * n; - * } - * - * var wrapped = _([1, 2]).map(square); - * var other = wrapped.plant([3, 4]); - * - * other.value(); - * // => [9, 16] - * - * wrapped.value(); - * // => [1, 4] - */ - function wrapperPlant(value) { - var result, - parent = this; - - while (parent instanceof baseLodash) { - var clone = wrapperClone(parent); - clone.__index__ = 0; - clone.__values__ = undefined; - if (result) { - previous.__wrapped__ = clone; - } else { - result = clone; - } - var previous = clone; - parent = parent.__wrapped__; - } - previous.__wrapped__ = value; - return result; - } - - /** - * This method is the wrapper version of `_.reverse`. - * - * **Note:** This method mutates the wrapped array. - * - * @name reverse - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var array = [1, 2, 3]; - * - * _(array).reverse().value() - * // => [3, 2, 1] - * - * console.log(array); - * // => [3, 2, 1] - */ - function wrapperReverse() { - var value = this.__wrapped__; - if (value instanceof LazyWrapper) { - var wrapped = value; - if (this.__actions__.length) { - wrapped = new LazyWrapper(this); - } - wrapped = wrapped.reverse(); - wrapped.__actions__.push({ - 'func': thru, - 'args': [reverse], - 'thisArg': undefined - }); - return new LodashWrapper(wrapped, this.__chain__); - } - return this.thru(reverse); - } - - /** - * Executes the chain sequence to resolve the unwrapped value. - * - * @name value - * @memberOf _ - * @since 0.1.0 - * @alias toJSON, valueOf - * @category Seq - * @returns {*} Returns the resolved unwrapped value. - * @example - * - * _([1, 2, 3]).value(); - * // => [1, 2, 3] - */ - function wrapperValue() { - return baseWrapperValue(this.__wrapped__, this.__actions__); - } - - /*------------------------------------------------------------------------*/ - - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The corresponding value of - * each key is the number of times the key was returned by `iteratee`. The - * iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * _.countBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': 1, '6': 2 } - * - * // The `_.property` iteratee shorthand. - * _.countBy(['one', 'two', 'three'], 'length'); - * // => { '3': 2, '5': 1 } - */ - var countBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - ++result[key]; - } else { - baseAssignValue(result, key, 1); - } - }); - - /** - * Checks if `predicate` returns truthy for **all** elements of `collection`. - * Iteration is stopped once `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * **Note:** This method returns `true` for - * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because - * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of - * elements of empty collections. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - * @example - * - * _.every([true, 1, null, 'yes'], Boolean); - * // => false - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.every(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.every(users, ['active', false]); - * // => true - * - * // The `_.property` iteratee shorthand. - * _.every(users, 'active'); - * // => false - */ - function every(collection, predicate, guard) { - var func = isArray(collection) ? arrayEvery : baseEvery; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined; - } - return func(collection, getIteratee(predicate, 3)); - } - - /** - * Iterates over elements of `collection`, returning an array of all elements - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * **Note:** Unlike `_.remove`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.reject - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * _.filter(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.filter(users, { 'age': 36, 'active': true }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.filter(users, ['active', false]); - * // => objects for ['fred'] - * - * // The `_.property` iteratee shorthand. - * _.filter(users, 'active'); - * // => objects for ['barney'] - * - * // Combining several predicates using `_.overEvery` or `_.overSome`. - * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); - * // => objects for ['fred', 'barney'] - */ - function filter(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, getIteratee(predicate, 3)); - } - - /** - * Iterates over elements of `collection`, returning the first element - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {*} Returns the matched element, else `undefined`. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false }, - * { 'user': 'pebbles', 'age': 1, 'active': true } - * ]; - * - * _.find(users, function(o) { return o.age < 40; }); - * // => object for 'barney' - * - * // The `_.matches` iteratee shorthand. - * _.find(users, { 'age': 1, 'active': true }); - * // => object for 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.find(users, ['active', false]); - * // => object for 'fred' - * - * // The `_.property` iteratee shorthand. - * _.find(users, 'active'); - * // => object for 'barney' - */ - var find = createFind(findIndex); - - /** - * This method is like `_.find` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Collection - * @param {Array|Object} collection The collection to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=collection.length-1] The index to search from. - * @returns {*} Returns the matched element, else `undefined`. - * @example - * - * _.findLast([1, 2, 3, 4], function(n) { - * return n % 2 == 1; - * }); - * // => 3 - */ - var findLast = createFind(findLastIndex); - - /** - * Creates a flattened array of values by running each element in `collection` - * thru `iteratee` and flattening the mapped results. The iteratee is invoked - * with three arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [n, n]; - * } - * - * _.flatMap([1, 2], duplicate); - * // => [1, 1, 2, 2] - */ - function flatMap(collection, iteratee) { - return baseFlatten(map(collection, iteratee), 1); - } - - /** - * This method is like `_.flatMap` except that it recursively flattens the - * mapped results. - * - * @static - * @memberOf _ - * @since 4.7.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [[[n, n]]]; - * } - * - * _.flatMapDeep([1, 2], duplicate); - * // => [1, 1, 2, 2] - */ - function flatMapDeep(collection, iteratee) { - return baseFlatten(map(collection, iteratee), INFINITY); - } - - /** - * This method is like `_.flatMap` except that it recursively flattens the - * mapped results up to `depth` times. - * - * @static - * @memberOf _ - * @since 4.7.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {number} [depth=1] The maximum recursion depth. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [[[n, n]]]; - * } - * - * _.flatMapDepth([1, 2], duplicate, 2); - * // => [[1, 1], [2, 2]] - */ - function flatMapDepth(collection, iteratee, depth) { - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(map(collection, iteratee), depth); - } - - /** - * Iterates over elements of `collection` and invokes `iteratee` for each element. - * The iteratee is invoked with three arguments: (value, index|key, collection). - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * **Note:** As with other "Collections" methods, objects with a "length" - * property are iterated like arrays. To avoid this behavior use `_.forIn` - * or `_.forOwn` for object iteration. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias each - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - * @see _.forEachRight - * @example - * - * _.forEach([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `1` then `2`. - * - * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). - */ - function forEach(collection, iteratee) { - var func = isArray(collection) ? arrayEach : baseEach; - return func(collection, getIteratee(iteratee, 3)); - } - - /** - * This method is like `_.forEach` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @alias eachRight - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - * @see _.forEach - * @example - * - * _.forEachRight([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `2` then `1`. - */ - function forEachRight(collection, iteratee) { - var func = isArray(collection) ? arrayEachRight : baseEachRight; - return func(collection, getIteratee(iteratee, 3)); - } - - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The order of grouped values - * is determined by the order they occur in `collection`. The corresponding - * value of each key is an array of elements responsible for generating the - * key. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * _.groupBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': [4.2], '6': [6.1, 6.3] } - * - * // The `_.property` iteratee shorthand. - * _.groupBy(['one', 'two', 'three'], 'length'); - * // => { '3': ['one', 'two'], '5': ['three'] } - */ - var groupBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - result[key].push(value); - } else { - baseAssignValue(result, key, [value]); - } - }); - - /** - * Checks if `value` is in `collection`. If `collection` is a string, it's - * checked for a substring of `value`, otherwise - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * is used for equality comparisons. If `fromIndex` is negative, it's used as - * the offset from the end of `collection`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {boolean} Returns `true` if `value` is found, else `false`. - * @example - * - * _.includes([1, 2, 3], 1); - * // => true - * - * _.includes([1, 2, 3], 1, 2); - * // => false - * - * _.includes({ 'a': 1, 'b': 2 }, 1); - * // => true - * - * _.includes('abcd', 'bc'); - * // => true - */ - function includes(collection, value, fromIndex, guard) { - collection = isArrayLike(collection) ? collection : values(collection); - fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; - - var length = collection.length; - if (fromIndex < 0) { - fromIndex = nativeMax(length + fromIndex, 0); - } - return isString(collection) - ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) - : (!!length && baseIndexOf(collection, value, fromIndex) > -1); - } - - /** - * Invokes the method at `path` of each element in `collection`, returning - * an array of the results of each invoked method. Any additional arguments - * are provided to each invoked method. If `path` is a function, it's invoked - * for, and `this` bound to, each element in `collection`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Array|Function|string} path The path of the method to invoke or - * the function invoked per iteration. - * @param {...*} [args] The arguments to invoke each method with. - * @returns {Array} Returns the array of results. - * @example - * - * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); - * // => [[1, 5, 7], [1, 2, 3]] - * - * _.invokeMap([123, 456], String.prototype.split, ''); - * // => [['1', '2', '3'], ['4', '5', '6']] - */ - var invokeMap = baseRest(function(collection, path, args) { - var index = -1, - isFunc = typeof path == 'function', - result = isArrayLike(collection) ? Array(collection.length) : []; - - baseEach(collection, function(value) { - result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); - }); - return result; - }); - - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The corresponding value of - * each key is the last element responsible for generating the key. The - * iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * var array = [ - * { 'dir': 'left', 'code': 97 }, - * { 'dir': 'right', 'code': 100 } - * ]; - * - * _.keyBy(array, function(o) { - * return String.fromCharCode(o.code); - * }); - * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } - * - * _.keyBy(array, 'dir'); - * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } - */ - var keyBy = createAggregator(function(result, value, key) { - baseAssignValue(result, key, value); - }); - - /** - * Creates an array of values by running each element in `collection` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. - * - * The guarded methods are: - * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, - * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, - * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, - * `template`, `trim`, `trimEnd`, `trimStart`, and `words` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - * @example - * - * function square(n) { - * return n * n; - * } - * - * _.map([4, 8], square); - * // => [16, 64] - * - * _.map({ 'a': 4, 'b': 8 }, square); - * // => [16, 64] (iteration order is not guaranteed) - * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; - * - * // The `_.property` iteratee shorthand. - * _.map(users, 'user'); - * // => ['barney', 'fred'] - */ - function map(collection, iteratee) { - var func = isArray(collection) ? arrayMap : baseMap; - return func(collection, getIteratee(iteratee, 3)); - } - - /** - * This method is like `_.sortBy` except that it allows specifying the sort - * orders of the iteratees to sort by. If `orders` is unspecified, all values - * are sorted in ascending order. Otherwise, specify an order of "desc" for - * descending or "asc" for ascending sort order of corresponding values. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] - * The iteratees to sort by. - * @param {string[]} [orders] The sort orders of `iteratees`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {Array} Returns the new sorted array. - * @example - * - * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 34 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'barney', 'age': 36 } - * ]; - * - * // Sort by `user` in ascending order and by `age` in descending order. - * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); - * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] - */ - function orderBy(collection, iteratees, orders, guard) { - if (collection == null) { - return []; - } - if (!isArray(iteratees)) { - iteratees = iteratees == null ? [] : [iteratees]; - } - orders = guard ? undefined : orders; - if (!isArray(orders)) { - orders = orders == null ? [] : [orders]; - } - return baseOrderBy(collection, iteratees, orders); - } - - /** - * Creates an array of elements split into two groups, the first of which - * contains elements `predicate` returns truthy for, the second of which - * contains elements `predicate` returns falsey for. The predicate is - * invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the array of grouped elements. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true }, - * { 'user': 'pebbles', 'age': 1, 'active': false } - * ]; - * - * _.partition(users, function(o) { return o.active; }); - * // => objects for [['fred'], ['barney', 'pebbles']] - * - * // The `_.matches` iteratee shorthand. - * _.partition(users, { 'age': 1, 'active': false }); - * // => objects for [['pebbles'], ['barney', 'fred']] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.partition(users, ['active', false]); - * // => objects for [['barney', 'pebbles'], ['fred']] - * - * // The `_.property` iteratee shorthand. - * _.partition(users, 'active'); - * // => objects for [['fred'], ['barney', 'pebbles']] - */ - var partition = createAggregator(function(result, value, key) { - result[key ? 0 : 1].push(value); - }, function() { return [[], []]; }); - - /** - * Reduces `collection` to a value which is the accumulated result of running - * each element in `collection` thru `iteratee`, where each successive - * invocation is supplied the return value of the previous. If `accumulator` - * is not given, the first element of `collection` is used as the initial - * value. The iteratee is invoked with four arguments: - * (accumulator, value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.reduce`, `_.reduceRight`, and `_.transform`. - * - * The guarded methods are: - * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, - * and `sortBy` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduceRight - * @example - * - * _.reduce([1, 2], function(sum, n) { - * return sum + n; - * }, 0); - * // => 3 - * - * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * return result; - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) - */ - function reduce(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduce : baseReduce, - initAccum = arguments.length < 3; - - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); - } - - /** - * This method is like `_.reduce` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduce - * @example - * - * var array = [[0, 1], [2, 3], [4, 5]]; - * - * _.reduceRight(array, function(flattened, other) { - * return flattened.concat(other); - * }, []); - * // => [4, 5, 2, 3, 0, 1] - */ - function reduceRight(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduceRight : baseReduce, - initAccum = arguments.length < 3; - - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); - } - - /** - * The opposite of `_.filter`; this method returns the elements of `collection` - * that `predicate` does **not** return truthy for. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.filter - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true } - * ]; - * - * _.reject(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.reject(users, { 'age': 40, 'active': true }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.reject(users, ['active', false]); - * // => objects for ['fred'] - * - * // The `_.property` iteratee shorthand. - * _.reject(users, 'active'); - * // => objects for ['barney'] - */ - function reject(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, negate(getIteratee(predicate, 3))); - } - - /** - * Gets a random element from `collection`. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. - * @example - * - * _.sample([1, 2, 3, 4]); - * // => 2 - */ - function sample(collection) { - var func = isArray(collection) ? arraySample : baseSample; - return func(collection); - } - - /** - * Gets `n` random elements at unique keys from `collection` up to the - * size of `collection`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @param {number} [n=1] The number of elements to sample. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the random elements. - * @example - * - * _.sampleSize([1, 2, 3], 2); - * // => [3, 1] - * - * _.sampleSize([1, 2, 3], 4); - * // => [2, 3, 1] - */ - function sampleSize(collection, n, guard) { - if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { - n = 1; - } else { - n = toInteger(n); - } - var func = isArray(collection) ? arraySampleSize : baseSampleSize; - return func(collection, n); - } - - /** - * Creates an array of shuffled values, using a version of the - * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to shuffle. - * @returns {Array} Returns the new shuffled array. - * @example - * - * _.shuffle([1, 2, 3, 4]); - * // => [4, 1, 3, 2] - */ - function shuffle(collection) { - var func = isArray(collection) ? arrayShuffle : baseShuffle; - return func(collection); - } - - /** - * Gets the size of `collection` by returning its length for array-like - * values or the number of own enumerable string keyed properties for objects. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @returns {number} Returns the collection size. - * @example - * - * _.size([1, 2, 3]); - * // => 3 - * - * _.size({ 'a': 1, 'b': 2 }); - * // => 2 - * - * _.size('pebbles'); - * // => 7 - */ - function size(collection) { - if (collection == null) { - return 0; - } - if (isArrayLike(collection)) { - return isString(collection) ? stringSize(collection) : collection.length; - } - var tag = getTag(collection); - if (tag == mapTag || tag == setTag) { - return collection.size; - } - return baseKeys(collection).length; - } - - /** - * Checks if `predicate` returns truthy for **any** element of `collection`. - * Iteration is stopped once `predicate` returns truthy. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - * @example - * - * _.some([null, 0, 'yes', false], Boolean); - * // => true - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.some(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.some(users, ['active', false]); - * // => true - * - * // The `_.property` iteratee shorthand. - * _.some(users, 'active'); - * // => true - */ - function some(collection, predicate, guard) { - var func = isArray(collection) ? arraySome : baseSome; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined; - } - return func(collection, getIteratee(predicate, 3)); - } - - /** - * Creates an array of elements, sorted in ascending order by the results of - * running each element in a collection thru each iteratee. This method - * performs a stable sort, that is, it preserves the original sort order of - * equal elements. The iteratees are invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {...(Function|Function[])} [iteratees=[_.identity]] - * The iteratees to sort by. - * @returns {Array} Returns the new sorted array. - * @example - * - * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 30 }, - * { 'user': 'barney', 'age': 34 } - * ]; - * - * _.sortBy(users, [function(o) { return o.user; }]); - * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] - * - * _.sortBy(users, ['user', 'age']); - * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] - */ - var sortBy = baseRest(function(collection, iteratees) { - if (collection == null) { - return []; - } - var length = iteratees.length; - if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { - iteratees = []; - } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { - iteratees = [iteratees[0]]; - } - return baseOrderBy(collection, baseFlatten(iteratees, 1), []); - }); - - /*------------------------------------------------------------------------*/ - - /** - * Gets the timestamp of the number of milliseconds that have elapsed since - * the Unix epoch (1 January 1970 00:00:00 UTC). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Date - * @returns {number} Returns the timestamp. - * @example - * - * _.defer(function(stamp) { - * console.log(_.now() - stamp); - * }, _.now()); - * // => Logs the number of milliseconds it took for the deferred invocation. - */ - var now = ctxNow || function() { - return root.Date.now(); - }; - - /*------------------------------------------------------------------------*/ - - /** - * The opposite of `_.before`; this method creates a function that invokes - * `func` once it's called `n` or more times. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {number} n The number of calls before `func` is invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var saves = ['profile', 'settings']; - * - * var done = _.after(saves.length, function() { - * console.log('done saving!'); - * }); - * - * _.forEach(saves, function(type) { - * asyncSave({ 'type': type, 'complete': done }); - * }); - * // => Logs 'done saving!' after the two async saves have completed. - */ - function after(n, func) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - n = toInteger(n); - return function() { - if (--n < 1) { - return func.apply(this, arguments); - } - }; - } - - /** - * Creates a function that invokes `func`, with up to `n` arguments, - * ignoring any additional arguments. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to cap arguments for. - * @param {number} [n=func.length] The arity cap. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new capped function. - * @example - * - * _.map(['6', '8', '10'], _.ary(parseInt, 1)); - * // => [6, 8, 10] - */ - function ary(func, n, guard) { - n = guard ? undefined : n; - n = (func && n == null) ? func.length : n; - return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); - } - - /** - * Creates a function that invokes `func`, with the `this` binding and arguments - * of the created function, while it's called less than `n` times. Subsequent - * calls to the created function return the result of the last `func` invocation. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {number} n The number of calls at which `func` is no longer invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * jQuery(element).on('click', _.before(5, addContactToList)); - * // => Allows adding up to 4 contacts to the list. - */ - function before(n, func) { - var result; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - n = toInteger(n); - return function() { - if (--n > 0) { - result = func.apply(this, arguments); - } - if (n <= 1) { - func = undefined; - } - return result; - }; - } - - /** - * Creates a function that invokes `func` with the `this` binding of `thisArg` - * and `partials` prepended to the arguments it receives. - * - * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, - * may be used as a placeholder for partially applied arguments. - * - * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" - * property of bound functions. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to bind. - * @param {*} thisArg The `this` binding of `func`. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * function greet(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } - * - * var object = { 'user': 'fred' }; - * - * var bound = _.bind(greet, object, 'hi'); - * bound('!'); - * // => 'hi fred!' - * - * // Bound with placeholders. - * var bound = _.bind(greet, object, _, '!'); - * bound('hi'); - * // => 'hi fred!' - */ - var bind = baseRest(function(func, thisArg, partials) { - var bitmask = WRAP_BIND_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bind)); - bitmask |= WRAP_PARTIAL_FLAG; - } - return createWrap(func, bitmask, thisArg, partials, holders); - }); - - /** - * Creates a function that invokes the method at `object[key]` with `partials` - * prepended to the arguments it receives. - * - * This method differs from `_.bind` by allowing bound functions to reference - * methods that may be redefined or don't yet exist. See - * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) - * for more details. - * - * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * @static - * @memberOf _ - * @since 0.10.0 - * @category Function - * @param {Object} object The object to invoke the method on. - * @param {string} key The key of the method. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * var object = { - * 'user': 'fred', - * 'greet': function(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } - * }; - * - * var bound = _.bindKey(object, 'greet', 'hi'); - * bound('!'); - * // => 'hi fred!' - * - * object.greet = function(greeting, punctuation) { - * return greeting + 'ya ' + this.user + punctuation; - * }; - * - * bound('!'); - * // => 'hiya fred!' - * - * // Bound with placeholders. - * var bound = _.bindKey(object, 'greet', _, '!'); - * bound('hi'); - * // => 'hiya fred!' - */ - var bindKey = baseRest(function(object, key, partials) { - var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bindKey)); - bitmask |= WRAP_PARTIAL_FLAG; - } - return createWrap(key, bitmask, object, partials, holders); - }); - - /** - * Creates a function that accepts arguments of `func` and either invokes - * `func` returning its result, if at least `arity` number of arguments have - * been provided, or returns a function that accepts the remaining `func` - * arguments, and so on. The arity of `func` may be specified if `func.length` - * is not sufficient. - * - * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, - * may be used as a placeholder for provided arguments. - * - * **Note:** This method doesn't set the "length" property of curried functions. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Function - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new curried function. - * @example - * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; - * - * var curried = _.curry(abc); - * - * curried(1)(2)(3); - * // => [1, 2, 3] - * - * curried(1, 2)(3); - * // => [1, 2, 3] - * - * curried(1, 2, 3); - * // => [1, 2, 3] - * - * // Curried with placeholders. - * curried(1)(_, 3)(2); - * // => [1, 2, 3] - */ - function curry(func, arity, guard) { - arity = guard ? undefined : arity; - var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); - result.placeholder = curry.placeholder; - return result; - } - - /** - * This method is like `_.curry` except that arguments are applied to `func` - * in the manner of `_.partialRight` instead of `_.partial`. - * - * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for provided arguments. - * - * **Note:** This method doesn't set the "length" property of curried functions. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new curried function. - * @example - * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; - * - * var curried = _.curryRight(abc); - * - * curried(3)(2)(1); - * // => [1, 2, 3] - * - * curried(2, 3)(1); - * // => [1, 2, 3] - * - * curried(1, 2, 3); - * // => [1, 2, 3] - * - * // Curried with placeholders. - * curried(3)(1, _)(2); - * // => [1, 2, 3] - */ - function curryRight(func, arity, guard) { - arity = guard ? undefined : arity; - var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); - result.placeholder = curryRight.placeholder; - return result; - } - - /** - * Creates a debounced function that delays invoking `func` until after `wait` - * milliseconds have elapsed since the last time the debounced function was - * invoked. The debounced function comes with a `cancel` method to cancel - * delayed `func` invocations and a `flush` method to immediately invoke them. - * Provide `options` to indicate whether `func` should be invoked on the - * leading and/or trailing edge of the `wait` timeout. The `func` is invoked - * with the last arguments provided to the debounced function. Subsequent - * calls to the debounced function return the result of the last `func` - * invocation. - * - * **Note:** If `leading` and `trailing` options are `true`, `func` is - * invoked on the trailing edge of the timeout only if the debounced function - * is invoked more than once during the `wait` timeout. - * - * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred - * until to the next tick, similar to `setTimeout` with a timeout of `0`. - * - * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) - * for details over the differences between `_.debounce` and `_.throttle`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to debounce. - * @param {number} [wait=0] The number of milliseconds to delay. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.leading=false] - * Specify invoking on the leading edge of the timeout. - * @param {number} [options.maxWait] - * The maximum time `func` is allowed to be delayed before it's invoked. - * @param {boolean} [options.trailing=true] - * Specify invoking on the trailing edge of the timeout. - * @returns {Function} Returns the new debounced function. - * @example - * - * // Avoid costly calculations while the window size is in flux. - * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); - * - * // Invoke `sendMail` when clicked, debouncing subsequent calls. - * jQuery(element).on('click', _.debounce(sendMail, 300, { - * 'leading': true, - * 'trailing': false - * })); - * - * // Ensure `batchLog` is invoked once after 1 second of debounced calls. - * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); - * var source = new EventSource('/stream'); - * jQuery(source).on('message', debounced); - * - * // Cancel the trailing debounced invocation. - * jQuery(window).on('popstate', debounced.cancel); - */ - function debounce(func, wait, options) { - var lastArgs, - lastThis, - maxWait, - result, - timerId, - lastCallTime, - lastInvokeTime = 0, - leading = false, - maxing = false, - trailing = true; - - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - wait = toNumber(wait) || 0; - if (isObject(options)) { - leading = !!options.leading; - maxing = 'maxWait' in options; - maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; - trailing = 'trailing' in options ? !!options.trailing : trailing; - } - - function invokeFunc(time) { - var args = lastArgs, - thisArg = lastThis; - - lastArgs = lastThis = undefined; - lastInvokeTime = time; - result = func.apply(thisArg, args); - return result; - } - - function leadingEdge(time) { - // Reset any `maxWait` timer. - lastInvokeTime = time; - // Start the timer for the trailing edge. - timerId = setTimeout(timerExpired, wait); - // Invoke the leading edge. - return leading ? invokeFunc(time) : result; - } - - function remainingWait(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime, - timeWaiting = wait - timeSinceLastCall; - - return maxing - ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) - : timeWaiting; - } - - function shouldInvoke(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime; - - // Either this is the first call, activity has stopped and we're at the - // trailing edge, the system time has gone backwards and we're treating - // it as the trailing edge, or we've hit the `maxWait` limit. - return (lastCallTime === undefined || (timeSinceLastCall >= wait) || - (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); - } - - function timerExpired() { - var time = now(); - if (shouldInvoke(time)) { - return trailingEdge(time); - } - // Restart the timer. - timerId = setTimeout(timerExpired, remainingWait(time)); - } - - function trailingEdge(time) { - timerId = undefined; - - // Only invoke if we have `lastArgs` which means `func` has been - // debounced at least once. - if (trailing && lastArgs) { - return invokeFunc(time); - } - lastArgs = lastThis = undefined; - return result; - } - - function cancel() { - if (timerId !== undefined) { - clearTimeout(timerId); - } - lastInvokeTime = 0; - lastArgs = lastCallTime = lastThis = timerId = undefined; - } - - function flush() { - return timerId === undefined ? result : trailingEdge(now()); - } - - function debounced() { - var time = now(), - isInvoking = shouldInvoke(time); - - lastArgs = arguments; - lastThis = this; - lastCallTime = time; - - if (isInvoking) { - if (timerId === undefined) { - return leadingEdge(lastCallTime); - } - if (maxing) { - // Handle invocations in a tight loop. - clearTimeout(timerId); - timerId = setTimeout(timerExpired, wait); - return invokeFunc(lastCallTime); - } - } - if (timerId === undefined) { - timerId = setTimeout(timerExpired, wait); - } - return result; - } - debounced.cancel = cancel; - debounced.flush = flush; - return debounced; - } - - /** - * Defers invoking the `func` until the current call stack has cleared. Any - * additional arguments are provided to `func` when it's invoked. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to defer. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {number} Returns the timer id. - * @example - * - * _.defer(function(text) { - * console.log(text); - * }, 'deferred'); - * // => Logs 'deferred' after one millisecond. - */ - var defer = baseRest(function(func, args) { - return baseDelay(func, 1, args); - }); - - /** - * Invokes `func` after `wait` milliseconds. Any additional arguments are - * provided to `func` when it's invoked. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {number} Returns the timer id. - * @example - * - * _.delay(function(text) { - * console.log(text); - * }, 1000, 'later'); - * // => Logs 'later' after one second. - */ - var delay = baseRest(function(func, wait, args) { - return baseDelay(func, toNumber(wait) || 0, args); - }); - - /** - * Creates a function that invokes `func` with arguments reversed. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to flip arguments for. - * @returns {Function} Returns the new flipped function. - * @example - * - * var flipped = _.flip(function() { - * return _.toArray(arguments); - * }); - * - * flipped('a', 'b', 'c', 'd'); - * // => ['d', 'c', 'b', 'a'] - */ - function flip(func) { - return createWrap(func, WRAP_FLIP_FLAG); - } - - /** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `clear`, `delete`, `get`, `has`, and `set`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] - * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] - * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; - */ - function memoize(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; - - if (cache.has(key)) { - return cache.get(key); - } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; - } - - // Expose `MapCache`. - memoize.Cache = MapCache; - - /** - * Creates a function that negates the result of the predicate `func`. The - * `func` predicate is invoked with the `this` binding and arguments of the - * created function. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} predicate The predicate to negate. - * @returns {Function} Returns the new negated function. - * @example - * - * function isEven(n) { - * return n % 2 == 0; - * } - * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] - */ - function negate(predicate) { - if (typeof predicate != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return function() { - var args = arguments; - switch (args.length) { - case 0: return !predicate.call(this); - case 1: return !predicate.call(this, args[0]); - case 2: return !predicate.call(this, args[0], args[1]); - case 3: return !predicate.call(this, args[0], args[1], args[2]); - } - return !predicate.apply(this, args); - }; - } - - /** - * Creates a function that is restricted to invoking `func` once. Repeat calls - * to the function return the value of the first invocation. The `func` is - * invoked with the `this` binding and arguments of the created function. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var initialize = _.once(createApplication); - * initialize(); - * initialize(); - * // => `createApplication` is invoked once - */ - function once(func) { - return before(2, func); - } - - /** - * Creates a function that invokes `func` with its arguments transformed. - * - * @static - * @since 4.0.0 - * @memberOf _ - * @category Function - * @param {Function} func The function to wrap. - * @param {...(Function|Function[])} [transforms=[_.identity]] - * The argument transforms. - * @returns {Function} Returns the new function. - * @example - * - * function doubled(n) { - * return n * 2; - * } - * - * function square(n) { - * return n * n; - * } - * - * var func = _.overArgs(function(x, y) { - * return [x, y]; - * }, [square, doubled]); - * - * func(9, 3); - * // => [81, 6] - * - * func(10, 5); - * // => [100, 10] - */ - var overArgs = castRest(function(func, transforms) { - transforms = (transforms.length == 1 && isArray(transforms[0])) - ? arrayMap(transforms[0], baseUnary(getIteratee())) - : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); - - var funcsLength = transforms.length; - return baseRest(function(args) { - var index = -1, - length = nativeMin(args.length, funcsLength); - - while (++index < length) { - args[index] = transforms[index].call(this, args[index]); - } - return apply(func, this, args); - }); - }); - - /** - * Creates a function that invokes `func` with `partials` prepended to the - * arguments it receives. This method is like `_.bind` except it does **not** - * alter the `this` binding. - * - * The `_.partial.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * **Note:** This method doesn't set the "length" property of partially - * applied functions. - * - * @static - * @memberOf _ - * @since 0.2.0 - * @category Function - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. - * @example - * - * function greet(greeting, name) { - * return greeting + ' ' + name; - * } - * - * var sayHelloTo = _.partial(greet, 'hello'); - * sayHelloTo('fred'); - * // => 'hello fred' - * - * // Partially applied with placeholders. - * var greetFred = _.partial(greet, _, 'fred'); - * greetFred('hi'); - * // => 'hi fred' - */ - var partial = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partial)); - return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); - }); - - /** - * This method is like `_.partial` except that partially applied arguments - * are appended to the arguments it receives. - * - * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * **Note:** This method doesn't set the "length" property of partially - * applied functions. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Function - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. - * @example - * - * function greet(greeting, name) { - * return greeting + ' ' + name; - * } - * - * var greetFred = _.partialRight(greet, 'fred'); - * greetFred('hi'); - * // => 'hi fred' - * - * // Partially applied with placeholders. - * var sayHelloTo = _.partialRight(greet, 'hello', _); - * sayHelloTo('fred'); - * // => 'hello fred' - */ - var partialRight = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partialRight)); - return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); - }); - - /** - * Creates a function that invokes `func` with arguments arranged according - * to the specified `indexes` where the argument value at the first index is - * provided as the first argument, the argument value at the second index is - * provided as the second argument, and so on. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to rearrange arguments for. - * @param {...(number|number[])} indexes The arranged argument indexes. - * @returns {Function} Returns the new function. - * @example - * - * var rearged = _.rearg(function(a, b, c) { - * return [a, b, c]; - * }, [2, 0, 1]); - * - * rearged('b', 'c', 'a') - * // => ['a', 'b', 'c'] - */ - var rearg = flatRest(function(func, indexes) { - return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); - }); - - /** - * Creates a function that invokes `func` with the `this` binding of the - * created function and arguments from `start` and beyond provided as - * an array. - * - * **Note:** This method is based on the - * [rest parameter](https://mdn.io/rest_parameters). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - * @example - * - * var say = _.rest(function(what, names) { - * return what + ' ' + _.initial(names).join(', ') + - * (_.size(names) > 1 ? ', & ' : '') + _.last(names); - * }); - * - * say('hello', 'fred', 'barney', 'pebbles'); - * // => 'hello fred, barney, & pebbles' - */ - function rest(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - start = start === undefined ? start : toInteger(start); - return baseRest(func, start); - } - - /** - * Creates a function that invokes `func` with the `this` binding of the - * create function and an array of arguments much like - * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). - * - * **Note:** This method is based on the - * [spread operator](https://mdn.io/spread_operator). - * - * @static - * @memberOf _ - * @since 3.2.0 - * @category Function - * @param {Function} func The function to spread arguments over. - * @param {number} [start=0] The start position of the spread. - * @returns {Function} Returns the new function. - * @example - * - * var say = _.spread(function(who, what) { - * return who + ' says ' + what; - * }); - * - * say(['fred', 'hello']); - * // => 'fred says hello' - * - * var numbers = Promise.all([ - * Promise.resolve(40), - * Promise.resolve(36) - * ]); - * - * numbers.then(_.spread(function(x, y) { - * return x + y; - * })); - * // => a Promise of 76 - */ - function spread(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - start = start == null ? 0 : nativeMax(toInteger(start), 0); - return baseRest(function(args) { - var array = args[start], - otherArgs = castSlice(args, 0, start); - - if (array) { - arrayPush(otherArgs, array); - } - return apply(func, this, otherArgs); - }); - } - - /** - * Creates a throttled function that only invokes `func` at most once per - * every `wait` milliseconds. The throttled function comes with a `cancel` - * method to cancel delayed `func` invocations and a `flush` method to - * immediately invoke them. Provide `options` to indicate whether `func` - * should be invoked on the leading and/or trailing edge of the `wait` - * timeout. The `func` is invoked with the last arguments provided to the - * throttled function. Subsequent calls to the throttled function return the - * result of the last `func` invocation. - * - * **Note:** If `leading` and `trailing` options are `true`, `func` is - * invoked on the trailing edge of the timeout only if the throttled function - * is invoked more than once during the `wait` timeout. - * - * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred - * until to the next tick, similar to `setTimeout` with a timeout of `0`. - * - * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) - * for details over the differences between `_.throttle` and `_.debounce`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to throttle. - * @param {number} [wait=0] The number of milliseconds to throttle invocations to. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.leading=true] - * Specify invoking on the leading edge of the timeout. - * @param {boolean} [options.trailing=true] - * Specify invoking on the trailing edge of the timeout. - * @returns {Function} Returns the new throttled function. - * @example - * - * // Avoid excessively updating the position while scrolling. - * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); - * - * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. - * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); - * jQuery(element).on('click', throttled); - * - * // Cancel the trailing throttled invocation. - * jQuery(window).on('popstate', throttled.cancel); - */ - function throttle(func, wait, options) { - var leading = true, - trailing = true; - - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - if (isObject(options)) { - leading = 'leading' in options ? !!options.leading : leading; - trailing = 'trailing' in options ? !!options.trailing : trailing; - } - return debounce(func, wait, { - 'leading': leading, - 'maxWait': wait, - 'trailing': trailing - }); - } - - /** - * Creates a function that accepts up to one argument, ignoring any - * additional arguments. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - * @example - * - * _.map(['6', '8', '10'], _.unary(parseInt)); - * // => [6, 8, 10] - */ - function unary(func) { - return ary(func, 1); - } - - /** - * Creates a function that provides `value` to `wrapper` as its first - * argument. Any additional arguments provided to the function are appended - * to those provided to the `wrapper`. The wrapper is invoked with the `this` - * binding of the created function. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {*} value The value to wrap. - * @param {Function} [wrapper=identity] The wrapper function. - * @returns {Function} Returns the new function. - * @example - * - * var p = _.wrap(_.escape, function(func, text) { - * return '

' + func(text) + '

'; - * }); - * - * p('fred, barney, & pebbles'); - * // => '

fred, barney, & pebbles

' - */ - function wrap(value, wrapper) { - return partial(castFunction(wrapper), value); - } - - /*------------------------------------------------------------------------*/ - - /** - * Casts `value` as an array if it's not one. - * - * @static - * @memberOf _ - * @since 4.4.0 - * @category Lang - * @param {*} value The value to inspect. - * @returns {Array} Returns the cast array. - * @example - * - * _.castArray(1); - * // => [1] - * - * _.castArray({ 'a': 1 }); - * // => [{ 'a': 1 }] - * - * _.castArray('abc'); - * // => ['abc'] - * - * _.castArray(null); - * // => [null] - * - * _.castArray(undefined); - * // => [undefined] - * - * _.castArray(); - * // => [] - * - * var array = [1, 2, 3]; - * console.log(_.castArray(array) === array); - * // => true - */ - function castArray() { - if (!arguments.length) { - return []; - } - var value = arguments[0]; - return isArray(value) ? value : [value]; - } - - /** - * Creates a shallow clone of `value`. - * - * **Note:** This method is loosely based on the - * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) - * and supports cloning arrays, array buffers, booleans, date objects, maps, - * numbers, `Object` objects, regexes, sets, strings, symbols, and typed - * arrays. The own enumerable properties of `arguments` objects are cloned - * as plain objects. An empty object is returned for uncloneable values such - * as error objects, functions, DOM nodes, and WeakMaps. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to clone. - * @returns {*} Returns the cloned value. - * @see _.cloneDeep - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var shallow = _.clone(objects); - * console.log(shallow[0] === objects[0]); - * // => true - */ - function clone(value) { - return baseClone(value, CLONE_SYMBOLS_FLAG); - } - - /** - * This method is like `_.clone` except that it accepts `customizer` which - * is invoked to produce the cloned value. If `customizer` returns `undefined`, - * cloning is handled by the method instead. The `customizer` is invoked with - * up to four arguments; (value [, index|key, object, stack]). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to clone. - * @param {Function} [customizer] The function to customize cloning. - * @returns {*} Returns the cloned value. - * @see _.cloneDeepWith - * @example - * - * function customizer(value) { - * if (_.isElement(value)) { - * return value.cloneNode(false); - * } - * } - * - * var el = _.cloneWith(document.body, customizer); - * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 0 - */ - function cloneWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); - } - - /** - * This method is like `_.clone` except that it recursively clones `value`. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @returns {*} Returns the deep cloned value. - * @see _.clone - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var deep = _.cloneDeep(objects); - * console.log(deep[0] === objects[0]); - * // => false - */ - function cloneDeep(value) { - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); - } - - /** - * This method is like `_.cloneWith` except that it recursively clones `value`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @param {Function} [customizer] The function to customize cloning. - * @returns {*} Returns the deep cloned value. - * @see _.cloneWith - * @example - * - * function customizer(value) { - * if (_.isElement(value)) { - * return value.cloneNode(true); - * } - * } - * - * var el = _.cloneDeepWith(document.body, customizer); - * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 20 - */ - function cloneDeepWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); - } - - /** - * Checks if `object` conforms to `source` by invoking the predicate - * properties of `source` with the corresponding property values of `object`. - * - * **Note:** This method is equivalent to `_.conforms` when `source` is - * partially applied. - * - * @static - * @memberOf _ - * @since 4.14.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property predicates to conform to. - * @returns {boolean} Returns `true` if `object` conforms, else `false`. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * - * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); - * // => true - * - * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); - * // => false - */ - function conformsTo(object, source) { - return source == null || baseConformsTo(object, source, keys(source)); - } - - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ - function eq(value, other) { - return value === other || (value !== value && other !== other); - } - - /** - * Checks if `value` is greater than `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than `other`, - * else `false`. - * @see _.lt - * @example - * - * _.gt(3, 1); - * // => true - * - * _.gt(3, 3); - * // => false - * - * _.gt(1, 3); - * // => false - */ - var gt = createRelationalOperation(baseGt); - - /** - * Checks if `value` is greater than or equal to `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than or equal to - * `other`, else `false`. - * @see _.lte - * @example - * - * _.gte(3, 1); - * // => true - * - * _.gte(3, 3); - * // => true - * - * _.gte(1, 3); - * // => false - */ - var gte = createRelationalOperation(function(value, other) { - return value >= other; - }); - - /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); - }; - - /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ - var isArray = Array.isArray; - - /** - * Checks if `value` is classified as an `ArrayBuffer` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. - * @example - * - * _.isArrayBuffer(new ArrayBuffer(2)); - * // => true - * - * _.isArrayBuffer(new Array(2)); - * // => false - */ - var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; - - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - - /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); - } - - /** - * Checks if `value` is classified as a boolean primitive or object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. - * @example - * - * _.isBoolean(false); - * // => true - * - * _.isBoolean(null); - * // => false - */ - function isBoolean(value) { - return value === true || value === false || - (isObjectLike(value) && baseGetTag(value) == boolTag); - } - - /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ - var isBuffer = nativeIsBuffer || stubFalse; - - /** - * Checks if `value` is classified as a `Date` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a date object, else `false`. - * @example - * - * _.isDate(new Date); - * // => true - * - * _.isDate('Mon April 23 2012'); - * // => false - */ - var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; - - /** - * Checks if `value` is likely a DOM element. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. - * @example - * - * _.isElement(document.body); - * // => true - * - * _.isElement(''); - * // => false - */ - function isElement(value) { - return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); - } - - /** - * Checks if `value` is an empty object, collection, map, or set. - * - * Objects are considered empty if they have no own enumerable string keyed - * properties. - * - * Array-like values such as `arguments` objects, arrays, buffers, strings, or - * jQuery-like collections are considered empty if they have a `length` of `0`. - * Similarly, maps and sets are considered empty if they have a `size` of `0`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is empty, else `false`. - * @example - * - * _.isEmpty(null); - * // => true - * - * _.isEmpty(true); - * // => true - * - * _.isEmpty(1); - * // => true - * - * _.isEmpty([1, 2, 3]); - * // => false - * - * _.isEmpty({ 'a': 1 }); - * // => false - */ - function isEmpty(value) { - if (value == null) { - return true; - } - if (isArrayLike(value) && - (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || - isBuffer(value) || isTypedArray(value) || isArguments(value))) { - return !value.length; - } - var tag = getTag(value); - if (tag == mapTag || tag == setTag) { - return !value.size; - } - if (isPrototype(value)) { - return !baseKeys(value).length; - } - for (var key in value) { - if (hasOwnProperty.call(value, key)) { - return false; - } - } - return true; - } - - /** - * Performs a deep comparison between two values to determine if they are - * equivalent. - * - * **Note:** This method supports comparing arrays, array buffers, booleans, - * date objects, error objects, maps, numbers, `Object` objects, regexes, - * sets, strings, symbols, and typed arrays. `Object` objects are compared - * by their own, not inherited, enumerable properties. Functions and DOM - * nodes are compared by strict equality, i.e. `===`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.isEqual(object, other); - * // => true - * - * object === other; - * // => false - */ - function isEqual(value, other) { - return baseIsEqual(value, other); - } - - /** - * This method is like `_.isEqual` except that it accepts `customizer` which - * is invoked to compare values. If `customizer` returns `undefined`, comparisons - * are handled by the method instead. The `customizer` is invoked with up to - * six arguments: (objValue, othValue [, index|key, object, other, stack]). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * function isGreeting(value) { - * return /^h(?:i|ello)$/.test(value); - * } - * - * function customizer(objValue, othValue) { - * if (isGreeting(objValue) && isGreeting(othValue)) { - * return true; - * } - * } - * - * var array = ['hello', 'goodbye']; - * var other = ['hi', 'goodbye']; - * - * _.isEqualWith(array, other, customizer); - * // => true - */ - function isEqualWith(value, other, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - var result = customizer ? customizer(value, other) : undefined; - return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; - } - - /** - * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, - * `SyntaxError`, `TypeError`, or `URIError` object. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an error object, else `false`. - * @example - * - * _.isError(new Error); - * // => true - * - * _.isError(Error); - * // => false - */ - function isError(value) { - if (!isObjectLike(value)) { - return false; - } - var tag = baseGetTag(value); - return tag == errorTag || tag == domExcTag || - (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); - } - - /** - * Checks if `value` is a finite primitive number. - * - * **Note:** This method is based on - * [`Number.isFinite`](https://mdn.io/Number/isFinite). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. - * @example - * - * _.isFinite(3); - * // => true - * - * _.isFinite(Number.MIN_VALUE); - * // => true - * - * _.isFinite(Infinity); - * // => false - * - * _.isFinite('3'); - * // => false - */ - function isFinite(value) { - return typeof value == 'number' && nativeIsFinite(value); - } - - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction(value) { - if (!isObject(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; - } - - /** - * Checks if `value` is an integer. - * - * **Note:** This method is based on - * [`Number.isInteger`](https://mdn.io/Number/isInteger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an integer, else `false`. - * @example - * - * _.isInteger(3); - * // => true - * - * _.isInteger(Number.MIN_VALUE); - * // => false - * - * _.isInteger(Infinity); - * // => false - * - * _.isInteger('3'); - * // => false - */ - function isInteger(value) { - return typeof value == 'number' && value == toInteger(value); - } - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; - } - - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ - function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); - } - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ - function isObjectLike(value) { - return value != null && typeof value == 'object'; - } - - /** - * Checks if `value` is classified as a `Map` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. - * @example - * - * _.isMap(new Map); - * // => true - * - * _.isMap(new WeakMap); - * // => false - */ - var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; - - /** - * Performs a partial deep comparison between `object` and `source` to - * determine if `object` contains equivalent property values. - * - * **Note:** This method is equivalent to `_.matches` when `source` is - * partially applied. - * - * Partial comparisons will match empty array and empty object `source` - * values against any array or object value, respectively. See `_.isEqual` - * for a list of supported value comparisons. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * - * _.isMatch(object, { 'b': 2 }); - * // => true - * - * _.isMatch(object, { 'b': 1 }); - * // => false - */ - function isMatch(object, source) { - return object === source || baseIsMatch(object, source, getMatchData(source)); - } - - /** - * This method is like `_.isMatch` except that it accepts `customizer` which - * is invoked to compare values. If `customizer` returns `undefined`, comparisons - * are handled by the method instead. The `customizer` is invoked with five - * arguments: (objValue, srcValue, index|key, object, source). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - * @example - * - * function isGreeting(value) { - * return /^h(?:i|ello)$/.test(value); - * } - * - * function customizer(objValue, srcValue) { - * if (isGreeting(objValue) && isGreeting(srcValue)) { - * return true; - * } - * } - * - * var object = { 'greeting': 'hello' }; - * var source = { 'greeting': 'hi' }; - * - * _.isMatchWith(object, source, customizer); - * // => true - */ - function isMatchWith(object, source, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseIsMatch(object, source, getMatchData(source), customizer); - } - - /** - * Checks if `value` is `NaN`. - * - * **Note:** This method is based on - * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as - * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for - * `undefined` and other non-number values. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - * @example - * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true - * - * _.isNaN(undefined); - * // => false - */ - function isNaN(value) { - // An `NaN` primitive is the only value that is not equal to itself. - // Perform the `toStringTag` check first to avoid errors with some - // ActiveX objects in IE. - return isNumber(value) && value != +value; - } - - /** - * Checks if `value` is a pristine native function. - * - * **Note:** This method can't reliably detect native functions in the presence - * of the core-js package because core-js circumvents this kind of detection. - * Despite multiple requests, the core-js maintainer has made it clear: any - * attempt to fix the detection will be obstructed. As a result, we're left - * with little choice but to throw an error. Unfortunately, this also affects - * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), - * which rely on core-js. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - * @example - * - * _.isNative(Array.prototype.push); - * // => true - * - * _.isNative(_); - * // => false - */ - function isNative(value) { - if (isMaskable(value)) { - throw new Error(CORE_ERROR_TEXT); - } - return baseIsNative(value); - } - - /** - * Checks if `value` is `null`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `null`, else `false`. - * @example - * - * _.isNull(null); - * // => true - * - * _.isNull(void 0); - * // => false - */ - function isNull(value) { - return value === null; - } - - /** - * Checks if `value` is `null` or `undefined`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is nullish, else `false`. - * @example - * - * _.isNil(null); - * // => true - * - * _.isNil(void 0); - * // => true - * - * _.isNil(NaN); - * // => false - */ - function isNil(value) { - return value == null; - } - - /** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are - * classified as numbers, use the `_.isFinite` method. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a number, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true - * - * _.isNumber('3'); - * // => false - */ - function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && baseGetTag(value) == numberTag); - } - - /** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ - function isPlainObject(value) { - if (!isObjectLike(value) || baseGetTag(value) != objectTag) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; - } - var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && - funcToString.call(Ctor) == objectCtorString; - } - - /** - * Checks if `value` is classified as a `RegExp` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - * @example - * - * _.isRegExp(/abc/); - * // => true - * - * _.isRegExp('/abc/'); - * // => false - */ - var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; - - /** - * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 - * double precision number which isn't the result of a rounded unsafe integer. - * - * **Note:** This method is based on - * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. - * @example - * - * _.isSafeInteger(3); - * // => true - * - * _.isSafeInteger(Number.MIN_VALUE); - * // => false - * - * _.isSafeInteger(Infinity); - * // => false - * - * _.isSafeInteger('3'); - * // => false - */ - function isSafeInteger(value) { - return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; - } - - /** - * Checks if `value` is classified as a `Set` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. - * @example - * - * _.isSet(new Set); - * // => true - * - * _.isSet(new WeakSet); - * // => false - */ - var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; - - /** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ - function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); - } - - /** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ - function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); - } - - /** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - - /** - * Checks if `value` is `undefined`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. - * @example - * - * _.isUndefined(void 0); - * // => true - * - * _.isUndefined(null); - * // => false - */ - function isUndefined(value) { - return value === undefined; - } - - /** - * Checks if `value` is classified as a `WeakMap` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. - * @example - * - * _.isWeakMap(new WeakMap); - * // => true - * - * _.isWeakMap(new Map); - * // => false - */ - function isWeakMap(value) { - return isObjectLike(value) && getTag(value) == weakMapTag; - } - - /** - * Checks if `value` is classified as a `WeakSet` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. - * @example - * - * _.isWeakSet(new WeakSet); - * // => true - * - * _.isWeakSet(new Set); - * // => false - */ - function isWeakSet(value) { - return isObjectLike(value) && baseGetTag(value) == weakSetTag; - } - - /** - * Checks if `value` is less than `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than `other`, - * else `false`. - * @see _.gt - * @example - * - * _.lt(1, 3); - * // => true - * - * _.lt(3, 3); - * // => false - * - * _.lt(3, 1); - * // => false - */ - var lt = createRelationalOperation(baseLt); - - /** - * Checks if `value` is less than or equal to `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than or equal to - * `other`, else `false`. - * @see _.gte - * @example - * - * _.lte(1, 3); - * // => true - * - * _.lte(3, 3); - * // => true - * - * _.lte(3, 1); - * // => false - */ - var lte = createRelationalOperation(function(value, other) { - return value <= other; - }); - - /** - * Converts `value` to an array. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to convert. - * @returns {Array} Returns the converted array. - * @example - * - * _.toArray({ 'a': 1, 'b': 2 }); - * // => [1, 2] - * - * _.toArray('abc'); - * // => ['a', 'b', 'c'] - * - * _.toArray(1); - * // => [] - * - * _.toArray(null); - * // => [] - */ - function toArray(value) { - if (!value) { - return []; - } - if (isArrayLike(value)) { - return isString(value) ? stringToArray(value) : copyArray(value); - } - if (symIterator && value[symIterator]) { - return iteratorToArray(value[symIterator]()); - } - var tag = getTag(value), - func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); - - return func(value); - } - - /** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toFinite('3.2'); - * // => 3.2 - */ - function toFinite(value) { - if (!value) { - return value === 0 ? value : 0; - } - value = toNumber(value); - if (value === INFINITY || value === -INFINITY) { - var sign = (value < 0 ? -1 : 1); - return sign * MAX_INTEGER; - } - return value === value ? value : 0; - } - - /** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toInteger('3.2'); - * // => 3 - */ - function toInteger(value) { - var result = toFinite(value), - remainder = result % 1; - - return result === result ? (remainder ? result - remainder : result) : 0; - } - - /** - * Converts `value` to an integer suitable for use as the length of an - * array-like object. - * - * **Note:** This method is based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toLength(3.2); - * // => 3 - * - * _.toLength(Number.MIN_VALUE); - * // => 0 - * - * _.toLength(Infinity); - * // => 4294967295 - * - * _.toLength('3.2'); - * // => 3 - */ - function toLength(value) { - return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; - } - - /** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ - function toNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - if (isObject(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject(other) ? (other + '') : other; - } - if (typeof value != 'string') { - return value === 0 ? value : +value; - } - value = value.replace(reTrim, ''); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); - } - - /** - * Converts `value` to a plain object flattening inherited enumerable string - * keyed properties of `value` to own properties of the plain object. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {Object} Returns the converted plain object. - * @example - * - * function Foo() { - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.assign({ 'a': 1 }, new Foo); - * // => { 'a': 1, 'b': 2 } - * - * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); - * // => { 'a': 1, 'b': 2, 'c': 3 } - */ - function toPlainObject(value) { - return copyObject(value, keysIn(value)); - } - - /** - * Converts `value` to a safe integer. A safe integer can be compared and - * represented correctly. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toSafeInteger(3.2); - * // => 3 - * - * _.toSafeInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toSafeInteger(Infinity); - * // => 9007199254740991 - * - * _.toSafeInteger('3.2'); - * // => 3 - */ - function toSafeInteger(value) { - return value - ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) - : (value === 0 ? value : 0); - } - - /** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ - function toString(value) { - return value == null ? '' : baseToString(value); - } - - /*------------------------------------------------------------------------*/ - - /** - * Assigns own enumerable string keyed properties of source objects to the - * destination object. Source objects are applied from left to right. - * Subsequent sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object` and is loosely based on - * [`Object.assign`](https://mdn.io/Object/assign). - * - * @static - * @memberOf _ - * @since 0.10.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.assignIn - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } - * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; - * - * _.assign({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'c': 3 } - */ - var assign = createAssigner(function(object, source) { - if (isPrototype(source) || isArrayLike(source)) { - copyObject(source, keys(source), object); - return; - } - for (var key in source) { - if (hasOwnProperty.call(source, key)) { - assignValue(object, key, source[key]); - } - } - }); - - /** - * This method is like `_.assign` except that it iterates over own and - * inherited source properties. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias extend - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.assign - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } - * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; - * - * _.assignIn({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } - */ - var assignIn = createAssigner(function(object, source) { - copyObject(source, keysIn(source), object); - }); - - /** - * This method is like `_.assignIn` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias extendWith - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignWith - * @example - * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignInWith, customizer); - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ - var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keysIn(source), object, customizer); - }); - - /** - * This method is like `_.assign` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignInWith - * @example - * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignWith, customizer); - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ - var assignWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keys(source), object, customizer); - }); - - /** - * Creates an array of values corresponding to `paths` of `object`. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Array} Returns the picked values. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; - * - * _.at(object, ['a[0].b.c', 'a[1]']); - * // => [3, 4] - */ - var at = flatRest(baseAt); - - /** - * Creates an object that inherits from the `prototype` object. If a - * `properties` object is given, its own enumerable string keyed properties - * are assigned to the created object. - * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Object - * @param {Object} prototype The object to inherit from. - * @param {Object} [properties] The properties to assign to the object. - * @returns {Object} Returns the new object. - * @example - * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } - * - * function Circle() { - * Shape.call(this); - * } - * - * Circle.prototype = _.create(Shape.prototype, { - * 'constructor': Circle - * }); - * - * var circle = new Circle; - * circle instanceof Circle; - * // => true - * - * circle instanceof Shape; - * // => true - */ - function create(prototype, properties) { - var result = baseCreate(prototype); - return properties == null ? result : baseAssign(result, properties); - } - - /** - * Assigns own and inherited enumerable string keyed properties of source - * objects to the destination object for all destination properties that - * resolve to `undefined`. Source objects are applied from left to right. - * Once a property is set, additional values of the same property are ignored. - * - * **Note:** This method mutates `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaultsDeep - * @example - * - * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ - var defaults = baseRest(function(object, sources) { - object = Object(object); - - var index = -1; - var length = sources.length; - var guard = length > 2 ? sources[2] : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - length = 1; - } - - while (++index < length) { - var source = sources[index]; - var props = keysIn(source); - var propsIndex = -1; - var propsLength = props.length; - - while (++propsIndex < propsLength) { - var key = props[propsIndex]; - var value = object[key]; - - if (value === undefined || - (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { - object[key] = source[key]; - } - } - } - - return object; - }); - - /** - * This method is like `_.defaults` except that it recursively assigns - * default properties. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 3.10.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaults - * @example - * - * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); - * // => { 'a': { 'b': 2, 'c': 3 } } - */ - var defaultsDeep = baseRest(function(args) { - args.push(undefined, customDefaultsMerge); - return apply(mergeWith, undefined, args); - }); - - /** - * This method is like `_.find` except that it returns the key of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. - * @example - * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findKey(users, function(o) { return o.age < 40; }); - * // => 'barney' (iteration order is not guaranteed) - * - * // The `_.matches` iteratee shorthand. - * _.findKey(users, { 'age': 1, 'active': true }); - * // => 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findKey(users, ['active', false]); - * // => 'fred' - * - * // The `_.property` iteratee shorthand. - * _.findKey(users, 'active'); - * // => 'barney' - */ - function findKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); - } - - /** - * This method is like `_.findKey` except that it iterates over elements of - * a collection in the opposite order. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. - * @example - * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findLastKey(users, function(o) { return o.age < 40; }); - * // => returns 'pebbles' assuming `_.findKey` returns 'barney' - * - * // The `_.matches` iteratee shorthand. - * _.findLastKey(users, { 'age': 36, 'active': true }); - * // => 'barney' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findLastKey(users, ['active', false]); - * // => 'fred' - * - * // The `_.property` iteratee shorthand. - * _.findLastKey(users, 'active'); - * // => 'pebbles' - */ - function findLastKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); - } - - /** - * Iterates over own and inherited enumerable string keyed properties of an - * object and invokes `iteratee` for each property. The iteratee is invoked - * with three arguments: (value, key, object). Iteratee functions may exit - * iteration early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @since 0.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forInRight - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forIn(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). - */ - function forIn(object, iteratee) { - return object == null - ? object - : baseFor(object, getIteratee(iteratee, 3), keysIn); - } - - /** - * This method is like `_.forIn` except that it iterates over properties of - * `object` in the opposite order. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forIn - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forInRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. - */ - function forInRight(object, iteratee) { - return object == null - ? object - : baseForRight(object, getIteratee(iteratee, 3), keysIn); - } - - /** - * Iterates over own enumerable string keyed properties of an object and - * invokes `iteratee` for each property. The iteratee is invoked with three - * arguments: (value, key, object). Iteratee functions may exit iteration - * early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @since 0.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forOwnRight - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forOwn(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). - */ - function forOwn(object, iteratee) { - return object && baseForOwn(object, getIteratee(iteratee, 3)); - } - - /** - * This method is like `_.forOwn` except that it iterates over properties of - * `object` in the opposite order. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forOwn - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forOwnRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. - */ - function forOwnRight(object, iteratee) { - return object && baseForOwnRight(object, getIteratee(iteratee, 3)); - } - - /** - * Creates an array of function property names from own enumerable properties - * of `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functionsIn - * @example - * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); - * } - * - * Foo.prototype.c = _.constant('c'); - * - * _.functions(new Foo); - * // => ['a', 'b'] - */ - function functions(object) { - return object == null ? [] : baseFunctions(object, keys(object)); - } - - /** - * Creates an array of function property names from own and inherited - * enumerable properties of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functions - * @example - * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); - * } - * - * Foo.prototype.c = _.constant('c'); - * - * _.functionsIn(new Foo); - * // => ['a', 'b', 'c'] - */ - function functionsIn(object) { - return object == null ? [] : baseFunctions(object, keysIn(object)); - } - - /** - * Gets the value at `path` of `object`. If the resolved value is - * `undefined`, the `defaultValue` is returned in its place. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 - * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' - */ - function get(object, path, defaultValue) { - var result = object == null ? undefined : baseGet(object, path); - return result === undefined ? defaultValue : result; - } - - /** - * Checks if `path` is a direct property of `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = { 'a': { 'b': 2 } }; - * var other = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.has(object, 'a'); - * // => true - * - * _.has(object, 'a.b'); - * // => true - * - * _.has(object, ['a', 'b']); - * // => true - * - * _.has(other, 'a'); - * // => false - */ - function has(object, path) { - return object != null && hasPath(object, path, baseHas); - } - - /** - * Checks if `path` is a direct or inherited property of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.hasIn(object, 'a'); - * // => true - * - * _.hasIn(object, 'a.b'); - * // => true - * - * _.hasIn(object, ['a', 'b']); - * // => true - * - * _.hasIn(object, 'b'); - * // => false - */ - function hasIn(object, path) { - return object != null && hasPath(object, path, baseHasIn); - } - - /** - * Creates an object composed of the inverted keys and values of `object`. - * If `object` contains duplicate values, subsequent values overwrite - * property assignments of previous values. - * - * @static - * @memberOf _ - * @since 0.7.0 - * @category Object - * @param {Object} object The object to invert. - * @returns {Object} Returns the new inverted object. - * @example - * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; - * - * _.invert(object); - * // => { '1': 'c', '2': 'b' } - */ - var invert = createInverter(function(result, value, key) { - if (value != null && - typeof value.toString != 'function') { - value = nativeObjectToString.call(value); - } - - result[value] = key; - }, constant(identity)); - - /** - * This method is like `_.invert` except that the inverted object is generated - * from the results of running each element of `object` thru `iteratee`. The - * corresponding inverted value of each inverted key is an array of keys - * responsible for generating the inverted value. The iteratee is invoked - * with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.1.0 - * @category Object - * @param {Object} object The object to invert. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Object} Returns the new inverted object. - * @example - * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; - * - * _.invertBy(object); - * // => { '1': ['a', 'c'], '2': ['b'] } - * - * _.invertBy(object, function(value) { - * return 'group' + value; - * }); - * // => { 'group1': ['a', 'c'], 'group2': ['b'] } - */ - var invertBy = createInverter(function(result, value, key) { - if (value != null && - typeof value.toString != 'function') { - value = nativeObjectToString.call(value); - } - - if (hasOwnProperty.call(result, value)) { - result[value].push(key); - } else { - result[value] = [key]; - } - }, getIteratee); - - /** - * Invokes the method at `path` of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the method to invoke. - * @param {...*} [args] The arguments to invoke the method with. - * @returns {*} Returns the result of the invoked method. - * @example - * - * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; - * - * _.invoke(object, 'a[0].b.c.slice', 1, 3); - * // => [2, 3] - */ - var invoke = baseRest(baseInvoke); - - /** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ - function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); - } - - /** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ - function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); - } - - /** - * The opposite of `_.mapValues`; this method creates an object with the - * same values as `object` and keys generated by running each own enumerable - * string keyed property of `object` thru `iteratee`. The iteratee is invoked - * with three arguments: (value, key, object). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapValues - * @example - * - * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { - * return key + value; - * }); - * // => { 'a1': 1, 'b2': 2 } - */ - function mapKeys(object, iteratee) { - var result = {}; - iteratee = getIteratee(iteratee, 3); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, iteratee(value, key, object), value); - }); - return result; - } - - /** - * Creates an object with the same keys as `object` and values generated - * by running each own enumerable string keyed property of `object` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, key, object). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapKeys - * @example - * - * var users = { - * 'fred': { 'user': 'fred', 'age': 40 }, - * 'pebbles': { 'user': 'pebbles', 'age': 1 } - * }; - * - * _.mapValues(users, function(o) { return o.age; }); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - * - * // The `_.property` iteratee shorthand. - * _.mapValues(users, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - */ - function mapValues(object, iteratee) { - var result = {}; - iteratee = getIteratee(iteratee, 3); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, key, iteratee(value, key, object)); - }); - return result; - } - - /** - * This method is like `_.assign` except that it recursively merges own and - * inherited enumerable string keyed properties of source objects into the - * destination object. Source properties that resolve to `undefined` are - * skipped if a destination value exists. Array and plain object properties - * are merged recursively. Other objects and value types are overridden by - * assignment. Source objects are applied from left to right. Subsequent - * sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @example - * - * var object = { - * 'a': [{ 'b': 2 }, { 'd': 4 }] - * }; - * - * var other = { - * 'a': [{ 'c': 3 }, { 'e': 5 }] - * }; - * - * _.merge(object, other); - * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } - */ - var merge = createAssigner(function(object, source, srcIndex) { - baseMerge(object, source, srcIndex); - }); - - /** - * This method is like `_.merge` except that it accepts `customizer` which - * is invoked to produce the merged values of the destination and source - * properties. If `customizer` returns `undefined`, merging is handled by the - * method instead. The `customizer` is invoked with six arguments: - * (objValue, srcValue, key, object, source, stack). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} customizer The function to customize assigned values. - * @returns {Object} Returns `object`. - * @example - * - * function customizer(objValue, srcValue) { - * if (_.isArray(objValue)) { - * return objValue.concat(srcValue); - * } - * } - * - * var object = { 'a': [1], 'b': [2] }; - * var other = { 'a': [3], 'b': [4] }; - * - * _.mergeWith(object, other, customizer); - * // => { 'a': [1, 3], 'b': [2, 4] } - */ - var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { - baseMerge(object, source, srcIndex, customizer); - }); - - /** - * The opposite of `_.pick`; this method creates an object composed of the - * own and inherited enumerable property paths of `object` that are not omitted. - * - * **Note:** This method is considerably slower than `_.pick`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {...(string|string[])} [paths] The property paths to omit. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omit(object, ['a', 'c']); - * // => { 'b': '2' } - */ - var omit = flatRest(function(object, paths) { - var result = {}; - if (object == null) { - return result; - } - var isDeep = false; - paths = arrayMap(paths, function(path) { - path = castPath(path, object); - isDeep || (isDeep = path.length > 1); - return path; - }); - copyObject(object, getAllKeysIn(object), result); - if (isDeep) { - result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); - } - var length = paths.length; - while (length--) { - baseUnset(result, paths[length]); - } - return result; - }); - - /** - * The opposite of `_.pickBy`; this method creates an object composed of - * the own and inherited enumerable string keyed properties of `object` that - * `predicate` doesn't return truthy for. The predicate is invoked with two - * arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omitBy(object, _.isNumber); - * // => { 'b': '2' } - */ - function omitBy(object, predicate) { - return pickBy(object, negate(getIteratee(predicate))); - } - - /** - * Creates an object composed of the picked `object` properties. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pick(object, ['a', 'c']); - * // => { 'a': 1, 'c': 3 } - */ - var pick = flatRest(function(object, paths) { - return object == null ? {} : basePick(object, paths); - }); - - /** - * Creates an object composed of the `object` properties `predicate` returns - * truthy for. The predicate is invoked with two arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pickBy(object, _.isNumber); - * // => { 'a': 1, 'c': 3 } - */ - function pickBy(object, predicate) { - if (object == null) { - return {}; - } - var props = arrayMap(getAllKeysIn(object), function(prop) { - return [prop]; - }); - predicate = getIteratee(predicate); - return basePickBy(object, props, function(value, path) { - return predicate(value, path[0]); - }); - } - - /** - * This method is like `_.get` except that if the resolved value is a - * function it's invoked with the `this` binding of its parent object and - * its result is returned. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to resolve. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; - * - * _.result(object, 'a[0].b.c1'); - * // => 3 - * - * _.result(object, 'a[0].b.c2'); - * // => 4 - * - * _.result(object, 'a[0].b.c3', 'default'); - * // => 'default' - * - * _.result(object, 'a[0].b.c3', _.constant('default')); - * // => 'default' - */ - function result(object, path, defaultValue) { - path = castPath(path, object); - - var index = -1, - length = path.length; - - // Ensure the loop is entered when path is empty. - if (!length) { - length = 1; - object = undefined; - } - while (++index < length) { - var value = object == null ? undefined : object[toKey(path[index])]; - if (value === undefined) { - index = length; - value = defaultValue; - } - object = isFunction(value) ? value.call(object) : value; - } - return object; - } - - /** - * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, - * it's created. Arrays are created for missing index properties while objects - * are created for all other missing properties. Use `_.setWith` to customize - * `path` creation. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @returns {Object} Returns `object`. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.set(object, 'a[0].b.c', 4); - * console.log(object.a[0].b.c); - * // => 4 - * - * _.set(object, ['x', '0', 'y', 'z'], 5); - * console.log(object.x[0].y.z); - * // => 5 - */ - function set(object, path, value) { - return object == null ? object : baseSet(object, path, value); - } - - /** - * This method is like `_.set` except that it accepts `customizer` which is - * invoked to produce the objects of `path`. If `customizer` returns `undefined` - * path creation is handled by the method instead. The `customizer` is invoked - * with three arguments: (nsValue, key, nsObject). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @example - * - * var object = {}; - * - * _.setWith(object, '[0][1]', 'a', Object); - * // => { '0': { '1': 'a' } } - */ - function setWith(object, path, value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return object == null ? object : baseSet(object, path, value, customizer); - } - - /** - * Creates an array of own enumerable string keyed-value pairs for `object` - * which can be consumed by `_.fromPairs`. If `object` is a map or set, its - * entries are returned. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias entries - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.toPairs(new Foo); - * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) - */ - var toPairs = createToPairs(keys); - - /** - * Creates an array of own and inherited enumerable string keyed-value pairs - * for `object` which can be consumed by `_.fromPairs`. If `object` is a map - * or set, its entries are returned. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias entriesIn - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.toPairsIn(new Foo); - * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) - */ - var toPairsIn = createToPairs(keysIn); - - /** - * An alternative to `_.reduce`; this method transforms `object` to a new - * `accumulator` object which is the result of running each of its own - * enumerable string keyed properties thru `iteratee`, with each invocation - * potentially mutating the `accumulator` object. If `accumulator` is not - * provided, a new object with the same `[[Prototype]]` will be used. The - * iteratee is invoked with four arguments: (accumulator, value, key, object). - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @since 1.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The custom accumulator value. - * @returns {*} Returns the accumulated value. - * @example - * - * _.transform([2, 3, 4], function(result, n) { - * result.push(n *= n); - * return n % 2 == 0; - * }, []); - * // => [4, 9] - * - * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } - */ - function transform(object, iteratee, accumulator) { - var isArr = isArray(object), - isArrLike = isArr || isBuffer(object) || isTypedArray(object); - - iteratee = getIteratee(iteratee, 4); - if (accumulator == null) { - var Ctor = object && object.constructor; - if (isArrLike) { - accumulator = isArr ? new Ctor : []; - } - else if (isObject(object)) { - accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; - } - else { - accumulator = {}; - } - } - (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { - return iteratee(accumulator, value, index, object); - }); - return accumulator; - } - - /** - * Removes the property at `path` of `object`. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to unset. - * @returns {boolean} Returns `true` if the property is deleted, else `false`. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 7 } }] }; - * _.unset(object, 'a[0].b.c'); - * // => true - * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; - * - * _.unset(object, ['a', '0', 'b', 'c']); - * // => true - * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; - */ - function unset(object, path) { - return object == null ? true : baseUnset(object, path); - } - - /** - * This method is like `_.set` except that accepts `updater` to produce the - * value to set. Use `_.updateWith` to customize `path` creation. The `updater` - * is invoked with one argument: (value). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.6.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {Function} updater The function to produce the updated value. - * @returns {Object} Returns `object`. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.update(object, 'a[0].b.c', function(n) { return n * n; }); - * console.log(object.a[0].b.c); - * // => 9 - * - * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); - * console.log(object.x[0].y.z); - * // => 0 - */ - function update(object, path, updater) { - return object == null ? object : baseUpdate(object, path, castFunction(updater)); - } - - /** - * This method is like `_.update` except that it accepts `customizer` which is - * invoked to produce the objects of `path`. If `customizer` returns `undefined` - * path creation is handled by the method instead. The `customizer` is invoked - * with three arguments: (nsValue, key, nsObject). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.6.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {Function} updater The function to produce the updated value. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @example - * - * var object = {}; - * - * _.updateWith(object, '[0][1]', _.constant('a'), Object); - * // => { '0': { '1': 'a' } } - */ - function updateWith(object, path, updater, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); - } - - /** - * Creates an array of the own enumerable string keyed property values of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.values(new Foo); - * // => [1, 2] (iteration order is not guaranteed) - * - * _.values('hi'); - * // => ['h', 'i'] - */ - function values(object) { - return object == null ? [] : baseValues(object, keys(object)); - } - - /** - * Creates an array of the own and inherited enumerable string keyed property - * values of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.valuesIn(new Foo); - * // => [1, 2, 3] (iteration order is not guaranteed) - */ - function valuesIn(object) { - return object == null ? [] : baseValues(object, keysIn(object)); - } - - /*------------------------------------------------------------------------*/ - - /** - * Clamps `number` within the inclusive `lower` and `upper` bounds. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Number - * @param {number} number The number to clamp. - * @param {number} [lower] The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the clamped number. - * @example - * - * _.clamp(-10, -5, 5); - * // => -5 - * - * _.clamp(10, -5, 5); - * // => 5 - */ - function clamp(number, lower, upper) { - if (upper === undefined) { - upper = lower; - lower = undefined; - } - if (upper !== undefined) { - upper = toNumber(upper); - upper = upper === upper ? upper : 0; - } - if (lower !== undefined) { - lower = toNumber(lower); - lower = lower === lower ? lower : 0; - } - return baseClamp(toNumber(number), lower, upper); - } - - /** - * Checks if `n` is between `start` and up to, but not including, `end`. If - * `end` is not specified, it's set to `start` with `start` then set to `0`. - * If `start` is greater than `end` the params are swapped to support - * negative ranges. - * - * @static - * @memberOf _ - * @since 3.3.0 - * @category Number - * @param {number} number The number to check. - * @param {number} [start=0] The start of the range. - * @param {number} end The end of the range. - * @returns {boolean} Returns `true` if `number` is in the range, else `false`. - * @see _.range, _.rangeRight - * @example - * - * _.inRange(3, 2, 4); - * // => true - * - * _.inRange(4, 8); - * // => true - * - * _.inRange(4, 2); - * // => false - * - * _.inRange(2, 2); - * // => false - * - * _.inRange(1.2, 2); - * // => true - * - * _.inRange(5.2, 4); - * // => false - * - * _.inRange(-3, -2, -6); - * // => true - */ - function inRange(number, start, end) { - start = toFinite(start); - if (end === undefined) { - end = start; - start = 0; - } else { - end = toFinite(end); - } - number = toNumber(number); - return baseInRange(number, start, end); - } - - /** - * Produces a random number between the inclusive `lower` and `upper` bounds. - * If only one argument is provided a number between `0` and the given number - * is returned. If `floating` is `true`, or either `lower` or `upper` are - * floats, a floating-point number is returned instead of an integer. - * - * **Note:** JavaScript follows the IEEE-754 standard for resolving - * floating-point values which can produce unexpected results. - * - * @static - * @memberOf _ - * @since 0.7.0 - * @category Number - * @param {number} [lower=0] The lower bound. - * @param {number} [upper=1] The upper bound. - * @param {boolean} [floating] Specify returning a floating-point number. - * @returns {number} Returns the random number. - * @example - * - * _.random(0, 5); - * // => an integer between 0 and 5 - * - * _.random(5); - * // => also an integer between 0 and 5 - * - * _.random(5, true); - * // => a floating-point number between 0 and 5 - * - * _.random(1.2, 5.2); - * // => a floating-point number between 1.2 and 5.2 - */ - function random(lower, upper, floating) { - if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { - upper = floating = undefined; - } - if (floating === undefined) { - if (typeof upper == 'boolean') { - floating = upper; - upper = undefined; - } - else if (typeof lower == 'boolean') { - floating = lower; - lower = undefined; - } - } - if (lower === undefined && upper === undefined) { - lower = 0; - upper = 1; - } - else { - lower = toFinite(lower); - if (upper === undefined) { - upper = lower; - lower = 0; - } else { - upper = toFinite(upper); - } - } - if (lower > upper) { - var temp = lower; - lower = upper; - upper = temp; - } - if (floating || lower % 1 || upper % 1) { - var rand = nativeRandom(); - return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); - } - return baseRandom(lower, upper); - } - - /*------------------------------------------------------------------------*/ - - /** - * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the camel cased string. - * @example - * - * _.camelCase('Foo Bar'); - * // => 'fooBar' - * - * _.camelCase('--foo-bar--'); - * // => 'fooBar' - * - * _.camelCase('__FOO_BAR__'); - * // => 'fooBar' - */ - var camelCase = createCompounder(function(result, word, index) { - word = word.toLowerCase(); - return result + (index ? capitalize(word) : word); - }); - - /** - * Converts the first character of `string` to upper case and the remaining - * to lower case. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to capitalize. - * @returns {string} Returns the capitalized string. - * @example - * - * _.capitalize('FRED'); - * // => 'Fred' - */ - function capitalize(string) { - return upperFirst(toString(string).toLowerCase()); - } - - /** - * Deburrs `string` by converting - * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) - * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) - * letters to basic Latin letters and removing - * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to deburr. - * @returns {string} Returns the deburred string. - * @example - * - * _.deburr('déjà vu'); - * // => 'deja vu' - */ - function deburr(string) { - string = toString(string); - return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); - } - - /** - * Checks if `string` ends with the given target string. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to inspect. - * @param {string} [target] The string to search for. - * @param {number} [position=string.length] The position to search up to. - * @returns {boolean} Returns `true` if `string` ends with `target`, - * else `false`. - * @example - * - * _.endsWith('abc', 'c'); - * // => true - * - * _.endsWith('abc', 'b'); - * // => false - * - * _.endsWith('abc', 'b', 2); - * // => true - */ - function endsWith(string, target, position) { - string = toString(string); - target = baseToString(target); - - var length = string.length; - position = position === undefined - ? length - : baseClamp(toInteger(position), 0, length); - - var end = position; - position -= target.length; - return position >= 0 && string.slice(position, end) == target; - } - - /** - * Converts the characters "&", "<", ">", '"', and "'" in `string` to their - * corresponding HTML entities. - * - * **Note:** No other characters are escaped. To escape additional - * characters use a third-party library like [_he_](https://mths.be/he). - * - * Though the ">" character is escaped for symmetry, characters like - * ">" and "/" don't need escaping in HTML and have no special meaning - * unless they're part of a tag or unquoted attribute value. See - * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) - * (under "semi-related fun fact") for more details. - * - * When working with HTML you should always - * [quote attribute values](http://wonko.com/post/html-escaping) to reduce - * XSS vectors. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. - * @example - * - * _.escape('fred, barney, & pebbles'); - * // => 'fred, barney, & pebbles' - */ - function escape(string) { - string = toString(string); - return (string && reHasUnescapedHtml.test(string)) - ? string.replace(reUnescapedHtml, escapeHtmlChar) - : string; - } - - /** - * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", - * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. - * @example - * - * _.escapeRegExp('[lodash](https://lodash.com/)'); - * // => '\[lodash\]\(https://lodash\.com/\)' - */ - function escapeRegExp(string) { - string = toString(string); - return (string && reHasRegExpChar.test(string)) - ? string.replace(reRegExpChar, '\\$&') - : string; - } - - /** - * Converts `string` to - * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the kebab cased string. - * @example - * - * _.kebabCase('Foo Bar'); - * // => 'foo-bar' - * - * _.kebabCase('fooBar'); - * // => 'foo-bar' - * - * _.kebabCase('__FOO_BAR__'); - * // => 'foo-bar' - */ - var kebabCase = createCompounder(function(result, word, index) { - return result + (index ? '-' : '') + word.toLowerCase(); - }); - - /** - * Converts `string`, as space separated words, to lower case. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the lower cased string. - * @example - * - * _.lowerCase('--Foo-Bar--'); - * // => 'foo bar' - * - * _.lowerCase('fooBar'); - * // => 'foo bar' - * - * _.lowerCase('__FOO_BAR__'); - * // => 'foo bar' - */ - var lowerCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + word.toLowerCase(); - }); - - /** - * Converts the first character of `string` to lower case. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.lowerFirst('Fred'); - * // => 'fred' - * - * _.lowerFirst('FRED'); - * // => 'fRED' - */ - var lowerFirst = createCaseFirst('toLowerCase'); - - /** - * Pads `string` on the left and right sides if it's shorter than `length`. - * Padding characters are truncated if they can't be evenly divided by `length`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. - * @example - * - * _.pad('abc', 8); - * // => ' abc ' - * - * _.pad('abc', 8, '_-'); - * // => '_-abc_-_' - * - * _.pad('abc', 3); - * // => 'abc' - */ - function pad(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - if (!length || strLength >= length) { - return string; - } - var mid = (length - strLength) / 2; - return ( - createPadding(nativeFloor(mid), chars) + - string + - createPadding(nativeCeil(mid), chars) - ); - } - - /** - * Pads `string` on the right side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. - * @example - * - * _.padEnd('abc', 6); - * // => 'abc ' - * - * _.padEnd('abc', 6, '_-'); - * // => 'abc_-_' - * - * _.padEnd('abc', 3); - * // => 'abc' - */ - function padEnd(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - return (length && strLength < length) - ? (string + createPadding(length - strLength, chars)) - : string; - } - - /** - * Pads `string` on the left side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. - * @example - * - * _.padStart('abc', 6); - * // => ' abc' - * - * _.padStart('abc', 6, '_-'); - * // => '_-_abc' - * - * _.padStart('abc', 3); - * // => 'abc' - */ - function padStart(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - return (length && strLength < length) - ? (createPadding(length - strLength, chars) + string) - : string; - } - - /** - * Converts `string` to an integer of the specified radix. If `radix` is - * `undefined` or `0`, a `radix` of `10` is used unless `value` is a - * hexadecimal, in which case a `radix` of `16` is used. - * - * **Note:** This method aligns with the - * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category String - * @param {string} string The string to convert. - * @param {number} [radix=10] The radix to interpret `value` by. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {number} Returns the converted integer. - * @example - * - * _.parseInt('08'); - * // => 8 - * - * _.map(['6', '08', '10'], _.parseInt); - * // => [6, 8, 10] - */ - function parseInt(string, radix, guard) { - if (guard || radix == null) { - radix = 0; - } else if (radix) { - radix = +radix; - } - return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); - } - - /** - * Repeats the given string `n` times. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to repeat. - * @param {number} [n=1] The number of times to repeat the string. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the repeated string. - * @example - * - * _.repeat('*', 3); - * // => '***' - * - * _.repeat('abc', 2); - * // => 'abcabc' - * - * _.repeat('abc', 0); - * // => '' - */ - function repeat(string, n, guard) { - if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { - n = 1; - } else { - n = toInteger(n); - } - return baseRepeat(toString(string), n); - } - - /** - * Replaces matches for `pattern` in `string` with `replacement`. - * - * **Note:** This method is based on - * [`String#replace`](https://mdn.io/String/replace). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to modify. - * @param {RegExp|string} pattern The pattern to replace. - * @param {Function|string} replacement The match replacement. - * @returns {string} Returns the modified string. - * @example - * - * _.replace('Hi Fred', 'Fred', 'Barney'); - * // => 'Hi Barney' - */ - function replace() { - var args = arguments, - string = toString(args[0]); - - return args.length < 3 ? string : string.replace(args[1], args[2]); - } - - /** - * Converts `string` to - * [snake case](https://en.wikipedia.org/wiki/Snake_case). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the snake cased string. - * @example - * - * _.snakeCase('Foo Bar'); - * // => 'foo_bar' - * - * _.snakeCase('fooBar'); - * // => 'foo_bar' - * - * _.snakeCase('--FOO-BAR--'); - * // => 'foo_bar' - */ - var snakeCase = createCompounder(function(result, word, index) { - return result + (index ? '_' : '') + word.toLowerCase(); - }); - - /** - * Splits `string` by `separator`. - * - * **Note:** This method is based on - * [`String#split`](https://mdn.io/String/split). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to split. - * @param {RegExp|string} separator The separator pattern to split by. - * @param {number} [limit] The length to truncate results to. - * @returns {Array} Returns the string segments. - * @example - * - * _.split('a-b-c', '-', 2); - * // => ['a', 'b'] - */ - function split(string, separator, limit) { - if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { - separator = limit = undefined; - } - limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; - if (!limit) { - return []; - } - string = toString(string); - if (string && ( - typeof separator == 'string' || - (separator != null && !isRegExp(separator)) - )) { - separator = baseToString(separator); - if (!separator && hasUnicode(string)) { - return castSlice(stringToArray(string), 0, limit); - } - } - return string.split(separator, limit); - } - - /** - * Converts `string` to - * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). - * - * @static - * @memberOf _ - * @since 3.1.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the start cased string. - * @example - * - * _.startCase('--foo-bar--'); - * // => 'Foo Bar' - * - * _.startCase('fooBar'); - * // => 'Foo Bar' - * - * _.startCase('__FOO_BAR__'); - * // => 'FOO BAR' - */ - var startCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + upperFirst(word); - }); - - /** - * Checks if `string` starts with the given target string. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to inspect. - * @param {string} [target] The string to search for. - * @param {number} [position=0] The position to search from. - * @returns {boolean} Returns `true` if `string` starts with `target`, - * else `false`. - * @example - * - * _.startsWith('abc', 'a'); - * // => true - * - * _.startsWith('abc', 'b'); - * // => false - * - * _.startsWith('abc', 'b', 1); - * // => true - */ - function startsWith(string, target, position) { - string = toString(string); - position = position == null - ? 0 - : baseClamp(toInteger(position), 0, string.length); - - target = baseToString(target); - return string.slice(position, position + target.length) == target; - } - - /** - * Creates a compiled template function that can interpolate data properties - * in "interpolate" delimiters, HTML-escape interpolated data properties in - * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data - * properties may be accessed as free variables in the template. If a setting - * object is given, it takes precedence over `_.templateSettings` values. - * - * **Note:** In the development build `_.template` utilizes - * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) - * for easier debugging. - * - * For more information on precompiling templates see - * [lodash's custom builds documentation](https://lodash.com/custom-builds). - * - * For more information on Chrome extension sandboxes see - * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category String - * @param {string} [string=''] The template string. - * @param {Object} [options={}] The options object. - * @param {RegExp} [options.escape=_.templateSettings.escape] - * The HTML "escape" delimiter. - * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] - * The "evaluate" delimiter. - * @param {Object} [options.imports=_.templateSettings.imports] - * An object to import into the template as free variables. - * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] - * The "interpolate" delimiter. - * @param {string} [options.sourceURL='lodash.templateSources[n]'] - * The sourceURL of the compiled template. - * @param {string} [options.variable='obj'] - * The data object variable name. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the compiled template function. - * @example - * - * // Use the "interpolate" delimiter to create a compiled template. - * var compiled = _.template('hello <%= user %>!'); - * compiled({ 'user': 'fred' }); - * // => 'hello fred!' - * - * // Use the HTML "escape" delimiter to escape data property values. - * var compiled = _.template('<%- value %>'); - * compiled({ 'value': ' -``` - -## UMD - -`browser-request` is [UMD](https://github.com/umdjs/umd) wrapped, allowing you to serve it directly to the browser from wherever you store the module. - -```html - -``` - -You may also use an [AMD loader](http://requirejs.org/docs/whyamd.html) by referencing the same file in your loader [config](http://requirejs.org/docs/api.html#config). - -## License - -Browser Request is licensed under the Apache 2.0 license. - diff --git a/node_modules/browser-request/index.js b/node_modules/browser-request/index.js deleted file mode 100755 index 51ac8b4c7..000000000 --- a/node_modules/browser-request/index.js +++ /dev/null @@ -1,494 +0,0 @@ -// Browser Request -// -// 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. - -// UMD HEADER START -(function (root, factory) { - if (typeof define === 'function' && define.amd) { - // AMD. Register as an anonymous module. - define([], factory); - } else if (typeof exports === 'object') { - // Node. Does not work with strict CommonJS, but - // only CommonJS-like enviroments that support module.exports, - // like Node. - module.exports = factory(); - } else { - // Browser globals (root is window) - root.returnExports = factory(); - } -}(this, function () { -// UMD HEADER END - -var XHR = XMLHttpRequest -if (!XHR) throw new Error('missing XMLHttpRequest') -request.log = { - 'trace': noop, 'debug': noop, 'info': noop, 'warn': noop, 'error': noop -} - -var DEFAULT_TIMEOUT = 3 * 60 * 1000 // 3 minutes - -// -// request -// - -function request(options, callback) { - // The entry-point to the API: prep the options object and pass the real work to run_xhr. - if(typeof callback !== 'function') - throw new Error('Bad callback given: ' + callback) - - if(!options) - throw new Error('No options given') - - var options_onResponse = options.onResponse; // Save this for later. - - if(typeof options === 'string') - options = {'uri':options}; - else - options = JSON.parse(JSON.stringify(options)); // Use a duplicate for mutating. - - options.onResponse = options_onResponse // And put it back. - - if (options.verbose) request.log = getLogger(); - - if(options.url) { - options.uri = options.url; - delete options.url; - } - - if(!options.uri && options.uri !== "") - throw new Error("options.uri is a required argument"); - - if(typeof options.uri != "string") - throw new Error("options.uri must be a string"); - - var unsupported_options = ['proxy', '_redirectsFollowed', 'maxRedirects', 'followRedirect'] - for (var i = 0; i < unsupported_options.length; i++) - if(options[ unsupported_options[i] ]) - throw new Error("options." + unsupported_options[i] + " is not supported") - - options.callback = callback - options.method = options.method || 'GET'; - options.headers = options.headers || {}; - options.body = options.body || null - options.timeout = options.timeout || request.DEFAULT_TIMEOUT - - if(options.headers.host) - throw new Error("Options.headers.host is not supported"); - - if(options.json) { - options.headers.accept = options.headers.accept || 'application/json' - if(options.method !== 'GET') - options.headers['content-type'] = 'application/json' - - if(typeof options.json !== 'boolean') - options.body = JSON.stringify(options.json) - else if(typeof options.body !== 'string') - options.body = JSON.stringify(options.body) - } - - //BEGIN QS Hack - var serialize = function(obj) { - var str = []; - for(var p in obj) - if (obj.hasOwnProperty(p)) { - str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); - } - return str.join("&"); - } - - if(options.qs){ - var qs = (typeof options.qs == 'string')? options.qs : serialize(options.qs); - if(options.uri.indexOf('?') !== -1){ //no get params - options.uri = options.uri+'&'+qs; - }else{ //existing get params - options.uri = options.uri+'?'+qs; - } - } - //END QS Hack - - //BEGIN FORM Hack - var multipart = function(obj) { - //todo: support file type (useful?) - var result = {}; - result.boundry = '-------------------------------'+Math.floor(Math.random()*1000000000); - var lines = []; - for(var p in obj){ - if (obj.hasOwnProperty(p)) { - lines.push( - '--'+result.boundry+"\n"+ - 'Content-Disposition: form-data; name="'+p+'"'+"\n"+ - "\n"+ - obj[p]+"\n" - ); - } - } - lines.push( '--'+result.boundry+'--' ); - result.body = lines.join(''); - result.length = result.body.length; - result.type = 'multipart/form-data; boundary='+result.boundry; - return result; - } - - if(options.form){ - if(typeof options.form == 'string') throw('form name unsupported'); - if(options.method === 'POST'){ - var encoding = (options.encoding || 'application/x-www-form-urlencoded').toLowerCase(); - options.headers['content-type'] = encoding; - switch(encoding){ - case 'application/x-www-form-urlencoded': - options.body = serialize(options.form).replace(/%20/g, "+"); - break; - case 'multipart/form-data': - var multi = multipart(options.form); - //options.headers['content-length'] = multi.length; - options.body = multi.body; - options.headers['content-type'] = multi.type; - break; - default : throw new Error('unsupported encoding:'+encoding); - } - } - } - //END FORM Hack - - // If onResponse is boolean true, call back immediately when the response is known, - // not when the full request is complete. - options.onResponse = options.onResponse || noop - if(options.onResponse === true) { - options.onResponse = callback - options.callback = noop - } - - // XXX Browsers do not like this. - //if(options.body) - // options.headers['content-length'] = options.body.length; - - // HTTP basic authentication - if(!options.headers.authorization && options.auth) - options.headers.authorization = 'Basic ' + b64_enc(options.auth.username + ':' + options.auth.password); - - return run_xhr(options) -} - -var req_seq = 0 -function run_xhr(options) { - var xhr = new XHR - , timed_out = false - , is_cors = is_crossDomain(options.uri) - , supports_cors = ('withCredentials' in xhr) - - req_seq += 1 - xhr.seq_id = req_seq - xhr.id = req_seq + ': ' + options.method + ' ' + options.uri - xhr._id = xhr.id // I know I will type "_id" from habit all the time. - - if(is_cors && !supports_cors) { - var cors_err = new Error('Browser does not support cross-origin request: ' + options.uri) - cors_err.cors = 'unsupported' - return options.callback(cors_err, xhr) - } - - xhr.timeoutTimer = setTimeout(too_late, options.timeout) - function too_late() { - timed_out = true - var er = new Error('ETIMEDOUT') - er.code = 'ETIMEDOUT' - er.duration = options.timeout - - request.log.error('Timeout', { 'id':xhr._id, 'milliseconds':options.timeout }) - return options.callback(er, xhr) - } - - // Some states can be skipped over, so remember what is still incomplete. - var did = {'response':false, 'loading':false, 'end':false} - - xhr.onreadystatechange = on_state_change - xhr.open(options.method, options.uri, true) // asynchronous - if(is_cors) - xhr.withCredentials = !! options.withCredentials - xhr.send(options.body) - return xhr - - function on_state_change(event) { - if(timed_out) - return request.log.debug('Ignoring timed out state change', {'state':xhr.readyState, 'id':xhr.id}) - - request.log.debug('State change', {'state':xhr.readyState, 'id':xhr.id, 'timed_out':timed_out}) - - if(xhr.readyState === XHR.OPENED) { - request.log.debug('Request started', {'id':xhr.id}) - for (var key in options.headers) - xhr.setRequestHeader(key, options.headers[key]) - } - - else if(xhr.readyState === XHR.HEADERS_RECEIVED) - on_response() - - else if(xhr.readyState === XHR.LOADING) { - on_response() - on_loading() - } - - else if(xhr.readyState === XHR.DONE) { - on_response() - on_loading() - on_end() - } - } - - function on_response() { - if(did.response) - return - - did.response = true - request.log.debug('Got response', {'id':xhr.id, 'status':xhr.status}) - clearTimeout(xhr.timeoutTimer) - xhr.statusCode = xhr.status // Node request compatibility - - // Detect failed CORS requests. - if(is_cors && xhr.statusCode == 0) { - var cors_err = new Error('CORS request rejected: ' + options.uri) - cors_err.cors = 'rejected' - - // Do not process this request further. - did.loading = true - did.end = true - - return options.callback(cors_err, xhr) - } - - options.onResponse(null, xhr) - } - - function on_loading() { - if(did.loading) - return - - did.loading = true - request.log.debug('Response body loading', {'id':xhr.id}) - // TODO: Maybe simulate "data" events by watching xhr.responseText - } - - function on_end() { - if(did.end) - return - - did.end = true - request.log.debug('Request done', {'id':xhr.id}) - - xhr.body = xhr.responseText - if(options.json) { - try { xhr.body = JSON.parse(xhr.responseText) } - catch (er) { return options.callback(er, xhr) } - } - - options.callback(null, xhr, xhr.body) - } - -} // request - -request.withCredentials = false; -request.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT; - -// -// defaults -// - -request.defaults = function(options, requester) { - var def = function (method) { - var d = function (params, callback) { - if(typeof params === 'string') - params = {'uri': params}; - else { - params = JSON.parse(JSON.stringify(params)); - } - for (var i in options) { - if (params[i] === undefined) params[i] = options[i] - } - return method(params, callback) - } - return d - } - var de = def(request) - de.get = def(request.get) - de.post = def(request.post) - de.put = def(request.put) - de.head = def(request.head) - return de -} - -// -// HTTP method shortcuts -// - -var shortcuts = [ 'get', 'put', 'post', 'head' ]; -shortcuts.forEach(function(shortcut) { - var method = shortcut.toUpperCase(); - var func = shortcut.toLowerCase(); - - request[func] = function(opts) { - if(typeof opts === 'string') - opts = {'method':method, 'uri':opts}; - else { - opts = JSON.parse(JSON.stringify(opts)); - opts.method = method; - } - - var args = [opts].concat(Array.prototype.slice.apply(arguments, [1])); - return request.apply(this, args); - } -}) - -// -// CouchDB shortcut -// - -request.couch = function(options, callback) { - if(typeof options === 'string') - options = {'uri':options} - - // Just use the request API to do JSON. - options.json = true - if(options.body) - options.json = options.body - delete options.body - - callback = callback || noop - - var xhr = request(options, couch_handler) - return xhr - - function couch_handler(er, resp, body) { - if(er) - return callback(er, resp, body) - - if((resp.statusCode < 200 || resp.statusCode > 299) && body.error) { - // The body is a Couch JSON object indicating the error. - er = new Error('CouchDB error: ' + (body.error.reason || body.error.error)) - for (var key in body) - er[key] = body[key] - return callback(er, resp, body); - } - - return callback(er, resp, body); - } -} - -// -// Utility -// - -function noop() {} - -function getLogger() { - var logger = {} - , levels = ['trace', 'debug', 'info', 'warn', 'error'] - , level, i - - for(i = 0; i < levels.length; i++) { - level = levels[i] - - logger[level] = noop - if(typeof console !== 'undefined' && console && console[level]) - logger[level] = formatted(console, level) - } - - return logger -} - -function formatted(obj, method) { - return formatted_logger - - function formatted_logger(str, context) { - if(typeof context === 'object') - str += ' ' + JSON.stringify(context) - - return obj[method].call(obj, str) - } -} - -// Return whether a URL is a cross-domain request. -function is_crossDomain(url) { - var rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/ - - // jQuery #8138, IE may throw an exception when accessing - // a field from window.location if document.domain has been set - var ajaxLocation - try { ajaxLocation = location.href } - catch (e) { - // Use the href attribute of an A element since IE will modify it given document.location - ajaxLocation = document.createElement( "a" ); - ajaxLocation.href = ""; - ajaxLocation = ajaxLocation.href; - } - - var ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || [] - , parts = rurl.exec(url.toLowerCase() ) - - var result = !!( - parts && - ( parts[1] != ajaxLocParts[1] - || parts[2] != ajaxLocParts[2] - || (parts[3] || (parts[1] === "http:" ? 80 : 443)) != (ajaxLocParts[3] || (ajaxLocParts[1] === "http:" ? 80 : 443)) - ) - ) - - //console.debug('is_crossDomain('+url+') -> ' + result) - return result -} - -// MIT License from http://phpjs.org/functions/base64_encode:358 -function b64_enc (data) { - // Encodes string using MIME base64 algorithm - var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; - var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = []; - - if (!data) { - return data; - } - - // assume utf8 data - // data = this.utf8_encode(data+''); - - do { // pack three octets into four hexets - o1 = data.charCodeAt(i++); - o2 = data.charCodeAt(i++); - o3 = data.charCodeAt(i++); - - bits = o1<<16 | o2<<8 | o3; - - h1 = bits>>18 & 0x3f; - h2 = bits>>12 & 0x3f; - h3 = bits>>6 & 0x3f; - h4 = bits & 0x3f; - - // use hexets to index into b64, and append result to encoded string - tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); - } while (i < data.length); - - enc = tmp_arr.join(''); - - switch (data.length % 3) { - case 1: - enc = enc.slice(0, -2) + '=='; - break; - case 2: - enc = enc.slice(0, -1) + '='; - break; - } - - return enc; -} - return request; -//UMD FOOTER START -})); -//UMD FOOTER END diff --git a/node_modules/browser-request/package.json b/node_modules/browser-request/package.json deleted file mode 100644 index 0ae2f7f63..000000000 --- a/node_modules/browser-request/package.json +++ /dev/null @@ -1,91 +0,0 @@ -{ - "_from": "browser-request@^0.3.2", - "_id": "browser-request@0.3.3", - "_inBundle": false, - "_integrity": "sha1-ns5bWsqJopkyJC4Yv5M975h2zBc=", - "_location": "/browser-request", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "browser-request@^0.3.2", - "name": "browser-request", - "escapedName": "browser-request", - "rawSpec": "^0.3.2", - "saveSpec": null, - "fetchSpec": "^0.3.2" - }, - "_requiredBy": [ - "/asana" - ], - "_resolved": "https://registry.npmjs.org/browser-request/-/browser-request-0.3.3.tgz", - "_shasum": "9ece5b5aca89a29932242e18bf933def9876cc17", - "_spec": "browser-request@^0.3.2", - "_where": "/Users/christopher/Projects/github-actions-asana/node_modules/asana", - "author": { - "name": "Jason Smith", - "email": "jhs@iriscouch.com" - }, - "bugs": { - "url": "https://github.com/iriscouch/browser-request/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Jason Smith Work", - "email": "jhs@iriscouch.com" - }, - { - "name": "Jason Smith", - "email": "jason.h.smith@gmail.com" - }, - { - "name": "maxogden", - "email": "max@maxogden.com" - }, - { - "name": "Abbey Sparrow via Google", - "email": "abbeys@google.com" - } - ], - "deprecated": false, - "description": "Browser port of the Node.js 'request' package", - "devDependencies": { - "beefy": "~0.4.0", - "browserify": "~2.25.0", - "tape": "~1.0.4" - }, - "engines": [ - "node" - ], - "homepage": "http://github.com/iriscouch/browser-request", - "keywords": [ - "request", - "http", - "browser", - "browserify" - ], - "name": "browser-request", - "repository": { - "type": "git", - "url": "git://github.com/iriscouch/browser-request.git" - }, - "scripts": { - "test": "beefy test.js" - }, - "testling": { - "files": "test.js", - "browsers": [ - "ie/6..latest", - "firefox/3..5", - "firefox/19..nightly", - "chrome/4..7", - "chrome/24..canary", - "opera/10..next", - "safari/4..latest", - "iphone/6", - "ipad/6" - ] - }, - "version": "0.3.3" -} diff --git a/node_modules/browser-request/test.js b/node_modules/browser-request/test.js deleted file mode 100644 index f427f233e..000000000 --- a/node_modules/browser-request/test.js +++ /dev/null @@ -1,20 +0,0 @@ -var test = require('tape') - -var request = require('./') - -test('try a CORS GET', function (t) { - var url = 'https://www.googleapis.com/plus/v1/activities' - request(url, function(err, resp, body) { - t.equal(resp.statusCode, 400) - t.equal(!!resp.body.match(/Required parameter/), true) - t.end() - }) -}) - -test('json true', function (t) { - var url = 'https://www.googleapis.com/plus/v1/activities' - request({url: url, json: true}, function(err, resp, body) { - t.equal(body.error.code, 400) - t.end() - }) -}) diff --git a/node_modules/call-bind/.eslintignore b/node_modules/call-bind/.eslintignore new file mode 100644 index 000000000..404abb221 --- /dev/null +++ b/node_modules/call-bind/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/node_modules/call-bind/.eslintrc b/node_modules/call-bind/.eslintrc new file mode 100644 index 000000000..dfa9a6cdc --- /dev/null +++ b/node_modules/call-bind/.eslintrc @@ -0,0 +1,16 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "id-length": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + "no-magic-numbers": 0, + }, +} diff --git a/node_modules/call-bind/.github/FUNDING.yml b/node_modules/call-bind/.github/FUNDING.yml new file mode 100644 index 000000000..c70c2ecdb --- /dev/null +++ b/node_modules/call-bind/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/call-bind +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/call-bind/.nycrc b/node_modules/call-bind/.nycrc new file mode 100644 index 000000000..bdd626ce9 --- /dev/null +++ b/node_modules/call-bind/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/call-bind/CHANGELOG.md b/node_modules/call-bind/CHANGELOG.md new file mode 100644 index 000000000..c653f701a --- /dev/null +++ b/node_modules/call-bind/CHANGELOG.md @@ -0,0 +1,93 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.7](https://github.com/ljharb/call-bind/compare/v1.0.6...v1.0.7) - 2024-02-12 + +### Commits + +- [Refactor] use `es-define-property` [`09b76a0`](https://github.com/ljharb/call-bind/commit/09b76a01634440461d44a80c9924ec4b500f3b03) +- [Deps] update `get-intrinsic`, `set-function-length` [`ad5136d`](https://github.com/ljharb/call-bind/commit/ad5136ddda2a45c590959829ad3dce0c9f4e3590) + +## [v1.0.6](https://github.com/ljharb/call-bind/compare/v1.0.5...v1.0.6) - 2024-02-05 + +### Commits + +- [Dev Deps] update `aud`, `npmignore`, `tape` [`d564d5c`](https://github.com/ljharb/call-bind/commit/d564d5ce3e06a19df4d499c77f8d1a9da44e77aa) +- [Deps] update `get-intrinsic`, `set-function-length` [`cfc2bdc`](https://github.com/ljharb/call-bind/commit/cfc2bdca7b633df0e0e689e6b637f668f1c6792e) +- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`64cd289`](https://github.com/ljharb/call-bind/commit/64cd289ae5862c250a4ca80aa8d461047c166af5) +- [meta] add missing `engines.node` [`32a4038`](https://github.com/ljharb/call-bind/commit/32a4038857b62179f7f9b7b3df2c5260036be582) + +## [v1.0.5](https://github.com/ljharb/call-bind/compare/v1.0.4...v1.0.5) - 2023-10-19 + +### Commits + +- [Fix] throw an error on non-functions as early as possible [`f262408`](https://github.com/ljharb/call-bind/commit/f262408f822c840fbc268080f3ad7c429611066d) +- [Deps] update `set-function-length` [`3fff271`](https://github.com/ljharb/call-bind/commit/3fff27145a1e3a76a5b74f1d7c3c43d0fa3b9871) + +## [v1.0.4](https://github.com/ljharb/call-bind/compare/v1.0.3...v1.0.4) - 2023-10-19 + +## [v1.0.3](https://github.com/ljharb/call-bind/compare/v1.0.2...v1.0.3) - 2023-10-19 + +### Commits + +- [actions] reuse common workflows [`a994df6`](https://github.com/ljharb/call-bind/commit/a994df69f401f4bf735a4ccd77029b85d1549453) +- [meta] use `npmignore` to autogenerate an npmignore file [`eef3ef2`](https://github.com/ljharb/call-bind/commit/eef3ef21e1f002790837fedb8af2679c761fbdf5) +- [readme] flesh out content [`1845ccf`](https://github.com/ljharb/call-bind/commit/1845ccfd9976a607884cfc7157c93192cc16cf22) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`5b47d53`](https://github.com/ljharb/call-bind/commit/5b47d53d2fd74af5ea0a44f1d51e503cd42f7a90) +- [Refactor] use `set-function-length` [`a0e165c`](https://github.com/ljharb/call-bind/commit/a0e165c5dc61db781cbc919b586b1c2b8da0b150) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`9c50103`](https://github.com/ljharb/call-bind/commit/9c50103f44137279a817317cf6cc421a658f85b4) +- [meta] simplify "exports" [`019c6d0`](https://github.com/ljharb/call-bind/commit/019c6d06b0e1246ceed8e579f57e44441cbbf6d9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `safe-publish-latest`, `tape` [`23bd718`](https://github.com/ljharb/call-bind/commit/23bd718a288d3b03042062b4ef5153b3cea83f11) +- [actions] update codecov uploader [`62552d7`](https://github.com/ljharb/call-bind/commit/62552d79cc79e05825e99aaba134ae5b37f33da5) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`ec81665`](https://github.com/ljharb/call-bind/commit/ec81665b300f87eabff597afdc8b8092adfa7afd) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`35d67fc`](https://github.com/ljharb/call-bind/commit/35d67fcea883e686650f736f61da5ddca2592de8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`0266d8d`](https://github.com/ljharb/call-bind/commit/0266d8d2a45086a922db366d0c2932fa463662ff) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`43a5b28`](https://github.com/ljharb/call-bind/commit/43a5b28a444e710e1bbf92adb8afb5cf7523a223) +- [Deps] update `define-data-property`, `function-bind`, `get-intrinsic` [`780eb36`](https://github.com/ljharb/call-bind/commit/780eb36552514f8cc99c70821ce698697c2726a5) +- [Dev Deps] update `aud`, `tape` [`90d50ad`](https://github.com/ljharb/call-bind/commit/90d50ad03b061e0268b3380b0065fcaec183dc05) +- [meta] use `prepublishOnly` script for npm 7+ [`44c5433`](https://github.com/ljharb/call-bind/commit/44c5433b7980e02b4870007046407cf6fc543329) +- [Deps] update `get-intrinsic` [`86bfbfc`](https://github.com/ljharb/call-bind/commit/86bfbfcf34afdc6eabc93ce3d408548d0e27d958) +- [Deps] update `get-intrinsic` [`5c53354`](https://github.com/ljharb/call-bind/commit/5c5335489be0294c18cd7a8bb6e08226ee019ff5) +- [actions] update checkout action [`4c393a8`](https://github.com/ljharb/call-bind/commit/4c393a8173b3c8e5b30d5b3297b3b94d48bf87f3) +- [Deps] update `get-intrinsic` [`4e70bde`](https://github.com/ljharb/call-bind/commit/4e70bdec0626acb11616d66250fc14565e716e91) +- [Deps] update `get-intrinsic` [`55ae803`](https://github.com/ljharb/call-bind/commit/55ae803a920bd93c369cd798c20de31f91e9fc60) + +## [v1.0.2](https://github.com/ljharb/call-bind/compare/v1.0.1...v1.0.2) - 2021-01-11 + +### Commits + +- [Fix] properly include the receiver in the bound length [`dbae7bc`](https://github.com/ljharb/call-bind/commit/dbae7bc676c079a0d33c0a43e9ef92cb7b01345d) + +## [v1.0.1](https://github.com/ljharb/call-bind/compare/v1.0.0...v1.0.1) - 2021-01-08 + +### Commits + +- [Tests] migrate tests to Github Actions [`b6db284`](https://github.com/ljharb/call-bind/commit/b6db284c36f8ccd195b88a6764fe84b7223a0da1) +- [meta] do not publish github action workflow files [`ec7fe46`](https://github.com/ljharb/call-bind/commit/ec7fe46e60cfa4764ee943d2755f5e5a366e578e) +- [Fix] preserve original function’s length when possible [`adbceaa`](https://github.com/ljharb/call-bind/commit/adbceaa3cac4b41ea78bb19d7ccdbaaf7e0bdadb) +- [Tests] gather coverage data on every job [`d69e23c`](https://github.com/ljharb/call-bind/commit/d69e23cc65f101ba1d4c19bb07fa8eb0ec624be8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`2fd3586`](https://github.com/ljharb/call-bind/commit/2fd3586c5d47b335364c14293114c6b625ae1f71) +- [Deps] update `get-intrinsic` [`f23e931`](https://github.com/ljharb/call-bind/commit/f23e9318cc271c2add8bb38cfded85ee7baf8eee) +- [Deps] update `get-intrinsic` [`72d9f44`](https://github.com/ljharb/call-bind/commit/72d9f44e184465ba8dd3fb48260bbcff234985f2) +- [meta] fix FUNDING.yml [`e723573`](https://github.com/ljharb/call-bind/commit/e723573438c5a68dcec31fb5d96ea6b7e4a93be8) +- [eslint] ignore coverage output [`15e76d2`](https://github.com/ljharb/call-bind/commit/15e76d28a5f43e504696401e5b31ebb78ee1b532) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`8fa4dab`](https://github.com/ljharb/call-bind/commit/8fa4dabb23ba3dd7bb92c9571c1241c08b56e4b6) + +## v1.0.0 - 2020-10-30 + +### Commits + +- Initial commit [`306cf98`](https://github.com/ljharb/call-bind/commit/306cf98c7ec9e7ef66b653ec152277ac1381eb50) +- Tests [`e10d0bb`](https://github.com/ljharb/call-bind/commit/e10d0bbdadc7a10ecedc9a1c035112d3e368b8df) +- Implementation [`43852ed`](https://github.com/ljharb/call-bind/commit/43852eda0f187327b7fad2423ca972149a52bd65) +- npm init [`408f860`](https://github.com/ljharb/call-bind/commit/408f860b773a2f610805fd3613d0d71bac1b6249) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`fb349b2`](https://github.com/ljharb/call-bind/commit/fb349b2e48defbec8b5ec8a8395cc8f69f220b13) +- [meta] add `auto-changelog` [`c4001fc`](https://github.com/ljharb/call-bind/commit/c4001fc43031799ef908211c98d3b0fb2b60fde4) +- [meta] add "funding"; create `FUNDING.yml` [`d4d6d29`](https://github.com/ljharb/call-bind/commit/d4d6d2974a14bc2e98830468eda7fe6d6a776717) +- [Tests] add `npm run lint` [`dedfb98`](https://github.com/ljharb/call-bind/commit/dedfb98bd0ecefb08ddb9a94061bd10cde4332af) +- Only apps should have lockfiles [`54ac776`](https://github.com/ljharb/call-bind/commit/54ac77653db45a7361dc153d2f478e743f110650) +- [meta] add `safe-publish-latest` [`9ea8e43`](https://github.com/ljharb/call-bind/commit/9ea8e435b950ce9b705559cd651039f9bf40140f) diff --git a/node_modules/call-bind/LICENSE b/node_modules/call-bind/LICENSE new file mode 100644 index 000000000..48f05d01d --- /dev/null +++ b/node_modules/call-bind/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/call-bind/README.md b/node_modules/call-bind/README.md new file mode 100644 index 000000000..48e9047f0 --- /dev/null +++ b/node_modules/call-bind/README.md @@ -0,0 +1,64 @@ +# call-bind [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Robustly `.call.bind()` a function. + +## Getting started + +```sh +npm install --save call-bind +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const callBind = require('call-bind'); +const callBound = require('call-bind/callBound'); + +function f(a, b) { + assert.equal(this, 1); + assert.equal(a, 2); + assert.equal(b, 3); + assert.equal(arguments.length, 2); +} + +const fBound = callBind(f); + +const slice = callBound('Array.prototype.slice'); + +delete Function.prototype.call; +delete Function.prototype.bind; + +fBound(1, 2, 3); + +assert.deepEqual(slice([1, 2, 3, 4], 1, -1), [2, 3]); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/call-bind +[npm-version-svg]: https://versionbadg.es/ljharb/call-bind.svg +[deps-svg]: https://david-dm.org/ljharb/call-bind.svg +[deps-url]: https://david-dm.org/ljharb/call-bind +[dev-deps-svg]: https://david-dm.org/ljharb/call-bind/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/call-bind#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/call-bind.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/call-bind.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/call-bind.svg +[downloads-url]: https://npm-stat.com/charts.html?package=call-bind +[codecov-image]: https://codecov.io/gh/ljharb/call-bind/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/call-bind/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/call-bind +[actions-url]: https://github.com/ljharb/call-bind/actions diff --git a/node_modules/call-bind/callBound.js b/node_modules/call-bind/callBound.js new file mode 100644 index 000000000..8374adfd0 --- /dev/null +++ b/node_modules/call-bind/callBound.js @@ -0,0 +1,15 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var callBind = require('./'); + +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); + +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBind(intrinsic); + } + return intrinsic; +}; diff --git a/node_modules/call-bind/index.js b/node_modules/call-bind/index.js new file mode 100644 index 000000000..01c5b3d4e --- /dev/null +++ b/node_modules/call-bind/index.js @@ -0,0 +1,35 @@ +'use strict'; + +var bind = require('function-bind'); +var GetIntrinsic = require('get-intrinsic'); +var setFunctionLength = require('set-function-length'); + +var $TypeError = require('es-errors/type'); +var $apply = GetIntrinsic('%Function.prototype.apply%'); +var $call = GetIntrinsic('%Function.prototype.call%'); +var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); + +var $defineProperty = require('es-define-property'); +var $max = GetIntrinsic('%Math.max%'); + +module.exports = function callBind(originalFunction) { + if (typeof originalFunction !== 'function') { + throw new $TypeError('a function is required'); + } + var func = $reflectApply(bind, $call, arguments); + return setFunctionLength( + func, + 1 + $max(0, originalFunction.length - (arguments.length - 1)), + true + ); +}; + +var applyBind = function applyBind() { + return $reflectApply(bind, $apply, arguments); +}; + +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); +} else { + module.exports.apply = applyBind; +} diff --git a/node_modules/call-bind/package.json b/node_modules/call-bind/package.json new file mode 100644 index 000000000..5ba88ff85 --- /dev/null +++ b/node_modules/call-bind/package.json @@ -0,0 +1,95 @@ +{ + "name": "call-bind", + "version": "1.0.7", + "description": "Robustly `.call.bind()` a function", + "main": "index.js", + "exports": { + ".": "./index.js", + "./callBound": "./callBound.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=auto", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "lint": "eslint --ext=.js,.mjs .", + "postlint": "evalmd README.md", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/call-bind.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "es", + "js", + "callbind", + "callbound", + "call", + "bind", + "bound", + "call-bind", + "call-bound", + "function", + "es-abstract" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/call-bind/issues" + }, + "homepage": "https://github.com/ljharb/call-bind#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-strict-mode": "^1.0.1", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.4" + }, + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/call-bind/test/callBound.js b/node_modules/call-bind/test/callBound.js new file mode 100644 index 000000000..c32319d70 --- /dev/null +++ b/node_modules/call-bind/test/callBound.js @@ -0,0 +1,54 @@ +'use strict'; + +var test = require('tape'); + +var callBound = require('../callBound'); + +test('callBound', function (t) { + // static primitive + t.equal(callBound('Array.length'), Array.length, 'Array.length yields itself'); + t.equal(callBound('%Array.length%'), Array.length, '%Array.length% yields itself'); + + // static non-function object + t.equal(callBound('Array.prototype'), Array.prototype, 'Array.prototype yields itself'); + t.equal(callBound('%Array.prototype%'), Array.prototype, '%Array.prototype% yields itself'); + t.equal(callBound('Array.constructor'), Array.constructor, 'Array.constructor yields itself'); + t.equal(callBound('%Array.constructor%'), Array.constructor, '%Array.constructor% yields itself'); + + // static function + t.equal(callBound('Date.parse'), Date.parse, 'Date.parse yields itself'); + t.equal(callBound('%Date.parse%'), Date.parse, '%Date.parse% yields itself'); + + // prototype primitive + t.equal(callBound('Error.prototype.message'), Error.prototype.message, 'Error.prototype.message yields itself'); + t.equal(callBound('%Error.prototype.message%'), Error.prototype.message, '%Error.prototype.message% yields itself'); + + // prototype function + t.notEqual(callBound('Object.prototype.toString'), Object.prototype.toString, 'Object.prototype.toString does not yield itself'); + t.notEqual(callBound('%Object.prototype.toString%'), Object.prototype.toString, '%Object.prototype.toString% does not yield itself'); + t.equal(callBound('Object.prototype.toString')(true), Object.prototype.toString.call(true), 'call-bound Object.prototype.toString calls into the original'); + t.equal(callBound('%Object.prototype.toString%')(true), Object.prototype.toString.call(true), 'call-bound %Object.prototype.toString% calls into the original'); + + t['throws']( + function () { callBound('does not exist'); }, + SyntaxError, + 'nonexistent intrinsic throws' + ); + t['throws']( + function () { callBound('does not exist', true); }, + SyntaxError, + 'allowMissing arg still throws for unknown intrinsic' + ); + + t.test('real but absent intrinsic', { skip: typeof WeakRef !== 'undefined' }, function (st) { + st['throws']( + function () { callBound('WeakRef'); }, + TypeError, + 'real but absent intrinsic throws' + ); + st.equal(callBound('WeakRef', true), undefined, 'allowMissing arg avoids exception'); + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/call-bind/test/index.js b/node_modules/call-bind/test/index.js new file mode 100644 index 000000000..1fd46689e --- /dev/null +++ b/node_modules/call-bind/test/index.js @@ -0,0 +1,80 @@ +'use strict'; + +var callBind = require('../'); +var bind = require('function-bind'); +var gOPD = require('gopd'); +var hasStrictMode = require('has-strict-mode')(); +var forEach = require('for-each'); +var inspect = require('object-inspect'); +var v = require('es-value-fixtures'); + +var test = require('tape'); + +/* + * older engines have length nonconfigurable + * in io.js v3, it is configurable except on bound functions, hence the .bind() + */ +var functionsHaveConfigurableLengths = !!( + gOPD + && Object.getOwnPropertyDescriptor + && Object.getOwnPropertyDescriptor(bind.call(function () {}), 'length').configurable +); + +test('callBind', function (t) { + forEach(v.nonFunctions, function (nonFunction) { + t['throws']( + function () { callBind(nonFunction); }, + TypeError, + inspect(nonFunction) + ' is not a function' + ); + }); + + var sentinel = { sentinel: true }; + var func = function (a, b) { + // eslint-disable-next-line no-invalid-this + return [!hasStrictMode && this === global ? undefined : this, a, b]; + }; + t.equal(func.length, 2, 'original function length is 2'); + t.deepEqual(func(), [undefined, undefined, undefined], 'unbound func with too few args'); + t.deepEqual(func(1, 2), [undefined, 1, 2], 'unbound func with right args'); + t.deepEqual(func(1, 2, 3), [undefined, 1, 2], 'unbound func with too many args'); + + var bound = callBind(func); + t.equal(bound.length, func.length + 1, 'function length is preserved', { skip: !functionsHaveConfigurableLengths }); + t.deepEqual(bound(), [undefined, undefined, undefined], 'bound func with too few args'); + t.deepEqual(bound(1, 2), [hasStrictMode ? 1 : Object(1), 2, undefined], 'bound func with right args'); + t.deepEqual(bound(1, 2, 3), [hasStrictMode ? 1 : Object(1), 2, 3], 'bound func with too many args'); + + var boundR = callBind(func, sentinel); + t.equal(boundR.length, func.length, 'function length is preserved', { skip: !functionsHaveConfigurableLengths }); + t.deepEqual(boundR(), [sentinel, undefined, undefined], 'bound func with receiver, with too few args'); + t.deepEqual(boundR(1, 2), [sentinel, 1, 2], 'bound func with receiver, with right args'); + t.deepEqual(boundR(1, 2, 3), [sentinel, 1, 2], 'bound func with receiver, with too many args'); + + var boundArg = callBind(func, sentinel, 1); + t.equal(boundArg.length, func.length - 1, 'function length is preserved', { skip: !functionsHaveConfigurableLengths }); + t.deepEqual(boundArg(), [sentinel, 1, undefined], 'bound func with receiver and arg, with too few args'); + t.deepEqual(boundArg(2), [sentinel, 1, 2], 'bound func with receiver and arg, with right arg'); + t.deepEqual(boundArg(2, 3), [sentinel, 1, 2], 'bound func with receiver and arg, with too many args'); + + t.test('callBind.apply', function (st) { + var aBound = callBind.apply(func); + st.deepEqual(aBound(sentinel), [sentinel, undefined, undefined], 'apply-bound func with no args'); + st.deepEqual(aBound(sentinel, [1], 4), [sentinel, 1, undefined], 'apply-bound func with too few args'); + st.deepEqual(aBound(sentinel, [1, 2], 4), [sentinel, 1, 2], 'apply-bound func with right args'); + + var aBoundArg = callBind.apply(func); + st.deepEqual(aBoundArg(sentinel, [1, 2, 3], 4), [sentinel, 1, 2], 'apply-bound func with too many args'); + st.deepEqual(aBoundArg(sentinel, [1, 2], 4), [sentinel, 1, 2], 'apply-bound func with right args'); + st.deepEqual(aBoundArg(sentinel, [1], 4), [sentinel, 1, undefined], 'apply-bound func with too few args'); + + var aBoundR = callBind.apply(func, sentinel); + st.deepEqual(aBoundR([1, 2, 3], 4), [sentinel, 1, 2], 'apply-bound func with receiver and too many args'); + st.deepEqual(aBoundR([1, 2], 4), [sentinel, 1, 2], 'apply-bound func with receiver and right args'); + st.deepEqual(aBoundR([1], 4), [sentinel, 1, undefined], 'apply-bound func with receiver and too few args'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/chokidar/LICENSE b/node_modules/chokidar/LICENSE new file mode 100644 index 000000000..fa9162b51 --- /dev/null +++ b/node_modules/chokidar/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012-2019 Paul Miller (https://paulmillr.com), Elan Shanker + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/chokidar/README.md b/node_modules/chokidar/README.md new file mode 100644 index 000000000..8e25decb4 --- /dev/null +++ b/node_modules/chokidar/README.md @@ -0,0 +1,308 @@ +# Chokidar [![Weekly downloads](https://img.shields.io/npm/dw/chokidar.svg)](https://github.com/paulmillr/chokidar) [![Yearly downloads](https://img.shields.io/npm/dy/chokidar.svg)](https://github.com/paulmillr/chokidar) + +> Minimal and efficient cross-platform file watching library + +[![NPM](https://nodei.co/npm/chokidar.png)](https://www.npmjs.com/package/chokidar) + +## Why? + +Node.js `fs.watch`: + +* Doesn't report filenames on MacOS. +* Doesn't report events at all when using editors like Sublime on MacOS. +* Often reports events twice. +* Emits most changes as `rename`. +* Does not provide an easy way to recursively watch file trees. +* Does not support recursive watching on Linux. + +Node.js `fs.watchFile`: + +* Almost as bad at event handling. +* Also does not provide any recursive watching. +* Results in high CPU utilization. + +Chokidar resolves these problems. + +Initially made for **[Brunch](https://brunch.io/)** (an ultra-swift web app build tool), it is now used in +[Microsoft's Visual Studio Code](https://github.com/microsoft/vscode), +[gulp](https://github.com/gulpjs/gulp/), +[karma](https://karma-runner.github.io/), +[PM2](https://github.com/Unitech/PM2), +[browserify](http://browserify.org/), +[webpack](https://webpack.github.io/), +[BrowserSync](https://www.browsersync.io/), +and [many others](https://www.npmjs.com/browse/depended/chokidar). +It has proven itself in production environments. + +Version 3 is out! Check out our blog post about it: [Chokidar 3: How to save 32TB of traffic every week](https://paulmillr.com/posts/chokidar-3-save-32tb-of-traffic/) + +## How? + +Chokidar does still rely on the Node.js core `fs` module, but when using +`fs.watch` and `fs.watchFile` for watching, it normalizes the events it +receives, often checking for truth by getting file stats and/or dir contents. + +On MacOS, chokidar by default uses a native extension exposing the Darwin +`FSEvents` API. This provides very efficient recursive watching compared with +implementations like `kqueue` available on most \*nix platforms. Chokidar still +does have to do some work to normalize the events received that way as well. + +On most other platforms, the `fs.watch`-based implementation is the default, which +avoids polling and keeps CPU usage down. Be advised that chokidar will initiate +watchers recursively for everything within scope of the paths that have been +specified, so be judicious about not wasting system resources by watching much +more than needed. + +## Getting started + +Install with npm: + +```sh +npm install chokidar +``` + +Then `require` and use it in your code: + +```javascript +const chokidar = require('chokidar'); + +// One-liner for current directory +chokidar.watch('.').on('all', (event, path) => { + console.log(event, path); +}); +``` + +## API + +```javascript +// Example of a more typical implementation structure + +// Initialize watcher. +const watcher = chokidar.watch('file, dir, glob, or array', { + ignored: /(^|[\/\\])\../, // ignore dotfiles + persistent: true +}); + +// Something to use when events are received. +const log = console.log.bind(console); +// Add event listeners. +watcher + .on('add', path => log(`File ${path} has been added`)) + .on('change', path => log(`File ${path} has been changed`)) + .on('unlink', path => log(`File ${path} has been removed`)); + +// More possible events. +watcher + .on('addDir', path => log(`Directory ${path} has been added`)) + .on('unlinkDir', path => log(`Directory ${path} has been removed`)) + .on('error', error => log(`Watcher error: ${error}`)) + .on('ready', () => log('Initial scan complete. Ready for changes')) + .on('raw', (event, path, details) => { // internal + log('Raw event info:', event, path, details); + }); + +// 'add', 'addDir' and 'change' events also receive stat() results as second +// argument when available: https://nodejs.org/api/fs.html#fs_class_fs_stats +watcher.on('change', (path, stats) => { + if (stats) console.log(`File ${path} changed size to ${stats.size}`); +}); + +// Watch new files. +watcher.add('new-file'); +watcher.add(['new-file-2', 'new-file-3', '**/other-file*']); + +// Get list of actual paths being watched on the filesystem +var watchedPaths = watcher.getWatched(); + +// Un-watch some files. +await watcher.unwatch('new-file*'); + +// Stop watching. +// The method is async! +watcher.close().then(() => console.log('closed')); + +// Full list of options. See below for descriptions. +// Do not use this example! +chokidar.watch('file', { + persistent: true, + + ignored: '*.txt', + ignoreInitial: false, + followSymlinks: true, + cwd: '.', + disableGlobbing: false, + + usePolling: false, + interval: 100, + binaryInterval: 300, + alwaysStat: false, + depth: 99, + awaitWriteFinish: { + stabilityThreshold: 2000, + pollInterval: 100 + }, + + ignorePermissionErrors: false, + atomic: true // or a custom 'atomicity delay', in milliseconds (default 100) +}); + +``` + +`chokidar.watch(paths, [options])` + +* `paths` (string or array of strings). Paths to files, dirs to be watched +recursively, or glob patterns. + - Note: globs must not contain windows separators (`\`), + because that's how they work by the standard — + you'll need to replace them with forward slashes (`/`). + - Note 2: for additional glob documentation, check out low-level + library: [picomatch](https://github.com/micromatch/picomatch). +* `options` (object) Options object as defined below: + +#### Persistence + +* `persistent` (default: `true`). Indicates whether the process +should continue to run as long as files are being watched. If set to +`false` when using `fsevents` to watch, no more events will be emitted +after `ready`, even if the process continues to run. + +#### Path filtering + +* `ignored` ([anymatch](https://github.com/es128/anymatch)-compatible definition) +Defines files/paths to be ignored. The whole relative or absolute path is +tested, not just filename. If a function with two arguments is provided, it +gets called twice per path - once with a single argument (the path), second +time with two arguments (the path and the +[`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) +object of that path). +* `ignoreInitial` (default: `false`). If set to `false` then `add`/`addDir` events are also emitted for matching paths while +instantiating the watching as chokidar discovers these file paths (before the `ready` event). +* `followSymlinks` (default: `true`). When `false`, only the +symlinks themselves will be watched for changes instead of following +the link references and bubbling events through the link's path. +* `cwd` (no default). The base directory from which watch `paths` are to be +derived. Paths emitted with events will be relative to this. +* `disableGlobbing` (default: `false`). If set to `true` then the strings passed to `.watch()` and `.add()` are treated as +literal path names, even if they look like globs. + +#### Performance + +* `usePolling` (default: `false`). +Whether to use fs.watchFile (backed by polling), or fs.watch. If polling +leads to high CPU utilization, consider setting this to `false`. It is +typically necessary to **set this to `true` to successfully watch files over +a network**, and it may be necessary to successfully watch files in other +non-standard situations. Setting to `true` explicitly on MacOS overrides the +`useFsEvents` default. You may also set the CHOKIDAR_USEPOLLING env variable +to true (1) or false (0) in order to override this option. +* _Polling-specific settings_ (effective when `usePolling: true`) + * `interval` (default: `100`). Interval of file system polling, in milliseconds. You may also + set the CHOKIDAR_INTERVAL env variable to override this option. + * `binaryInterval` (default: `300`). Interval of file system + polling for binary files. + ([see list of binary extensions](https://github.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json)) +* `useFsEvents` (default: `true` on MacOS). Whether to use the +`fsevents` watching interface if available. When set to `true` explicitly +and `fsevents` is available this supercedes the `usePolling` setting. When +set to `false` on MacOS, `usePolling: true` becomes the default. +* `alwaysStat` (default: `false`). If relying upon the +[`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) +object that may get passed with `add`, `addDir`, and `change` events, set +this to `true` to ensure it is provided even in cases where it wasn't +already available from the underlying watch events. +* `depth` (default: `undefined`). If set, limits how many levels of +subdirectories will be traversed. +* `awaitWriteFinish` (default: `false`). +By default, the `add` event will fire when a file first appears on disk, before +the entire file has been written. Furthermore, in some cases some `change` +events will be emitted while the file is being written. In some cases, +especially when watching for large files there will be a need to wait for the +write operation to finish before responding to a file creation or modification. +Setting `awaitWriteFinish` to `true` (or a truthy value) will poll file size, +holding its `add` and `change` events until the size does not change for a +configurable amount of time. The appropriate duration setting is heavily +dependent on the OS and hardware. For accurate detection this parameter should +be relatively high, making file watching much less responsive. +Use with caution. + * *`options.awaitWriteFinish` can be set to an object in order to adjust + timing params:* + * `awaitWriteFinish.stabilityThreshold` (default: 2000). Amount of time in + milliseconds for a file size to remain constant before emitting its event. + * `awaitWriteFinish.pollInterval` (default: 100). File size polling interval, in milliseconds. + +#### Errors + +* `ignorePermissionErrors` (default: `false`). Indicates whether to watch files +that don't have read permissions if possible. If watching fails due to `EPERM` +or `EACCES` with this set to `true`, the errors will be suppressed silently. +* `atomic` (default: `true` if `useFsEvents` and `usePolling` are `false`). +Automatically filters out artifacts that occur when using editors that use +"atomic writes" instead of writing directly to the source file. If a file is +re-added within 100 ms of being deleted, Chokidar emits a `change` event +rather than `unlink` then `add`. If the default of 100 ms does not work well +for you, you can override it by setting `atomic` to a custom value, in +milliseconds. + +### Methods & Events + +`chokidar.watch()` produces an instance of `FSWatcher`. Methods of `FSWatcher`: + +* `.add(path / paths)`: Add files, directories, or glob patterns for tracking. +Takes an array of strings or just one string. +* `.on(event, callback)`: Listen for an FS event. +Available events: `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `ready`, +`raw`, `error`. +Additionally `all` is available which gets emitted with the underlying event +name and path for every event other than `ready`, `raw`, and `error`. `raw` is internal, use it carefully. +* `.unwatch(path / paths)`: Stop watching files, directories, or glob patterns. +Takes an array of strings or just one string. +* `.close()`: **async** Removes all listeners from watched files. Asynchronous, returns Promise. Use with `await` to ensure bugs don't happen. +* `.getWatched()`: Returns an object representing all the paths on the file +system being watched by this `FSWatcher` instance. The object's keys are all the +directories (using absolute paths unless the `cwd` option was used), and the +values are arrays of the names of the items contained in each directory. + +## CLI + +If you need a CLI interface for your file watching, check out +[chokidar-cli](https://github.com/open-cli-tools/chokidar-cli), allowing you to +execute a command on each change, or get a stdio stream of change events. + +## Install Troubleshooting + +* `npm WARN optional dep failed, continuing fsevents@n.n.n` + * This message is normal part of how `npm` handles optional dependencies and is + not indicative of a problem. Even if accompanied by other related error messages, + Chokidar should function properly. + +* `TypeError: fsevents is not a constructor` + * Update chokidar by doing `rm -rf node_modules package-lock.json yarn.lock && npm install`, or update your dependency that uses chokidar. + +* Chokidar is producing `ENOSP` error on Linux, like this: + * `bash: cannot set terminal process group (-1): Inappropriate ioctl for device bash: no job control in this shell` + `Error: watch /home/ ENOSPC` + * This means Chokidar ran out of file handles and you'll need to increase their count by executing the following command in Terminal: + `echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p` + +## Changelog + +For more detailed changelog, see [`full_changelog.md`](.github/full_changelog.md). +- **v3.5 (Jan 6, 2021):** Support for ARM Macs with Apple Silicon. Fixes for deleted symlinks. +- **v3.4 (Apr 26, 2020):** Support for directory-based symlinks. Fixes for macos file replacement. +- **v3.3 (Nov 2, 2019):** `FSWatcher#close()` method became async. That fixes IO race conditions related to close method. +- **v3.2 (Oct 1, 2019):** Improve Linux RAM usage by 50%. Race condition fixes. Windows glob fixes. Improve stability by using tight range of dependency versions. +- **v3.1 (Sep 16, 2019):** dotfiles are no longer filtered out by default. Use `ignored` option if needed. Improve initial Linux scan time by 50%. +- **v3 (Apr 30, 2019):** massive CPU & RAM consumption improvements; reduces deps / package size by a factor of 17x and bumps Node.js requirement to v8.16 and higher. +- **v2 (Dec 29, 2017):** Globs are now posix-style-only; without windows support. Tons of bugfixes. +- **v1 (Apr 7, 2015):** Glob support, symlink support, tons of bugfixes. Node 0.8+ is supported +- **v0.1 (Apr 20, 2012):** Initial release, extracted from [Brunch](https://github.com/brunch/brunch/blob/9847a065aea300da99bd0753f90354cde9de1261/src/helpers.coffee#L66) + +## Also + +Why was chokidar named this way? What's the meaning behind it? + +>Chowkidar is a transliteration of a Hindi word meaning 'watchman, gatekeeper', चौकीदार. This ultimately comes from Sanskrit _ चतुष्क_ (crossway, quadrangle, consisting-of-four). This word is also used in other languages like Urdu as (چوکیدار) which is widely used in Pakistan and India. + +## License + +MIT (c) Paul Miller (), see [LICENSE](LICENSE) file. diff --git a/node_modules/chokidar/index.js b/node_modules/chokidar/index.js new file mode 100644 index 000000000..8752893ca --- /dev/null +++ b/node_modules/chokidar/index.js @@ -0,0 +1,973 @@ +'use strict'; + +const { EventEmitter } = require('events'); +const fs = require('fs'); +const sysPath = require('path'); +const { promisify } = require('util'); +const readdirp = require('readdirp'); +const anymatch = require('anymatch').default; +const globParent = require('glob-parent'); +const isGlob = require('is-glob'); +const braces = require('braces'); +const normalizePath = require('normalize-path'); + +const NodeFsHandler = require('./lib/nodefs-handler'); +const FsEventsHandler = require('./lib/fsevents-handler'); +const { + EV_ALL, + EV_READY, + EV_ADD, + EV_CHANGE, + EV_UNLINK, + EV_ADD_DIR, + EV_UNLINK_DIR, + EV_RAW, + EV_ERROR, + + STR_CLOSE, + STR_END, + + BACK_SLASH_RE, + DOUBLE_SLASH_RE, + SLASH_OR_BACK_SLASH_RE, + DOT_RE, + REPLACER_RE, + + SLASH, + SLASH_SLASH, + BRACE_START, + BANG, + ONE_DOT, + TWO_DOTS, + GLOBSTAR, + SLASH_GLOBSTAR, + ANYMATCH_OPTS, + STRING_TYPE, + FUNCTION_TYPE, + EMPTY_STR, + EMPTY_FN, + + isWindows, + isMacos, + isIBMi +} = require('./lib/constants'); + +const stat = promisify(fs.stat); +const readdir = promisify(fs.readdir); + +/** + * @typedef {String} Path + * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName + * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType + */ + +/** + * + * @typedef {Object} WatchHelpers + * @property {Boolean} followSymlinks + * @property {'stat'|'lstat'} statMethod + * @property {Path} path + * @property {Path} watchPath + * @property {Function} entryPath + * @property {Boolean} hasGlob + * @property {Object} globFilter + * @property {Function} filterPath + * @property {Function} filterDir + */ + +const arrify = (value = []) => Array.isArray(value) ? value : [value]; +const flatten = (list, result = []) => { + list.forEach(item => { + if (Array.isArray(item)) { + flatten(item, result); + } else { + result.push(item); + } + }); + return result; +}; + +const unifyPaths = (paths_) => { + /** + * @type {Array} + */ + const paths = flatten(arrify(paths_)); + if (!paths.every(p => typeof p === STRING_TYPE)) { + throw new TypeError(`Non-string provided as watch path: ${paths}`); + } + return paths.map(normalizePathToUnix); +}; + +// If SLASH_SLASH occurs at the beginning of path, it is not replaced +// because "//StoragePC/DrivePool/Movies" is a valid network path +const toUnix = (string) => { + let str = string.replace(BACK_SLASH_RE, SLASH); + let prepend = false; + if (str.startsWith(SLASH_SLASH)) { + prepend = true; + } + while (str.match(DOUBLE_SLASH_RE)) { + str = str.replace(DOUBLE_SLASH_RE, SLASH); + } + if (prepend) { + str = SLASH + str; + } + return str; +}; + +// Our version of upath.normalize +// TODO: this is not equal to path-normalize module - investigate why +const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path))); + +const normalizeIgnored = (cwd = EMPTY_STR) => (path) => { + if (typeof path !== STRING_TYPE) return path; + return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path)); +}; + +const getAbsolutePath = (path, cwd) => { + if (sysPath.isAbsolute(path)) { + return path; + } + if (path.startsWith(BANG)) { + return BANG + sysPath.join(cwd, path.slice(1)); + } + return sysPath.join(cwd, path); +}; + +const undef = (opts, key) => opts[key] === undefined; + +/** + * Directory entry. + * @property {Path} path + * @property {Set} items + */ +class DirEntry { + /** + * @param {Path} dir + * @param {Function} removeWatcher + */ + constructor(dir, removeWatcher) { + this.path = dir; + this._removeWatcher = removeWatcher; + /** @type {Set} */ + this.items = new Set(); + } + + add(item) { + const {items} = this; + if (!items) return; + if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item); + } + + async remove(item) { + const {items} = this; + if (!items) return; + items.delete(item); + if (items.size > 0) return; + + const dir = this.path; + try { + await readdir(dir); + } catch (err) { + if (this._removeWatcher) { + this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir)); + } + } + } + + has(item) { + const {items} = this; + if (!items) return; + return items.has(item); + } + + /** + * @returns {Array} + */ + getChildren() { + const {items} = this; + if (!items) return; + return [...items.values()]; + } + + dispose() { + this.items.clear(); + delete this.path; + delete this._removeWatcher; + delete this.items; + Object.freeze(this); + } +} + +const STAT_METHOD_F = 'stat'; +const STAT_METHOD_L = 'lstat'; +class WatchHelper { + constructor(path, watchPath, follow, fsw) { + this.fsw = fsw; + this.path = path = path.replace(REPLACER_RE, EMPTY_STR); + this.watchPath = watchPath; + this.fullWatchPath = sysPath.resolve(watchPath); + this.hasGlob = watchPath !== path; + /** @type {object|boolean} */ + if (path === EMPTY_STR) this.hasGlob = false; + this.globSymlink = this.hasGlob && follow ? undefined : false; + this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false; + this.dirParts = this.getDirParts(path); + this.dirParts.forEach((parts) => { + if (parts.length > 1) parts.pop(); + }); + this.followSymlinks = follow; + this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L; + } + + checkGlobSymlink(entry) { + // only need to resolve once + // first entry should always have entry.parentDir === EMPTY_STR + if (this.globSymlink === undefined) { + this.globSymlink = entry.fullParentDir === this.fullWatchPath ? + false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath}; + } + + if (this.globSymlink) { + return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath); + } + + return entry.fullPath; + } + + entryPath(entry) { + return sysPath.join(this.watchPath, + sysPath.relative(this.watchPath, this.checkGlobSymlink(entry)) + ); + } + + filterPath(entry) { + const {stats} = entry; + if (stats && stats.isSymbolicLink()) return this.filterDir(entry); + const resolvedPath = this.entryPath(entry); + const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ? + this.globFilter(resolvedPath) : true; + return matchesGlob && + this.fsw._isntIgnored(resolvedPath, stats) && + this.fsw._hasReadPermissions(stats); + } + + getDirParts(path) { + if (!this.hasGlob) return []; + const parts = []; + const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path]; + expandedPath.forEach((path) => { + parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE)); + }); + return parts; + } + + filterDir(entry) { + if (this.hasGlob) { + const entryParts = this.getDirParts(this.checkGlobSymlink(entry)); + let globstar = false; + this.unmatchedGlob = !this.dirParts.some((parts) => { + return parts.every((part, i) => { + if (part === GLOBSTAR) globstar = true; + return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS); + }); + }); + } + return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats); + } +} + +/** + * Watches files & directories for changes. Emitted events: + * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error` + * + * new FSWatcher() + * .add(directories) + * .on('add', path => log('File', path, 'was added')) + */ +class FSWatcher extends EventEmitter { +// Not indenting methods for history sake; for now. +constructor(_opts) { + super(); + + const opts = {}; + if (_opts) Object.assign(opts, _opts); // for frozen objects + + /** @type {Map} */ + this._watched = new Map(); + /** @type {Map} */ + this._closers = new Map(); + /** @type {Set} */ + this._ignoredPaths = new Set(); + + /** @type {Map} */ + this._throttled = new Map(); + + /** @type {Map} */ + this._symlinkPaths = new Map(); + + this._streams = new Set(); + this.closed = false; + + // Set up default options. + if (undef(opts, 'persistent')) opts.persistent = true; + if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false; + if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false; + if (undef(opts, 'interval')) opts.interval = 100; + if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300; + if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false; + opts.enableBinaryInterval = opts.binaryInterval !== opts.interval; + + // Enable fsevents on OS X when polling isn't explicitly enabled. + if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling; + + // If we can't use fsevents, ensure the options reflect it's disabled. + const canUseFsEvents = FsEventsHandler.canUse(); + if (!canUseFsEvents) opts.useFsEvents = false; + + // Use polling on Mac if not using fsevents. + // Other platforms use non-polling fs_watch. + if (undef(opts, 'usePolling') && !opts.useFsEvents) { + opts.usePolling = isMacos; + } + + // Always default to polling on IBM i because fs.watch() is not available on IBM i. + if(isIBMi) { + opts.usePolling = true; + } + + // Global override (useful for end-developers that need to force polling for all + // instances of chokidar, regardless of usage/dependency depth) + const envPoll = process.env.CHOKIDAR_USEPOLLING; + if (envPoll !== undefined) { + const envLower = envPoll.toLowerCase(); + + if (envLower === 'false' || envLower === '0') { + opts.usePolling = false; + } else if (envLower === 'true' || envLower === '1') { + opts.usePolling = true; + } else { + opts.usePolling = !!envLower; + } + } + const envInterval = process.env.CHOKIDAR_INTERVAL; + if (envInterval) { + opts.interval = Number.parseInt(envInterval, 10); + } + + // Editor atomic write normalization enabled by default with fs.watch + if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents; + if (opts.atomic) this._pendingUnlinks = new Map(); + + if (undef(opts, 'followSymlinks')) opts.followSymlinks = true; + + if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false; + if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {}; + const awf = opts.awaitWriteFinish; + if (awf) { + if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000; + if (!awf.pollInterval) awf.pollInterval = 100; + this._pendingWrites = new Map(); + } + if (opts.ignored) opts.ignored = arrify(opts.ignored); + + let readyCalls = 0; + this._emitReady = () => { + readyCalls++; + if (readyCalls >= this._readyCount) { + this._emitReady = EMPTY_FN; + this._readyEmitted = true; + // use process.nextTick to allow time for listener to be bound + process.nextTick(() => this.emit(EV_READY)); + } + }; + this._emitRaw = (...args) => this.emit(EV_RAW, ...args); + this._readyEmitted = false; + this.options = opts; + + // Initialize with proper watcher. + if (opts.useFsEvents) { + this._fsEventsHandler = new FsEventsHandler(this); + } else { + this._nodeFsHandler = new NodeFsHandler(this); + } + + // You’re frozen when your heart’s not open. + Object.freeze(opts); +} + +// Public methods + +/** + * Adds paths to be watched on an existing FSWatcher instance + * @param {Path|Array} paths_ + * @param {String=} _origAdd private; for handling non-existent paths to be watched + * @param {Boolean=} _internal private; indicates a non-user add + * @returns {FSWatcher} for chaining + */ +add(paths_, _origAdd, _internal) { + const {cwd, disableGlobbing} = this.options; + this.closed = false; + let paths = unifyPaths(paths_); + if (cwd) { + paths = paths.map((path) => { + const absPath = getAbsolutePath(path, cwd); + + // Check `path` instead of `absPath` because the cwd portion can't be a glob + if (disableGlobbing || !isGlob(path)) { + return absPath; + } + return normalizePath(absPath); + }); + } + + // set aside negated glob strings + paths = paths.filter((path) => { + if (path.startsWith(BANG)) { + this._ignoredPaths.add(path.slice(1)); + return false; + } + + // if a path is being added that was previously ignored, stop ignoring it + this._ignoredPaths.delete(path); + this._ignoredPaths.delete(path + SLASH_GLOBSTAR); + + // reset the cached userIgnored anymatch fn + // to make ignoredPaths changes effective + this._userIgnored = undefined; + + return true; + }); + + if (this.options.useFsEvents && this._fsEventsHandler) { + if (!this._readyCount) this._readyCount = paths.length; + if (this.options.persistent) this._readyCount += paths.length; + paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path)); + } else { + if (!this._readyCount) this._readyCount = 0; + this._readyCount += paths.length; + Promise.all( + paths.map(async path => { + const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd); + if (res) this._emitReady(); + return res; + }) + ).then(results => { + if (this.closed) return; + results.filter(item => item).forEach(item => { + this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item)); + }); + }); + } + + return this; +} + +/** + * Close watchers or start ignoring events from specified paths. + * @param {Path|Array} paths_ - string or array of strings, file/directory paths and/or globs + * @returns {FSWatcher} for chaining +*/ +unwatch(paths_) { + if (this.closed) return this; + const paths = unifyPaths(paths_); + const {cwd} = this.options; + + paths.forEach((path) => { + // convert to absolute path unless relative path already matches + if (!sysPath.isAbsolute(path) && !this._closers.has(path)) { + if (cwd) path = sysPath.join(cwd, path); + path = sysPath.resolve(path); + } + + this._closePath(path); + + this._ignoredPaths.add(path); + if (this._watched.has(path)) { + this._ignoredPaths.add(path + SLASH_GLOBSTAR); + } + + // reset the cached userIgnored anymatch fn + // to make ignoredPaths changes effective + this._userIgnored = undefined; + }); + + return this; +} + +/** + * Close watchers and remove all listeners from watched paths. + * @returns {Promise}. +*/ +close() { + if (this.closed) return this._closePromise; + this.closed = true; + + // Memory management. + this.removeAllListeners(); + const closers = []; + this._closers.forEach(closerList => closerList.forEach(closer => { + const promise = closer(); + if (promise instanceof Promise) closers.push(promise); + })); + this._streams.forEach(stream => stream.destroy()); + this._userIgnored = undefined; + this._readyCount = 0; + this._readyEmitted = false; + this._watched.forEach(dirent => dirent.dispose()); + ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => { + this[`_${key}`].clear(); + }); + + this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve(); + return this._closePromise; +} + +/** + * Expose list of watched paths + * @returns {Object} for chaining +*/ +getWatched() { + const watchList = {}; + this._watched.forEach((entry, dir) => { + const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir; + watchList[key || ONE_DOT] = entry.getChildren().sort(); + }); + return watchList; +} + +emitWithAll(event, args) { + this.emit(...args); + if (event !== EV_ERROR) this.emit(EV_ALL, ...args); +} + +// Common helpers +// -------------- + +/** + * Normalize and emit events. + * Calling _emit DOES NOT MEAN emit() would be called! + * @param {EventName} event Type of event + * @param {Path} path File or directory path + * @param {*=} val1 arguments to be passed with event + * @param {*=} val2 + * @param {*=} val3 + * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag + */ +async _emit(event, path, val1, val2, val3) { + if (this.closed) return; + + const opts = this.options; + if (isWindows) path = sysPath.normalize(path); + if (opts.cwd) path = sysPath.relative(opts.cwd, path); + /** @type Array */ + const args = [event, path]; + if (val3 !== undefined) args.push(val1, val2, val3); + else if (val2 !== undefined) args.push(val1, val2); + else if (val1 !== undefined) args.push(val1); + + const awf = opts.awaitWriteFinish; + let pw; + if (awf && (pw = this._pendingWrites.get(path))) { + pw.lastChange = new Date(); + return this; + } + + if (opts.atomic) { + if (event === EV_UNLINK) { + this._pendingUnlinks.set(path, args); + setTimeout(() => { + this._pendingUnlinks.forEach((entry, path) => { + this.emit(...entry); + this.emit(EV_ALL, ...entry); + this._pendingUnlinks.delete(path); + }); + }, typeof opts.atomic === 'number' ? opts.atomic : 100); + return this; + } + if (event === EV_ADD && this._pendingUnlinks.has(path)) { + event = args[0] = EV_CHANGE; + this._pendingUnlinks.delete(path); + } + } + + if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) { + const awfEmit = (err, stats) => { + if (err) { + event = args[0] = EV_ERROR; + args[1] = err; + this.emitWithAll(event, args); + } else if (stats) { + // if stats doesn't exist the file must have been deleted + if (args.length > 2) { + args[2] = stats; + } else { + args.push(stats); + } + this.emitWithAll(event, args); + } + }; + + this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit); + return this; + } + + if (event === EV_CHANGE) { + const isThrottled = !this._throttle(EV_CHANGE, path, 50); + if (isThrottled) return this; + } + + if (opts.alwaysStat && val1 === undefined && + (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE) + ) { + const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path; + let stats; + try { + stats = await stat(fullPath); + } catch (err) {} + // Suppress event when fs_stat fails, to avoid sending undefined 'stat' + if (!stats || this.closed) return; + args.push(stats); + } + this.emitWithAll(event, args); + + return this; +} + +/** + * Common handler for errors + * @param {Error} error + * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag + */ +_handleError(error) { + const code = error && error.code; + if (error && code !== 'ENOENT' && code !== 'ENOTDIR' && + (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES')) + ) { + this.emit(EV_ERROR, error); + } + return error || this.closed; +} + +/** + * Helper utility for throttling + * @param {ThrottleType} actionType type being throttled + * @param {Path} path being acted upon + * @param {Number} timeout duration of time to suppress duplicate actions + * @returns {Object|false} tracking object or false if action should be suppressed + */ +_throttle(actionType, path, timeout) { + if (!this._throttled.has(actionType)) { + this._throttled.set(actionType, new Map()); + } + + /** @type {Map} */ + const action = this._throttled.get(actionType); + /** @type {Object} */ + const actionPath = action.get(path); + + if (actionPath) { + actionPath.count++; + return false; + } + + let timeoutObject; + const clear = () => { + const item = action.get(path); + const count = item ? item.count : 0; + action.delete(path); + clearTimeout(timeoutObject); + if (item) clearTimeout(item.timeoutObject); + return count; + }; + timeoutObject = setTimeout(clear, timeout); + const thr = {timeoutObject, clear, count: 0}; + action.set(path, thr); + return thr; +} + +_incrReadyCount() { + return this._readyCount++; +} + +/** + * Awaits write operation to finish. + * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback. + * @param {Path} path being acted upon + * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished + * @param {EventName} event + * @param {Function} awfEmit Callback to be called when ready for event to be emitted. + */ +_awaitWriteFinish(path, threshold, event, awfEmit) { + let timeoutHandler; + + let fullPath = path; + if (this.options.cwd && !sysPath.isAbsolute(path)) { + fullPath = sysPath.join(this.options.cwd, path); + } + + const now = new Date(); + + const awaitWriteFinish = (prevStat) => { + fs.stat(fullPath, (err, curStat) => { + if (err || !this._pendingWrites.has(path)) { + if (err && err.code !== 'ENOENT') awfEmit(err); + return; + } + + const now = Number(new Date()); + + if (prevStat && curStat.size !== prevStat.size) { + this._pendingWrites.get(path).lastChange = now; + } + const pw = this._pendingWrites.get(path); + const df = now - pw.lastChange; + + if (df >= threshold) { + this._pendingWrites.delete(path); + awfEmit(undefined, curStat); + } else { + timeoutHandler = setTimeout( + awaitWriteFinish, + this.options.awaitWriteFinish.pollInterval, + curStat + ); + } + }); + }; + + if (!this._pendingWrites.has(path)) { + this._pendingWrites.set(path, { + lastChange: now, + cancelWait: () => { + this._pendingWrites.delete(path); + clearTimeout(timeoutHandler); + return event; + } + }); + timeoutHandler = setTimeout( + awaitWriteFinish, + this.options.awaitWriteFinish.pollInterval + ); + } +} + +_getGlobIgnored() { + return [...this._ignoredPaths.values()]; +} + +/** + * Determines whether user has asked to ignore this path. + * @param {Path} path filepath or dir + * @param {fs.Stats=} stats result of fs.stat + * @returns {Boolean} + */ +_isIgnored(path, stats) { + if (this.options.atomic && DOT_RE.test(path)) return true; + if (!this._userIgnored) { + const {cwd} = this.options; + const ign = this.options.ignored; + + const ignored = ign && ign.map(normalizeIgnored(cwd)); + const paths = arrify(ignored) + .filter((path) => typeof path === STRING_TYPE && !isGlob(path)) + .map((path) => path + SLASH_GLOBSTAR); + const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths); + this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS); + } + + return this._userIgnored([path, stats]); +} + +_isntIgnored(path, stat) { + return !this._isIgnored(path, stat); +} + +/** + * Provides a set of common helpers and properties relating to symlink and glob handling. + * @param {Path} path file, directory, or glob pattern being watched + * @param {Number=} depth at any depth > 0, this isn't a glob + * @returns {WatchHelper} object containing helpers for this path + */ +_getWatchHelpers(path, depth) { + const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path); + const follow = this.options.followSymlinks; + + return new WatchHelper(path, watchPath, follow, this); +} + +// Directory helpers +// ----------------- + +/** + * Provides directory tracking objects + * @param {String} directory path of the directory + * @returns {DirEntry} the directory's tracking object + */ +_getWatchedDir(directory) { + if (!this._boundRemove) this._boundRemove = this._remove.bind(this); + const dir = sysPath.resolve(directory); + if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove)); + return this._watched.get(dir); +} + +// File helpers +// ------------ + +/** + * Check for read permissions. + * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405 + * @param {fs.Stats} stats - object, result of fs_stat + * @returns {Boolean} indicates whether the file can be read +*/ +_hasReadPermissions(stats) { + if (this.options.ignorePermissionErrors) return true; + + // stats.mode may be bigint + const md = stats && Number.parseInt(stats.mode, 10); + const st = md & 0o777; + const it = Number.parseInt(st.toString(8)[0], 10); + return Boolean(4 & it); +} + +/** + * Handles emitting unlink events for + * files and directories, and via recursion, for + * files and directories within directories that are unlinked + * @param {String} directory within which the following item is located + * @param {String} item base path of item/directory + * @returns {void} +*/ +_remove(directory, item, isDirectory) { + // if what is being deleted is a directory, get that directory's paths + // for recursive deleting and cleaning of watched object + // if it is not a directory, nestedDirectoryChildren will be empty array + const path = sysPath.join(directory, item); + const fullPath = sysPath.resolve(path); + isDirectory = isDirectory != null + ? isDirectory + : this._watched.has(path) || this._watched.has(fullPath); + + // prevent duplicate handling in case of arriving here nearly simultaneously + // via multiple paths (such as _handleFile and _handleDir) + if (!this._throttle('remove', path, 100)) return; + + // if the only watched file is removed, watch for its return + if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) { + this.add(directory, item, true); + } + + // This will create a new entry in the watched object in either case + // so we got to do the directory check beforehand + const wp = this._getWatchedDir(path); + const nestedDirectoryChildren = wp.getChildren(); + + // Recursively remove children directories / files. + nestedDirectoryChildren.forEach(nested => this._remove(path, nested)); + + // Check if item was on the watched list and remove it + const parent = this._getWatchedDir(directory); + const wasTracked = parent.has(item); + parent.remove(item); + + // Fixes issue #1042 -> Relative paths were detected and added as symlinks + // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612), + // but never removed from the map in case the path was deleted. + // This leads to an incorrect state if the path was recreated: + // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553 + if (this._symlinkPaths.has(fullPath)) { + this._symlinkPaths.delete(fullPath); + } + + // If we wait for this file to be fully written, cancel the wait. + let relPath = path; + if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path); + if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) { + const event = this._pendingWrites.get(relPath).cancelWait(); + if (event === EV_ADD) return; + } + + // The Entry will either be a directory that just got removed + // or a bogus entry to a file, in either case we have to remove it + this._watched.delete(path); + this._watched.delete(fullPath); + const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK; + if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path); + + // Avoid conflicts if we later create another file with the same name + if (!this.options.useFsEvents) { + this._closePath(path); + } +} + +/** + * Closes all watchers for a path + * @param {Path} path + */ +_closePath(path) { + this._closeFile(path) + const dir = sysPath.dirname(path); + this._getWatchedDir(dir).remove(sysPath.basename(path)); +} + +/** + * Closes only file-specific watchers + * @param {Path} path + */ +_closeFile(path) { + const closers = this._closers.get(path); + if (!closers) return; + closers.forEach(closer => closer()); + this._closers.delete(path); +} + +/** + * + * @param {Path} path + * @param {Function} closer + */ +_addPathCloser(path, closer) { + if (!closer) return; + let list = this._closers.get(path); + if (!list) { + list = []; + this._closers.set(path, list); + } + list.push(closer); +} + +_readdirp(root, opts) { + if (this.closed) return; + const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts}; + let stream = readdirp(root, options); + this._streams.add(stream); + stream.once(STR_CLOSE, () => { + stream = undefined; + }); + stream.once(STR_END, () => { + if (stream) { + this._streams.delete(stream); + stream = undefined; + } + }); + return stream; +} + +} + +// Export FSWatcher class +exports.FSWatcher = FSWatcher; + +/** + * Instantiates watcher with paths to be tracked. + * @param {String|Array} paths file/directory paths and/or globs + * @param {Object=} options chokidar opts + * @returns an instance of FSWatcher for chaining. + */ +const watch = (paths, options) => { + const watcher = new FSWatcher(options); + watcher.add(paths); + return watcher; +}; + +exports.watch = watch; diff --git a/node_modules/chokidar/lib/constants.js b/node_modules/chokidar/lib/constants.js new file mode 100644 index 000000000..4743865d6 --- /dev/null +++ b/node_modules/chokidar/lib/constants.js @@ -0,0 +1,66 @@ +'use strict'; + +const {sep} = require('path'); +const {platform} = process; +const os = require('os'); + +exports.EV_ALL = 'all'; +exports.EV_READY = 'ready'; +exports.EV_ADD = 'add'; +exports.EV_CHANGE = 'change'; +exports.EV_ADD_DIR = 'addDir'; +exports.EV_UNLINK = 'unlink'; +exports.EV_UNLINK_DIR = 'unlinkDir'; +exports.EV_RAW = 'raw'; +exports.EV_ERROR = 'error'; + +exports.STR_DATA = 'data'; +exports.STR_END = 'end'; +exports.STR_CLOSE = 'close'; + +exports.FSEVENT_CREATED = 'created'; +exports.FSEVENT_MODIFIED = 'modified'; +exports.FSEVENT_DELETED = 'deleted'; +exports.FSEVENT_MOVED = 'moved'; +exports.FSEVENT_CLONED = 'cloned'; +exports.FSEVENT_UNKNOWN = 'unknown'; +exports.FSEVENT_FLAG_MUST_SCAN_SUBDIRS = 1; +exports.FSEVENT_TYPE_FILE = 'file'; +exports.FSEVENT_TYPE_DIRECTORY = 'directory'; +exports.FSEVENT_TYPE_SYMLINK = 'symlink'; + +exports.KEY_LISTENERS = 'listeners'; +exports.KEY_ERR = 'errHandlers'; +exports.KEY_RAW = 'rawEmitters'; +exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW]; + +exports.DOT_SLASH = `.${sep}`; + +exports.BACK_SLASH_RE = /\\/g; +exports.DOUBLE_SLASH_RE = /\/\//; +exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/; +exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/; +exports.REPLACER_RE = /^\.[/\\]/; + +exports.SLASH = '/'; +exports.SLASH_SLASH = '//'; +exports.BRACE_START = '{'; +exports.BANG = '!'; +exports.ONE_DOT = '.'; +exports.TWO_DOTS = '..'; +exports.STAR = '*'; +exports.GLOBSTAR = '**'; +exports.ROOT_GLOBSTAR = '/**/*'; +exports.SLASH_GLOBSTAR = '/**'; +exports.DIR_SUFFIX = 'Dir'; +exports.ANYMATCH_OPTS = {dot: true}; +exports.STRING_TYPE = 'string'; +exports.FUNCTION_TYPE = 'function'; +exports.EMPTY_STR = ''; +exports.EMPTY_FN = () => {}; +exports.IDENTITY_FN = val => val; + +exports.isWindows = platform === 'win32'; +exports.isMacos = platform === 'darwin'; +exports.isLinux = platform === 'linux'; +exports.isIBMi = os.type() === 'OS400'; diff --git a/node_modules/chokidar/lib/fsevents-handler.js b/node_modules/chokidar/lib/fsevents-handler.js new file mode 100644 index 000000000..fe29393c1 --- /dev/null +++ b/node_modules/chokidar/lib/fsevents-handler.js @@ -0,0 +1,526 @@ +'use strict'; + +const fs = require('fs'); +const sysPath = require('path'); +const { promisify } = require('util'); + +let fsevents; +try { + fsevents = require('fsevents'); +} catch (error) { + if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error); +} + +if (fsevents) { + // TODO: real check + const mtch = process.version.match(/v(\d+)\.(\d+)/); + if (mtch && mtch[1] && mtch[2]) { + const maj = Number.parseInt(mtch[1], 10); + const min = Number.parseInt(mtch[2], 10); + if (maj === 8 && min < 16) { + fsevents = undefined; + } + } +} + +const { + EV_ADD, + EV_CHANGE, + EV_ADD_DIR, + EV_UNLINK, + EV_ERROR, + STR_DATA, + STR_END, + FSEVENT_CREATED, + FSEVENT_MODIFIED, + FSEVENT_DELETED, + FSEVENT_MOVED, + // FSEVENT_CLONED, + FSEVENT_UNKNOWN, + FSEVENT_FLAG_MUST_SCAN_SUBDIRS, + FSEVENT_TYPE_FILE, + FSEVENT_TYPE_DIRECTORY, + FSEVENT_TYPE_SYMLINK, + + ROOT_GLOBSTAR, + DIR_SUFFIX, + DOT_SLASH, + FUNCTION_TYPE, + EMPTY_FN, + IDENTITY_FN +} = require('./constants'); + +const Depth = (value) => isNaN(value) ? {} : {depth: value}; + +const stat = promisify(fs.stat); +const lstat = promisify(fs.lstat); +const realpath = promisify(fs.realpath); + +const statMethods = { stat, lstat }; + +/** + * @typedef {String} Path + */ + +/** + * @typedef {Object} FsEventsWatchContainer + * @property {Set} listeners + * @property {Function} rawEmitter + * @property {{stop: Function}} watcher + */ + +// fsevents instance helper functions +/** + * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances) + * @type {Map} + */ +const FSEventsWatchers = new Map(); + +// Threshold of duplicate path prefixes at which to start +// consolidating going forward +const consolidateThreshhold = 10; + +const wrongEventFlags = new Set([ + 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912 +]); + +/** + * Instantiates the fsevents interface + * @param {Path} path path to be watched + * @param {Function} callback called when fsevents is bound and ready + * @returns {{stop: Function}} new fsevents instance + */ +const createFSEventsInstance = (path, callback) => { + const stop = fsevents.watch(path, callback); + return {stop}; +}; + +/** + * Instantiates the fsevents interface or binds listeners to an existing one covering + * the same file tree. + * @param {Path} path - to be watched + * @param {Path} realPath - real path for symlinks + * @param {Function} listener - called when fsevents emits events + * @param {Function} rawEmitter - passes data to listeners of the 'raw' event + * @returns {Function} closer + */ +function setFSEventsListener(path, realPath, listener, rawEmitter) { + let watchPath = sysPath.extname(realPath) ? sysPath.dirname(realPath) : realPath; + + const parentPath = sysPath.dirname(watchPath); + let cont = FSEventsWatchers.get(watchPath); + + // If we've accumulated a substantial number of paths that + // could have been consolidated by watching one directory + // above the current one, create a watcher on the parent + // path instead, so that we do consolidate going forward. + if (couldConsolidate(parentPath)) { + watchPath = parentPath; + } + + const resolvedPath = sysPath.resolve(path); + const hasSymlink = resolvedPath !== realPath; + + const filteredListener = (fullPath, flags, info) => { + if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath); + if ( + fullPath === resolvedPath || + !fullPath.indexOf(resolvedPath + sysPath.sep) + ) listener(fullPath, flags, info); + }; + + // check if there is already a watcher on a parent path + // modifies `watchPath` to the parent path when it finds a match + let watchedParent = false; + for (const watchedPath of FSEventsWatchers.keys()) { + if (realPath.indexOf(sysPath.resolve(watchedPath) + sysPath.sep) === 0) { + watchPath = watchedPath; + cont = FSEventsWatchers.get(watchPath); + watchedParent = true; + break; + } + } + + if (cont || watchedParent) { + cont.listeners.add(filteredListener); + } else { + cont = { + listeners: new Set([filteredListener]), + rawEmitter, + watcher: createFSEventsInstance(watchPath, (fullPath, flags) => { + if (!cont.listeners.size) return; + if (flags & FSEVENT_FLAG_MUST_SCAN_SUBDIRS) return; + const info = fsevents.getInfo(fullPath, flags); + cont.listeners.forEach(list => { + list(fullPath, flags, info); + }); + + cont.rawEmitter(info.event, fullPath, info); + }) + }; + FSEventsWatchers.set(watchPath, cont); + } + + // removes this instance's listeners and closes the underlying fsevents + // instance if there are no more listeners left + return () => { + const lst = cont.listeners; + + lst.delete(filteredListener); + if (!lst.size) { + FSEventsWatchers.delete(watchPath); + if (cont.watcher) return cont.watcher.stop().then(() => { + cont.rawEmitter = cont.watcher = undefined; + Object.freeze(cont); + }); + } + }; +} + +// Decide whether or not we should start a new higher-level +// parent watcher +const couldConsolidate = (path) => { + let count = 0; + for (const watchPath of FSEventsWatchers.keys()) { + if (watchPath.indexOf(path) === 0) { + count++; + if (count >= consolidateThreshhold) { + return true; + } + } + } + + return false; +}; + +// returns boolean indicating whether fsevents can be used +const canUse = () => fsevents && FSEventsWatchers.size < 128; + +// determines subdirectory traversal levels from root to path +const calcDepth = (path, root) => { + let i = 0; + while (!path.indexOf(root) && (path = sysPath.dirname(path)) !== root) i++; + return i; +}; + +// returns boolean indicating whether the fsevents' event info has the same type +// as the one returned by fs.stat +const sameTypes = (info, stats) => ( + info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() || + info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() || + info.type === FSEVENT_TYPE_FILE && stats.isFile() +) + +/** + * @mixin + */ +class FsEventsHandler { + +/** + * @param {import('../index').FSWatcher} fsw + */ +constructor(fsw) { + this.fsw = fsw; +} +checkIgnored(path, stats) { + const ipaths = this.fsw._ignoredPaths; + if (this.fsw._isIgnored(path, stats)) { + ipaths.add(path); + if (stats && stats.isDirectory()) { + ipaths.add(path + ROOT_GLOBSTAR); + } + return true; + } + + ipaths.delete(path); + ipaths.delete(path + ROOT_GLOBSTAR); +} + +addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) { + const event = watchedDir.has(item) ? EV_CHANGE : EV_ADD; + this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts); +} + +async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) { + try { + const stats = await stat(path) + if (this.fsw.closed) return; + if (sameTypes(info, stats)) { + this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } else { + this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } catch (error) { + if (error.code === 'EACCES') { + this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } else { + this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } +} + +handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) { + if (this.fsw.closed || this.checkIgnored(path)) return; + + if (event === EV_UNLINK) { + const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY + // suppress unlink events on never before seen files + if (isDirectory || watchedDir.has(item)) { + this.fsw._remove(parent, item, isDirectory); + } + } else { + if (event === EV_ADD) { + // track new directories + if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path); + + if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) { + // push symlinks back to the top of the stack to get handled + const curDepth = opts.depth === undefined ? + undefined : calcDepth(fullPath, realPath) + 1; + return this._addToFsEvents(path, false, true, curDepth); + } + + // track new paths + // (other than symlinks being followed, which will be tracked soon) + this.fsw._getWatchedDir(parent).add(item); + } + /** + * @type {'add'|'addDir'|'unlink'|'unlinkDir'} + */ + const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event; + this.fsw._emit(eventName, path); + if (eventName === EV_ADD_DIR) this._addToFsEvents(path, false, true); + } +} + +/** + * Handle symlinks encountered during directory scan + * @param {String} watchPath - file/dir path to be watched with fsevents + * @param {String} realPath - real path (in case of symlinks) + * @param {Function} transform - path transformer + * @param {Function} globFilter - path filter in case a glob pattern was provided + * @returns {Function} closer for the watcher instance +*/ +_watchWithFsEvents(watchPath, realPath, transform, globFilter) { + if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return; + const opts = this.fsw.options; + const watchCallback = async (fullPath, flags, info) => { + if (this.fsw.closed) return; + if ( + opts.depth !== undefined && + calcDepth(fullPath, realPath) > opts.depth + ) return; + const path = transform(sysPath.join( + watchPath, sysPath.relative(watchPath, fullPath) + )); + if (globFilter && !globFilter(path)) return; + // ensure directories are tracked + const parent = sysPath.dirname(path); + const item = sysPath.basename(path); + const watchedDir = this.fsw._getWatchedDir( + info.type === FSEVENT_TYPE_DIRECTORY ? path : parent + ); + + // correct for wrong events emitted + if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) { + if (typeof opts.ignored === FUNCTION_TYPE) { + let stats; + try { + stats = await stat(path); + } catch (error) {} + if (this.fsw.closed) return; + if (this.checkIgnored(path, stats)) return; + if (sameTypes(info, stats)) { + this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } else { + this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } else { + this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } else { + switch (info.event) { + case FSEVENT_CREATED: + case FSEVENT_MODIFIED: + return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + case FSEVENT_DELETED: + case FSEVENT_MOVED: + return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } + }; + + const closer = setFSEventsListener( + watchPath, + realPath, + watchCallback, + this.fsw._emitRaw + ); + + this.fsw._emitReady(); + return closer; +} + +/** + * Handle symlinks encountered during directory scan + * @param {String} linkPath path to symlink + * @param {String} fullPath absolute path to the symlink + * @param {Function} transform pre-existing path transformer + * @param {Number} curDepth level of subdirectories traversed to where symlink is + * @returns {Promise} + */ +async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) { + // don't follow the same symlink more than once + if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return; + + this.fsw._symlinkPaths.set(fullPath, true); + this.fsw._incrReadyCount(); + + try { + const linkTarget = await realpath(linkPath); + if (this.fsw.closed) return; + if (this.fsw._isIgnored(linkTarget)) { + return this.fsw._emitReady(); + } + + this.fsw._incrReadyCount(); + + // add the linkTarget for watching with a wrapper for transform + // that causes emitted paths to incorporate the link's path + this._addToFsEvents(linkTarget || linkPath, (path) => { + let aliasedPath = linkPath; + if (linkTarget && linkTarget !== DOT_SLASH) { + aliasedPath = path.replace(linkTarget, linkPath); + } else if (path !== DOT_SLASH) { + aliasedPath = sysPath.join(linkPath, path); + } + return transform(aliasedPath); + }, false, curDepth); + } catch(error) { + if (this.fsw._handleError(error)) { + return this.fsw._emitReady(); + } + } +} + +/** + * + * @param {Path} newPath + * @param {fs.Stats} stats + */ +emitAdd(newPath, stats, processPath, opts, forceAdd) { + const pp = processPath(newPath); + const isDir = stats.isDirectory(); + const dirObj = this.fsw._getWatchedDir(sysPath.dirname(pp)); + const base = sysPath.basename(pp); + + // ensure empty dirs get tracked + if (isDir) this.fsw._getWatchedDir(pp); + if (dirObj.has(base)) return; + dirObj.add(base); + + if (!opts.ignoreInitial || forceAdd === true) { + this.fsw._emit(isDir ? EV_ADD_DIR : EV_ADD, pp, stats); + } +} + +initWatch(realPath, path, wh, processPath) { + if (this.fsw.closed) return; + const closer = this._watchWithFsEvents( + wh.watchPath, + sysPath.resolve(realPath || wh.watchPath), + processPath, + wh.globFilter + ); + this.fsw._addPathCloser(path, closer); +} + +/** + * Handle added path with fsevents + * @param {String} path file/dir path or glob pattern + * @param {Function|Boolean=} transform converts working path to what the user expects + * @param {Boolean=} forceAdd ensure add is emitted + * @param {Number=} priorDepth Level of subdirectories already traversed. + * @returns {Promise} + */ +async _addToFsEvents(path, transform, forceAdd, priorDepth) { + if (this.fsw.closed) { + return; + } + const opts = this.fsw.options; + const processPath = typeof transform === FUNCTION_TYPE ? transform : IDENTITY_FN; + + const wh = this.fsw._getWatchHelpers(path); + + // evaluate what is at the path we're being asked to watch + try { + const stats = await statMethods[wh.statMethod](wh.watchPath); + if (this.fsw.closed) return; + if (this.fsw._isIgnored(wh.watchPath, stats)) { + throw null; + } + if (stats.isDirectory()) { + // emit addDir unless this is a glob parent + if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd); + + // don't recurse further if it would exceed depth setting + if (priorDepth && priorDepth > opts.depth) return; + + // scan the contents of the dir + this.fsw._readdirp(wh.watchPath, { + fileFilter: entry => wh.filterPath(entry), + directoryFilter: entry => wh.filterDir(entry), + ...Depth(opts.depth - (priorDepth || 0)) + }).on(STR_DATA, (entry) => { + // need to check filterPath on dirs b/c filterDir is less restrictive + if (this.fsw.closed) { + return; + } + if (entry.stats.isDirectory() && !wh.filterPath(entry)) return; + + const joinedPath = sysPath.join(wh.watchPath, entry.path); + const {fullPath} = entry; + + if (wh.followSymlinks && entry.stats.isSymbolicLink()) { + // preserve the current depth here since it can't be derived from + // real paths past the symlink + const curDepth = opts.depth === undefined ? + undefined : calcDepth(joinedPath, sysPath.resolve(wh.watchPath)) + 1; + + this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth); + } else { + this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd); + } + }).on(EV_ERROR, EMPTY_FN).on(STR_END, () => { + this.fsw._emitReady(); + }); + } else { + this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd); + this.fsw._emitReady(); + } + } catch (error) { + if (!error || this.fsw._handleError(error)) { + // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__- + this.fsw._emitReady(); + this.fsw._emitReady(); + } + } + + if (opts.persistent && forceAdd !== true) { + if (typeof transform === FUNCTION_TYPE) { + // realpath has already been resolved + this.initWatch(undefined, path, wh, processPath); + } else { + let realPath; + try { + realPath = await realpath(wh.watchPath); + } catch (e) {} + this.initWatch(realPath, path, wh, processPath); + } + } +} + +} + +module.exports = FsEventsHandler; +module.exports.canUse = canUse; diff --git a/node_modules/chokidar/lib/nodefs-handler.js b/node_modules/chokidar/lib/nodefs-handler.js new file mode 100644 index 000000000..199cfe9f9 --- /dev/null +++ b/node_modules/chokidar/lib/nodefs-handler.js @@ -0,0 +1,654 @@ +'use strict'; + +const fs = require('fs'); +const sysPath = require('path'); +const { promisify } = require('util'); +const isBinaryPath = require('is-binary-path'); +const { + isWindows, + isLinux, + EMPTY_FN, + EMPTY_STR, + KEY_LISTENERS, + KEY_ERR, + KEY_RAW, + HANDLER_KEYS, + EV_CHANGE, + EV_ADD, + EV_ADD_DIR, + EV_ERROR, + STR_DATA, + STR_END, + BRACE_START, + STAR +} = require('./constants'); + +const THROTTLE_MODE_WATCH = 'watch'; + +const open = promisify(fs.open); +const stat = promisify(fs.stat); +const lstat = promisify(fs.lstat); +const close = promisify(fs.close); +const fsrealpath = promisify(fs.realpath); + +const statMethods = { lstat, stat }; + +// TODO: emit errors properly. Example: EMFILE on Macos. +const foreach = (val, fn) => { + if (val instanceof Set) { + val.forEach(fn); + } else { + fn(val); + } +}; + +const addAndConvert = (main, prop, item) => { + let container = main[prop]; + if (!(container instanceof Set)) { + main[prop] = container = new Set([container]); + } + container.add(item); +}; + +const clearItem = cont => key => { + const set = cont[key]; + if (set instanceof Set) { + set.clear(); + } else { + delete cont[key]; + } +}; + +const delFromSet = (main, prop, item) => { + const container = main[prop]; + if (container instanceof Set) { + container.delete(item); + } else if (container === item) { + delete main[prop]; + } +}; + +const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val; + +/** + * @typedef {String} Path + */ + +// fs_watch helpers + +// object to hold per-process fs_watch instances +// (may be shared across chokidar FSWatcher instances) + +/** + * @typedef {Object} FsWatchContainer + * @property {Set} listeners + * @property {Set} errHandlers + * @property {Set} rawEmitters + * @property {fs.FSWatcher=} watcher + * @property {Boolean=} watcherUnusable + */ + +/** + * @type {Map} + */ +const FsWatchInstances = new Map(); + +/** + * Instantiates the fs_watch interface + * @param {String} path to be watched + * @param {Object} options to be passed to fs_watch + * @param {Function} listener main event handler + * @param {Function} errHandler emits info about errors + * @param {Function} emitRaw emits raw event data + * @returns {fs.FSWatcher} new fsevents instance + */ +function createFsWatchInstance(path, options, listener, errHandler, emitRaw) { + const handleEvent = (rawEvent, evPath) => { + listener(path); + emitRaw(rawEvent, evPath, {watchedPath: path}); + + // emit based on events occurring for files from a directory's watcher in + // case the file's watcher misses it (and rely on throttling to de-dupe) + if (evPath && path !== evPath) { + fsWatchBroadcast( + sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath) + ); + } + }; + try { + return fs.watch(path, options, handleEvent); + } catch (error) { + errHandler(error); + } +} + +/** + * Helper for passing fs_watch event data to a collection of listeners + * @param {Path} fullPath absolute path bound to fs_watch instance + * @param {String} type listener type + * @param {*=} val1 arguments to be passed to listeners + * @param {*=} val2 + * @param {*=} val3 + */ +const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => { + const cont = FsWatchInstances.get(fullPath); + if (!cont) return; + foreach(cont[type], (listener) => { + listener(val1, val2, val3); + }); +}; + +/** + * Instantiates the fs_watch interface or binds listeners + * to an existing one covering the same file system entry + * @param {String} path + * @param {String} fullPath absolute path + * @param {Object} options to be passed to fs_watch + * @param {Object} handlers container for event listener functions + */ +const setFsWatchListener = (path, fullPath, options, handlers) => { + const {listener, errHandler, rawEmitter} = handlers; + let cont = FsWatchInstances.get(fullPath); + + /** @type {fs.FSWatcher=} */ + let watcher; + if (!options.persistent) { + watcher = createFsWatchInstance( + path, options, listener, errHandler, rawEmitter + ); + return watcher.close.bind(watcher); + } + if (cont) { + addAndConvert(cont, KEY_LISTENERS, listener); + addAndConvert(cont, KEY_ERR, errHandler); + addAndConvert(cont, KEY_RAW, rawEmitter); + } else { + watcher = createFsWatchInstance( + path, + options, + fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), + errHandler, // no need to use broadcast here + fsWatchBroadcast.bind(null, fullPath, KEY_RAW) + ); + if (!watcher) return; + watcher.on(EV_ERROR, async (error) => { + const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR); + cont.watcherUnusable = true; // documented since Node 10.4.1 + // Workaround for https://github.com/joyent/node/issues/4337 + if (isWindows && error.code === 'EPERM') { + try { + const fd = await open(path, 'r'); + await close(fd); + broadcastErr(error); + } catch (err) {} + } else { + broadcastErr(error); + } + }); + cont = { + listeners: listener, + errHandlers: errHandler, + rawEmitters: rawEmitter, + watcher + }; + FsWatchInstances.set(fullPath, cont); + } + // const index = cont.listeners.indexOf(listener); + + // removes this instance's listeners and closes the underlying fs_watch + // instance if there are no more listeners left + return () => { + delFromSet(cont, KEY_LISTENERS, listener); + delFromSet(cont, KEY_ERR, errHandler); + delFromSet(cont, KEY_RAW, rawEmitter); + if (isEmptySet(cont.listeners)) { + // Check to protect against issue gh-730. + // if (cont.watcherUnusable) { + cont.watcher.close(); + // } + FsWatchInstances.delete(fullPath); + HANDLER_KEYS.forEach(clearItem(cont)); + cont.watcher = undefined; + Object.freeze(cont); + } + }; +}; + +// fs_watchFile helpers + +// object to hold per-process fs_watchFile instances +// (may be shared across chokidar FSWatcher instances) +const FsWatchFileInstances = new Map(); + +/** + * Instantiates the fs_watchFile interface or binds listeners + * to an existing one covering the same file system entry + * @param {String} path to be watched + * @param {String} fullPath absolute path + * @param {Object} options options to be passed to fs_watchFile + * @param {Object} handlers container for event listener functions + * @returns {Function} closer + */ +const setFsWatchFileListener = (path, fullPath, options, handlers) => { + const {listener, rawEmitter} = handlers; + let cont = FsWatchFileInstances.get(fullPath); + + /* eslint-disable no-unused-vars, prefer-destructuring */ + let listeners = new Set(); + let rawEmitters = new Set(); + + const copts = cont && cont.options; + if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) { + // "Upgrade" the watcher to persistence or a quicker interval. + // This creates some unlikely edge case issues if the user mixes + // settings in a very weird way, but solving for those cases + // doesn't seem worthwhile for the added complexity. + listeners = cont.listeners; + rawEmitters = cont.rawEmitters; + fs.unwatchFile(fullPath); + cont = undefined; + } + + /* eslint-enable no-unused-vars, prefer-destructuring */ + + if (cont) { + addAndConvert(cont, KEY_LISTENERS, listener); + addAndConvert(cont, KEY_RAW, rawEmitter); + } else { + // TODO + // listeners.add(listener); + // rawEmitters.add(rawEmitter); + cont = { + listeners: listener, + rawEmitters: rawEmitter, + options, + watcher: fs.watchFile(fullPath, options, (curr, prev) => { + foreach(cont.rawEmitters, (rawEmitter) => { + rawEmitter(EV_CHANGE, fullPath, {curr, prev}); + }); + const currmtime = curr.mtimeMs; + if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) { + foreach(cont.listeners, (listener) => listener(path, curr)); + } + }) + }; + FsWatchFileInstances.set(fullPath, cont); + } + // const index = cont.listeners.indexOf(listener); + + // Removes this instance's listeners and closes the underlying fs_watchFile + // instance if there are no more listeners left. + return () => { + delFromSet(cont, KEY_LISTENERS, listener); + delFromSet(cont, KEY_RAW, rawEmitter); + if (isEmptySet(cont.listeners)) { + FsWatchFileInstances.delete(fullPath); + fs.unwatchFile(fullPath); + cont.options = cont.watcher = undefined; + Object.freeze(cont); + } + }; +}; + +/** + * @mixin + */ +class NodeFsHandler { + +/** + * @param {import("../index").FSWatcher} fsW + */ +constructor(fsW) { + this.fsw = fsW; + this._boundHandleError = (error) => fsW._handleError(error); +} + +/** + * Watch file for changes with fs_watchFile or fs_watch. + * @param {String} path to file or dir + * @param {Function} listener on fs change + * @returns {Function} closer for the watcher instance + */ +_watchWithNodeFs(path, listener) { + const opts = this.fsw.options; + const directory = sysPath.dirname(path); + const basename = sysPath.basename(path); + const parent = this.fsw._getWatchedDir(directory); + parent.add(basename); + const absolutePath = sysPath.resolve(path); + const options = {persistent: opts.persistent}; + if (!listener) listener = EMPTY_FN; + + let closer; + if (opts.usePolling) { + options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ? + opts.binaryInterval : opts.interval; + closer = setFsWatchFileListener(path, absolutePath, options, { + listener, + rawEmitter: this.fsw._emitRaw + }); + } else { + closer = setFsWatchListener(path, absolutePath, options, { + listener, + errHandler: this._boundHandleError, + rawEmitter: this.fsw._emitRaw + }); + } + return closer; +} + +/** + * Watch a file and emit add event if warranted. + * @param {Path} file Path + * @param {fs.Stats} stats result of fs_stat + * @param {Boolean} initialAdd was the file added at watch instantiation? + * @returns {Function} closer for the watcher instance + */ +_handleFile(file, stats, initialAdd) { + if (this.fsw.closed) { + return; + } + const dirname = sysPath.dirname(file); + const basename = sysPath.basename(file); + const parent = this.fsw._getWatchedDir(dirname); + // stats is always present + let prevStats = stats; + + // if the file is already being watched, do nothing + if (parent.has(basename)) return; + + const listener = async (path, newStats) => { + if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return; + if (!newStats || newStats.mtimeMs === 0) { + try { + const newStats = await stat(file); + if (this.fsw.closed) return; + // Check that change event was not fired because of changed only accessTime. + const at = newStats.atimeMs; + const mt = newStats.mtimeMs; + if (!at || at <= mt || mt !== prevStats.mtimeMs) { + this.fsw._emit(EV_CHANGE, file, newStats); + } + if (isLinux && prevStats.ino !== newStats.ino) { + this.fsw._closeFile(path) + prevStats = newStats; + this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener)); + } else { + prevStats = newStats; + } + } catch (error) { + // Fix issues where mtime is null but file is still present + this.fsw._remove(dirname, basename); + } + // add is about to be emitted if file not already tracked in parent + } else if (parent.has(basename)) { + // Check that change event was not fired because of changed only accessTime. + const at = newStats.atimeMs; + const mt = newStats.mtimeMs; + if (!at || at <= mt || mt !== prevStats.mtimeMs) { + this.fsw._emit(EV_CHANGE, file, newStats); + } + prevStats = newStats; + } + } + // kick off the watcher + const closer = this._watchWithNodeFs(file, listener); + + // emit an add event if we're supposed to + if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) { + if (!this.fsw._throttle(EV_ADD, file, 0)) return; + this.fsw._emit(EV_ADD, file, stats); + } + + return closer; +} + +/** + * Handle symlinks encountered while reading a dir. + * @param {Object} entry returned by readdirp + * @param {String} directory path of dir being read + * @param {String} path of this item + * @param {String} item basename of this item + * @returns {Promise} true if no more processing is needed for this entry. + */ +async _handleSymlink(entry, directory, path, item) { + if (this.fsw.closed) { + return; + } + const full = entry.fullPath; + const dir = this.fsw._getWatchedDir(directory); + + if (!this.fsw.options.followSymlinks) { + // watch symlink directly (don't follow) and detect changes + this.fsw._incrReadyCount(); + + let linkPath; + try { + linkPath = await fsrealpath(path); + } catch (e) { + this.fsw._emitReady(); + return true; + } + + if (this.fsw.closed) return; + if (dir.has(item)) { + if (this.fsw._symlinkPaths.get(full) !== linkPath) { + this.fsw._symlinkPaths.set(full, linkPath); + this.fsw._emit(EV_CHANGE, path, entry.stats); + } + } else { + dir.add(item); + this.fsw._symlinkPaths.set(full, linkPath); + this.fsw._emit(EV_ADD, path, entry.stats); + } + this.fsw._emitReady(); + return true; + } + + // don't follow the same symlink more than once + if (this.fsw._symlinkPaths.has(full)) { + return true; + } + + this.fsw._symlinkPaths.set(full, true); +} + +_handleRead(directory, initialAdd, wh, target, dir, depth, throttler) { + // Normalize the directory name on Windows + directory = sysPath.join(directory, EMPTY_STR); + + if (!wh.hasGlob) { + throttler = this.fsw._throttle('readdir', directory, 1000); + if (!throttler) return; + } + + const previous = this.fsw._getWatchedDir(wh.path); + const current = new Set(); + + let stream = this.fsw._readdirp(directory, { + fileFilter: entry => wh.filterPath(entry), + directoryFilter: entry => wh.filterDir(entry), + depth: 0 + }).on(STR_DATA, async (entry) => { + if (this.fsw.closed) { + stream = undefined; + return; + } + const item = entry.path; + let path = sysPath.join(directory, item); + current.add(item); + + if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) { + return; + } + + if (this.fsw.closed) { + stream = undefined; + return; + } + // Files that present in current directory snapshot + // but absent in previous are added to watch list and + // emit `add` event. + if (item === target || !target && !previous.has(item)) { + this.fsw._incrReadyCount(); + + // ensure relativeness of path is preserved in case of watcher reuse + path = sysPath.join(dir, sysPath.relative(dir, path)); + + this._addToNodeFs(path, initialAdd, wh, depth + 1); + } + }).on(EV_ERROR, this._boundHandleError); + + return new Promise(resolve => + stream.once(STR_END, () => { + if (this.fsw.closed) { + stream = undefined; + return; + } + const wasThrottled = throttler ? throttler.clear() : false; + + resolve(); + + // Files that absent in current directory snapshot + // but present in previous emit `remove` event + // and are removed from @watched[directory]. + previous.getChildren().filter((item) => { + return item !== directory && + !current.has(item) && + // in case of intersecting globs; + // a path may have been filtered out of this readdir, but + // shouldn't be removed because it matches a different glob + (!wh.hasGlob || wh.filterPath({ + fullPath: sysPath.resolve(directory, item) + })); + }).forEach((item) => { + this.fsw._remove(directory, item); + }); + + stream = undefined; + + // one more time for any missed in case changes came in extremely quickly + if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler); + }) + ); +} + +/** + * Read directory to add / remove files from `@watched` list and re-read it on change. + * @param {String} dir fs path + * @param {fs.Stats} stats + * @param {Boolean} initialAdd + * @param {Number} depth relative to user-supplied path + * @param {String} target child path targeted for watch + * @param {Object} wh Common watch helpers for this path + * @param {String} realpath + * @returns {Promise} closer for the watcher instance. + */ +async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) { + const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir)); + const tracked = parentDir.has(sysPath.basename(dir)); + if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) { + if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR, dir, stats); + } + + // ensure dir is tracked (harmless if redundant) + parentDir.add(sysPath.basename(dir)); + this.fsw._getWatchedDir(dir); + let throttler; + let closer; + + const oDepth = this.fsw.options.depth; + if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) { + if (!target) { + await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler); + if (this.fsw.closed) return; + } + + closer = this._watchWithNodeFs(dir, (dirPath, stats) => { + // if current directory is removed, do nothing + if (stats && stats.mtimeMs === 0) return; + + this._handleRead(dirPath, false, wh, target, dir, depth, throttler); + }); + } + return closer; +} + +/** + * Handle added file, directory, or glob pattern. + * Delegates call to _handleFile / _handleDir after checks. + * @param {String} path to file or ir + * @param {Boolean} initialAdd was the file added at watch instantiation? + * @param {Object} priorWh depth relative to user-supplied path + * @param {Number} depth Child path actually targeted for watch + * @param {String=} target Child path actually targeted for watch + * @returns {Promise} + */ +async _addToNodeFs(path, initialAdd, priorWh, depth, target) { + const ready = this.fsw._emitReady; + if (this.fsw._isIgnored(path) || this.fsw.closed) { + ready(); + return false; + } + + const wh = this.fsw._getWatchHelpers(path, depth); + if (!wh.hasGlob && priorWh) { + wh.hasGlob = priorWh.hasGlob; + wh.globFilter = priorWh.globFilter; + wh.filterPath = entry => priorWh.filterPath(entry); + wh.filterDir = entry => priorWh.filterDir(entry); + } + + // evaluate what is at the path we're being asked to watch + try { + const stats = await statMethods[wh.statMethod](wh.watchPath); + if (this.fsw.closed) return; + if (this.fsw._isIgnored(wh.watchPath, stats)) { + ready(); + return false; + } + + const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START); + let closer; + if (stats.isDirectory()) { + const absPath = sysPath.resolve(path); + const targetPath = follow ? await fsrealpath(path) : path; + if (this.fsw.closed) return; + closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath); + if (this.fsw.closed) return; + // preserve this symlink's target path + if (absPath !== targetPath && targetPath !== undefined) { + this.fsw._symlinkPaths.set(absPath, targetPath); + } + } else if (stats.isSymbolicLink()) { + const targetPath = follow ? await fsrealpath(path) : path; + if (this.fsw.closed) return; + const parent = sysPath.dirname(wh.watchPath); + this.fsw._getWatchedDir(parent).add(wh.watchPath); + this.fsw._emit(EV_ADD, wh.watchPath, stats); + closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath); + if (this.fsw.closed) return; + + // preserve this symlink's target path + if (targetPath !== undefined) { + this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath); + } + } else { + closer = this._handleFile(wh.watchPath, stats, initialAdd); + } + ready(); + + this.fsw._addPathCloser(path, closer); + return false; + + } catch (error) { + if (this.fsw._handleError(error)) { + ready(); + return path; + } + } +} + +} + +module.exports = NodeFsHandler; diff --git a/node_modules/chokidar/package.json b/node_modules/chokidar/package.json new file mode 100644 index 000000000..e8f8b3d99 --- /dev/null +++ b/node_modules/chokidar/package.json @@ -0,0 +1,70 @@ +{ + "name": "chokidar", + "description": "Minimal and efficient cross-platform file watching library", + "version": "3.6.0", + "homepage": "https://github.com/paulmillr/chokidar", + "author": "Paul Miller (https://paulmillr.com)", + "contributors": [ + "Paul Miller (https://paulmillr.com)", + "Elan Shanker" + ], + "engines": { + "node": ">= 8.10.0" + }, + "main": "index.js", + "types": "./types/index.d.ts", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + }, + "devDependencies": { + "@types/node": "^14", + "chai": "^4.3", + "dtslint": "^3.3.0", + "eslint": "^7.0.0", + "mocha": "^7.0.0", + "rimraf": "^3.0.0", + "sinon": "^9.0.1", + "sinon-chai": "^3.3.0", + "typescript": "^4.4.3", + "upath": "^1.2.0" + }, + "files": [ + "index.js", + "lib/*.js", + "types/index.d.ts" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/paulmillr/chokidar.git" + }, + "bugs": { + "url": "https://github.com/paulmillr/chokidar/issues" + }, + "license": "MIT", + "scripts": { + "dtslint": "dtslint types", + "lint": "eslint --report-unused-disable-directives --ignore-path .gitignore .", + "build": "npm ls", + "mocha": "mocha --exit --timeout 90000", + "test": "npm run lint && npm run mocha" + }, + "keywords": [ + "fs", + "watch", + "watchFile", + "watcher", + "watching", + "file", + "fsevents" + ], + "funding": "https://paulmillr.com/funding/" +} diff --git a/node_modules/chokidar/types/index.d.ts b/node_modules/chokidar/types/index.d.ts new file mode 100644 index 000000000..455806638 --- /dev/null +++ b/node_modules/chokidar/types/index.d.ts @@ -0,0 +1,192 @@ +// TypeScript Version: 3.0 + +/// + +import * as fs from "fs"; +import { EventEmitter } from "events"; +import { Matcher } from 'anymatch'; + +export class FSWatcher extends EventEmitter implements fs.FSWatcher { + options: WatchOptions; + + /** + * Constructs a new FSWatcher instance with optional WatchOptions parameter. + */ + constructor(options?: WatchOptions); + + /** + * Add files, directories, or glob patterns for tracking. Takes an array of strings or just one + * string. + */ + add(paths: string | ReadonlyArray): this; + + /** + * Stop watching files, directories, or glob patterns. Takes an array of strings or just one + * string. + */ + unwatch(paths: string | ReadonlyArray): this; + + /** + * Returns an object representing all the paths on the file system being watched by this + * `FSWatcher` instance. The object's keys are all the directories (using absolute paths unless + * the `cwd` option was used), and the values are arrays of the names of the items contained in + * each directory. + */ + getWatched(): { + [directory: string]: string[]; + }; + + /** + * Removes all listeners from watched files. + */ + close(): Promise; + + on(event: 'add'|'addDir'|'change', listener: (path: string, stats?: fs.Stats) => void): this; + + on(event: 'all', listener: (eventName: 'add'|'addDir'|'change'|'unlink'|'unlinkDir', path: string, stats?: fs.Stats) => void): this; + + /** + * Error occurred + */ + on(event: 'error', listener: (error: Error) => void): this; + + /** + * Exposes the native Node `fs.FSWatcher events` + */ + on(event: 'raw', listener: (eventName: string, path: string, details: any) => void): this; + + /** + * Fires when the initial scan is complete + */ + on(event: 'ready', listener: () => void): this; + + on(event: 'unlink'|'unlinkDir', listener: (path: string) => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + + ref(): this; + + unref(): this; +} + +export interface WatchOptions { + /** + * Indicates whether the process should continue to run as long as files are being watched. If + * set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`, + * even if the process continues to run. + */ + persistent?: boolean; + + /** + * ([anymatch](https://github.com/micromatch/anymatch)-compatible definition) Defines files/paths to + * be ignored. The whole relative or absolute path is tested, not just filename. If a function + * with two arguments is provided, it gets called twice per path - once with a single argument + * (the path), second time with two arguments (the path and the + * [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object of that path). + */ + ignored?: Matcher; + + /** + * If set to `false` then `add`/`addDir` events are also emitted for matching paths while + * instantiating the watching as chokidar discovers these file paths (before the `ready` event). + */ + ignoreInitial?: boolean; + + /** + * When `false`, only the symlinks themselves will be watched for changes instead of following + * the link references and bubbling events through the link's path. + */ + followSymlinks?: boolean; + + /** + * The base directory from which watch `paths` are to be derived. Paths emitted with events will + * be relative to this. + */ + cwd?: string; + + /** + * If set to true then the strings passed to .watch() and .add() are treated as literal path + * names, even if they look like globs. Default: false. + */ + disableGlobbing?: boolean; + + /** + * Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU + * utilization, consider setting this to `false`. It is typically necessary to **set this to + * `true` to successfully watch files over a network**, and it may be necessary to successfully + * watch files in other non-standard situations. Setting to `true` explicitly on OS X overrides + * the `useFsEvents` default. + */ + usePolling?: boolean; + + /** + * Whether to use the `fsevents` watching interface if available. When set to `true` explicitly + * and `fsevents` is available this supercedes the `usePolling` setting. When set to `false` on + * OS X, `usePolling: true` becomes the default. + */ + useFsEvents?: boolean; + + /** + * If relying upon the [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object that + * may get passed with `add`, `addDir`, and `change` events, set this to `true` to ensure it is + * provided even in cases where it wasn't already available from the underlying watch events. + */ + alwaysStat?: boolean; + + /** + * If set, limits how many levels of subdirectories will be traversed. + */ + depth?: number; + + /** + * Interval of file system polling. + */ + interval?: number; + + /** + * Interval of file system polling for binary files. ([see list of binary extensions](https://gi + * thub.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json)) + */ + binaryInterval?: number; + + /** + * Indicates whether to watch files that don't have read permissions if possible. If watching + * fails due to `EPERM` or `EACCES` with this set to `true`, the errors will be suppressed + * silently. + */ + ignorePermissionErrors?: boolean; + + /** + * `true` if `useFsEvents` and `usePolling` are `false`). Automatically filters out artifacts + * that occur when using editors that use "atomic writes" instead of writing directly to the + * source file. If a file is re-added within 100 ms of being deleted, Chokidar emits a `change` + * event rather than `unlink` then `add`. If the default of 100 ms does not work well for you, + * you can override it by setting `atomic` to a custom value, in milliseconds. + */ + atomic?: boolean | number; + + /** + * can be set to an object in order to adjust timing params: + */ + awaitWriteFinish?: AwaitWriteFinishOptions | boolean; +} + +export interface AwaitWriteFinishOptions { + /** + * Amount of time in milliseconds for a file size to remain constant before emitting its event. + */ + stabilityThreshold?: number; + + /** + * File size polling interval. + */ + pollInterval?: number; +} + +/** + * produces an instance of `FSWatcher`. + */ +export function watch( + paths: string | ReadonlyArray, + options?: WatchOptions +): FSWatcher; diff --git a/node_modules/commander/CHANGELOG.md b/node_modules/commander/CHANGELOG.md new file mode 100644 index 000000000..f00cb2b53 --- /dev/null +++ b/node_modules/commander/CHANGELOG.md @@ -0,0 +1,436 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). (Format adopted after v3.0.0.) + + + +## [4.1.1] (2020-02-02) + +### Fixed + +* TypeScript definition for `.action()` should include Promise for async ([#1157]) + +## [4.1.0] (2020-01-06) + +### Added + +* two routines to change how option values are handled, and eliminate name clashes with command properties ([#933] [#1102]) + * see storeOptionsAsProperties and passCommandToAction in README +* `.parseAsync` to use instead of `.parse` if supply async action handlers ([#806] [#1118]) + +### Fixed + +* Remove trailing blanks from wrapped help text ([#1096]) + +### Changed + +* update dependencies +* extend security coverage for Commander 2.x to 2020-02-03 +* improvements to README +* improvements to TypeScript definition documentation +* move old versions out of main CHANGELOG +* removed explicit use of `ts-node` in tests + +## [4.0.1] (2019-11-12) + +### Fixed + +* display help when requested, even if there are missing required options ([#1091]) + +## [4.0.0] (2019-11-02) + +### Added + +* automatically wrap and indent help descriptions for options and commands ([#1051]) +* `.exitOverride()` allows override of calls to `process.exit` for additional error handling and to keep program running ([#1040]) +* support for declaring required options with `.requiredOptions()` ([#1071]) +* GitHub Actions support ([#1027]) +* translation links in README + +### Changed + +* dev: switch tests from Sinon+Should to Jest with major rewrite of tests ([#1035]) +* call default subcommand even when there are unknown options ([#1047]) +* *Breaking* Commander is only officially supported on Node 8 and above, and requires Node 6 ([#1053]) + +### Fixed + +* *Breaking* keep command object out of program.args when action handler called ([#1048]) + * also, action handler now passed array of unknown arguments +* complain about unknown options when program argument supplied and action handler ([#1049]) + * this changes parameters to `command:*` event to include unknown arguments +* removed deprecated `customFds` option from call to `child_process.spawn` ([#1052]) +* rework TypeScript declarations to bring all types into imported namespace ([#1081]) + +### Migration Tips + +#### Testing for no arguments + +If you were previously using code like: + +```js +if (!program.args.length) ... +``` + +a partial replacement is: + +```js +if (program.rawArgs.length < 3) ... +``` + +## [4.0.0-1] Prerelease (2019-10-08) + +(Released in 4.0.0) + +## [4.0.0-0] Prerelease (2019-10-01) + +(Released in 4.0.0) + +## [2.20.1] (2019-09-29) + +### Fixed + +* Improve tracking of executable subcommands. + +### Changed + +* update development dependencies + +## [3.0.2] (2019-09-27) + +### Fixed + +* Improve tracking of executable subcommands. + +### Changed + +* update development dependencies + +## [3.0.1] (2019-08-30) + +### Added + +* .name and .usage to README ([#1010]) +* Table of Contents to README ([#1010]) +* TypeScript definition for `executableFile` in CommandOptions ([#1028]) + +### Changed + +* consistently use `const` rather than `var` in README ([#1026]) + +### Fixed + +* help for sub commands with custom executableFile ([#1018]) + +## [3.0.0] / 2019-08-08 + +* Add option to specify executable file name ([#999]) + * e.g. `.command('clone', 'clone description', { executableFile: 'myClone' })` +* Change docs for `.command` to contrast action handler vs git-style executable. ([#938] [#990]) +* **Breaking** Change TypeScript to use overloaded function for `.command`. ([#938] [#990]) +* Change to use straight quotes around strings in error messages (like 'this' instead of `this') ([#915]) +* Add TypeScript "reference types" for node ([#974]) +* Add support for hyphen as an option argument in subcommands ([#697]) +* Add support for a short option flag and its value to be concatenated for action handler subcommands ([#599]) + * e.g. `-p 80` can also be supplied as `-p80` +* Add executable arguments to spawn in win32, for git-style executables ([#611]) + * e.g. `node --harmony myCommand.js clone` +* Add parent command as prefix of subcommand in help ([#980]) +* Add optional custom description to `.version` ([#963]) + * e.g. `program.version('0.0.1', '-v, --vers', 'output the current version')` +* Add `.helpOption(flags, description)` routine to customise help flags and description ([#963]) + * e.g. `.helpOption('-e, --HELP', 'read more information')` +* Fix behavior of --no-* options ([#795]) + * can now define both `--foo` and `--no-foo` + * **Breaking** custom event listeners: `--no-foo` on cli now emits `option:no-foo` (previously `option:foo`) + * **Breaking** default value: defining `--no-foo` after defining `--foo` leaves the default value unchanged (previously set it to false) + * allow boolean default value, such as from environment ([#987]) +* Increment inspector port for spawned subcommands ([#991]) + * e.g. `node --inspect myCommand.js clone` + +### Migration Tips + +The custom event for a negated option like `--no-foo` is `option:no-foo` (previously `option:foo`). + +```js +program + .option('--no-foo') + .on('option:no-foo', () => { + console.log('removing foo'); + }); +``` + +When using TypeScript, adding a command does not allow an explicit `undefined` for an unwanted executable description (e.g +for a command with an action handler). + +```js +program + .command('action1', undefined, { noHelp: true }) // No longer valid + .command('action2', { noHelp: true }) // Correct +``` + +## 3.0.0-0 Prerelease / 2019-07-28 + +(Released as 3.0.0) + +## 2.20.0 / 2019-04-02 + +* fix: resolve symbolic links completely when hunting for subcommands (#935) +* Update index.d.ts (#930) +* Update Readme.md (#924) +* Remove --save option as it isn't required anymore (#918) +* Add link to the license file (#900) +* Added example of receiving args from options (#858) +* Added missing semicolon (#882) +* Add extension to .eslintrc (#876) + +## 2.19.0 / 2018-10-02 + +* Removed newline after Options and Commands headers (#864) +* Bugfix - Error output (#862) +* Fix to change default value to string (#856) + +## 2.18.0 / 2018-09-07 + +* Standardize help output (#853) +* chmod 644 travis.yml (#851) +* add support for execute typescript subcommand via ts-node (#849) + +## 2.17.1 / 2018-08-07 + +* Fix bug in command emit (#844) + +## 2.17.0 / 2018-08-03 + +* fixed newline output after help information (#833) +* Fix to emit the action even without command (#778) +* npm update (#823) + +## 2.16.0 / 2018-06-29 + +* Remove Makefile and `test/run` (#821) +* Make 'npm test' run on Windows (#820) +* Add badge to display install size (#807) +* chore: cache node_modules (#814) +* chore: remove Node.js 4 (EOL), add Node.js 10 (#813) +* fixed typo in readme (#812) +* Fix types (#804) +* Update eslint to resolve vulnerabilities in lodash (#799) +* updated readme with custom event listeners. (#791) +* fix tests (#794) + +## 2.15.0 / 2018-03-07 + +* Update downloads badge to point to graph of downloads over time instead of duplicating link to npm +* Arguments description + +## 2.14.1 / 2018-02-07 + +* Fix typing of help function + +## 2.14.0 / 2018-02-05 + +* only register the option:version event once +* Fixes issue #727: Passing empty string for option on command is set to undefined +* enable eqeqeq rule +* resolves #754 add linter configuration to project +* resolves #560 respect custom name for version option +* document how to override the version flag +* document using options per command + +## 2.13.0 / 2018-01-09 + +* Do not print default for --no- +* remove trailing spaces in command help +* Update CI's Node.js to LTS and latest version +* typedefs: Command and Option types added to commander namespace + +## 2.12.2 / 2017-11-28 + +* fix: typings are not shipped + +## 2.12.1 / 2017-11-23 + +* Move @types/node to dev dependency + +## 2.12.0 / 2017-11-22 + +* add attributeName() method to Option objects +* Documentation updated for options with --no prefix +* typings: `outputHelp` takes a string as the first parameter +* typings: use overloads +* feat(typings): update to match js api +* Print default value in option help +* Fix translation error +* Fail when using same command and alias (#491) +* feat(typings): add help callback +* fix bug when description is add after command with options (#662) +* Format js code +* Rename History.md to CHANGELOG.md (#668) +* feat(typings): add typings to support TypeScript (#646) +* use current node + +## 2.11.0 / 2017-07-03 + +* Fix help section order and padding (#652) +* feature: support for signals to subcommands (#632) +* Fixed #37, --help should not display first (#447) +* Fix translation errors. (#570) +* Add package-lock.json +* Remove engines +* Upgrade package version +* Prefix events to prevent conflicts between commands and options (#494) +* Removing dependency on graceful-readlink +* Support setting name in #name function and make it chainable +* Add .vscode directory to .gitignore (Visual Studio Code metadata) +* Updated link to ruby commander in readme files + +## 2.10.0 / 2017-06-19 + +* Update .travis.yml. drop support for older node.js versions. +* Fix require arguments in README.md +* On SemVer you do not start from 0.0.1 +* Add missing semi colon in readme +* Add save param to npm install +* node v6 travis test +* Update Readme_zh-CN.md +* Allow literal '--' to be passed-through as an argument +* Test subcommand alias help +* link build badge to master branch +* Support the alias of Git style sub-command +* added keyword commander for better search result on npm +* Fix Sub-Subcommands +* test node.js stable +* Fixes TypeError when a command has an option called `--description` +* Update README.md to make it beginner friendly and elaborate on the difference between angled and square brackets. +* Add chinese Readme file + +## 2.9.0 / 2015-10-13 + +* Add option `isDefault` to set default subcommand #415 @Qix- +* Add callback to allow filtering or post-processing of help text #434 @djulien +* Fix `undefined` text in help information close #414 #416 @zhiyelee + +## 2.8.1 / 2015-04-22 + +* Back out `support multiline description` Close #396 #397 + +## 2.8.0 / 2015-04-07 + +* Add `process.execArg` support, execution args like `--harmony` will be passed to sub-commands #387 @DigitalIO @zhiyelee +* Fix bug in Git-style sub-commands #372 @zhiyelee +* Allow commands to be hidden from help #383 @tonylukasavage +* When git-style sub-commands are in use, yet none are called, display help #382 @claylo +* Add ability to specify arguments syntax for top-level command #258 @rrthomas +* Support multiline descriptions #208 @zxqfox + +## 2.7.1 / 2015-03-11 + +* Revert #347 (fix collisions when option and first arg have same name) which causes a bug in #367. + +## 2.7.0 / 2015-03-09 + +* Fix git-style bug when installed globally. Close #335 #349 @zhiyelee +* Fix collisions when option and first arg have same name. Close #346 #347 @tonylukasavage +* Add support for camelCase on `opts()`. Close #353 @nkzawa +* Add node.js 0.12 and io.js to travis.yml +* Allow RegEx options. #337 @palanik +* Fixes exit code when sub-command failing. Close #260 #332 @pirelenito +* git-style `bin` files in $PATH make sense. Close #196 #327 @zhiyelee + +## 2.6.0 / 2014-12-30 + +* added `Command#allowUnknownOption` method. Close #138 #318 @doozr @zhiyelee +* Add application description to the help msg. Close #112 @dalssoft + +## 2.5.1 / 2014-12-15 + +* fixed two bugs incurred by variadic arguments. Close #291 @Quentin01 #302 @zhiyelee + +## 2.5.0 / 2014-10-24 + +* add support for variadic arguments. Closes #277 @whitlockjc + +## 2.4.0 / 2014-10-17 + +* fixed a bug on executing the coercion function of subcommands option. Closes #270 +* added `Command.prototype.name` to retrieve command name. Closes #264 #266 @tonylukasavage +* added `Command.prototype.opts` to retrieve all the options as a simple object of key-value pairs. Closes #262 @tonylukasavage +* fixed a bug on subcommand name. Closes #248 @jonathandelgado +* fixed function normalize doesn’t honor option terminator. Closes #216 @abbr + +## 2.3.0 / 2014-07-16 + +* add command alias'. Closes PR #210 +* fix: Typos. Closes #99 +* fix: Unused fs module. Closes #217 + +## 2.2.0 / 2014-03-29 + +* add passing of previous option value +* fix: support subcommands on windows. Closes #142 +* Now the defaultValue passed as the second argument of the coercion function. + +## 2.1.0 / 2013-11-21 + +* add: allow cflag style option params, unit test, fixes #174 + +## 2.0.0 / 2013-07-18 + +* remove input methods (.prompt, .confirm, etc) + +## Older versions + +* [1.x](./changelogs/CHANGELOG-1.md) +* [0.x](./changelogs/CHANGELOG-0.md) + +[#599]: https://github.com/tj/commander.js/issues/599 +[#611]: https://github.com/tj/commander.js/issues/611 +[#697]: https://github.com/tj/commander.js/issues/697 +[#795]: https://github.com/tj/commander.js/issues/795 +[#806]: https://github.com/tj/commander.js/issues/806 +[#915]: https://github.com/tj/commander.js/issues/915 +[#938]: https://github.com/tj/commander.js/issues/938 +[#963]: https://github.com/tj/commander.js/issues/963 +[#974]: https://github.com/tj/commander.js/issues/974 +[#980]: https://github.com/tj/commander.js/issues/980 +[#987]: https://github.com/tj/commander.js/issues/987 +[#990]: https://github.com/tj/commander.js/issues/990 +[#991]: https://github.com/tj/commander.js/issues/991 +[#993]: https://github.com/tj/commander.js/issues/993 +[#999]: https://github.com/tj/commander.js/issues/999 +[#1010]: https://github.com/tj/commander.js/pull/1010 +[#1018]: https://github.com/tj/commander.js/pull/1018 +[#1026]: https://github.com/tj/commander.js/pull/1026 +[#1027]: https://github.com/tj/commander.js/pull/1027 +[#1028]: https://github.com/tj/commander.js/pull/1028 +[#1035]: https://github.com/tj/commander.js/pull/1035 +[#1040]: https://github.com/tj/commander.js/pull/1040 +[#1047]: https://github.com/tj/commander.js/pull/1047 +[#1048]: https://github.com/tj/commander.js/pull/1048 +[#1049]: https://github.com/tj/commander.js/pull/1049 +[#1051]: https://github.com/tj/commander.js/pull/1051 +[#1052]: https://github.com/tj/commander.js/pull/1052 +[#1053]: https://github.com/tj/commander.js/pull/1053 +[#1071]: https://github.com/tj/commander.js/pull/1071 +[#1081]: https://github.com/tj/commander.js/pull/1081 +[#1091]: https://github.com/tj/commander.js/pull/1091 +[#1096]: https://github.com/tj/commander.js/pull/1096 +[#1102]: https://github.com/tj/commander.js/pull/1102 +[#1118]: https://github.com/tj/commander.js/pull/1118 +[#1157]: https://github.com/tj/commander.js/pull/1157 + +[Unreleased]: https://github.com/tj/commander.js/compare/master...develop +[4.1.1]: https://github.com/tj/commander.js/compare/v4.0.0..v4.1.1 +[4.1.0]: https://github.com/tj/commander.js/compare/v4.0.1..v4.1.0 +[4.0.1]: https://github.com/tj/commander.js/compare/v4.0.0..v4.0.1 +[4.0.0]: https://github.com/tj/commander.js/compare/v3.0.2..v4.0.0 +[4.0.0-1]: https://github.com/tj/commander.js/compare/v4.0.0-0..v4.0.0-1 +[4.0.0-0]: https://github.com/tj/commander.js/compare/v3.0.2...v4.0.0-0 +[3.0.2]: https://github.com/tj/commander.js/compare/v3.0.1...v3.0.2 +[3.0.1]: https://github.com/tj/commander.js/compare/v3.0.0...v3.0.1 +[3.0.0]: https://github.com/tj/commander.js/compare/v2.20.1...v3.0.0 +[2.20.1]: https://github.com/tj/commander.js/compare/v2.20.0...v2.20.1 diff --git a/node_modules/commander/LICENSE b/node_modules/commander/LICENSE new file mode 100644 index 000000000..10f997ab1 --- /dev/null +++ b/node_modules/commander/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2011 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/commander/Readme.md b/node_modules/commander/Readme.md new file mode 100644 index 000000000..aa4f42b59 --- /dev/null +++ b/node_modules/commander/Readme.md @@ -0,0 +1,713 @@ +# Commander.js + +[![Build Status](https://api.travis-ci.org/tj/commander.js.svg?branch=master)](http://travis-ci.org/tj/commander.js) +[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander) +[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true) +[![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander) + +The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander). + +Read this in other languages: English | [简体中文](./Readme_zh-CN.md) + +- [Commander.js](#commanderjs) + - [Installation](#installation) + - [Declaring program variable](#declaring-program-variable) + - [Options](#options) + - [Common option types, boolean and value](#common-option-types-boolean-and-value) + - [Default option value](#default-option-value) + - [Other option types, negatable boolean and flag|value](#other-option-types-negatable-boolean-and-flagvalue) + - [Custom option processing](#custom-option-processing) + - [Required option](#required-option) + - [Version option](#version-option) + - [Commands](#commands) + - [Specify the argument syntax](#specify-the-argument-syntax) + - [Action handler (sub)commands](#action-handler-subcommands) + - [Git-style executable (sub)commands](#git-style-executable-subcommands) + - [Automated --help](#automated---help) + - [Custom help](#custom-help) + - [.usage and .name](#usage-and-name) + - [.outputHelp(cb)](#outputhelpcb) + - [.helpOption(flags, description)](#helpoptionflags-description) + - [.help(cb)](#helpcb) + - [Custom event listeners](#custom-event-listeners) + - [Bits and pieces](#bits-and-pieces) + - [Avoiding option name clashes](#avoiding-option-name-clashes) + - [TypeScript](#typescript) + - [Node options such as --harmony](#node-options-such-as---harmony) + - [Node debugging](#node-debugging) + - [Override exit handling](#override-exit-handling) + - [Examples](#examples) + - [License](#license) + - [Support](#support) + - [Commander for enterprise](#commander-for-enterprise) + +## Installation + +```bash +npm install commander +``` + +## Declaring _program_ variable + +Commander exports a global object which is convenient for quick programs. +This is used in the examples in this README for brevity. + +```js +const program = require('commander'); +program.version('0.0.1'); +``` + +For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use. + + ```js + const commander = require('commander'); + const program = new commander.Command(); + program.version('0.0.1'); + ``` + +## Options + +Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma or space. + +The options can be accessed as properties on the Command object. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. Multiple short flags may be combined as a single arg, for example `-abc` is equivalent to `-a -b -c`. + +See also optional new behaviour to [avoid name clashes](#avoiding-option-name-clashes). + +### Common option types, boolean and value + +The two most used option types are a boolean flag, and an option which takes a value (declared using angle brackets). Both are `undefined` unless specified on command line. + +```js +const program = require('commander'); + +program + .option('-d, --debug', 'output extra debugging') + .option('-s, --small', 'small pizza size') + .option('-p, --pizza-type ', 'flavour of pizza'); + +program.parse(process.argv); + +if (program.debug) console.log(program.opts()); +console.log('pizza details:'); +if (program.small) console.log('- small pizza size'); +if (program.pizzaType) console.log(`- ${program.pizzaType}`); +``` + +```bash +$ pizza-options -d +{ debug: true, small: undefined, pizzaType: undefined } +pizza details: +$ pizza-options -p +error: option '-p, --pizza-type ' argument missing +$ pizza-options -ds -p vegetarian +{ debug: true, small: true, pizzaType: 'vegetarian' } +pizza details: +- small pizza size +- vegetarian +$ pizza-options --pizza-type=cheese +pizza details: +- cheese +``` + +`program.parse(arguments)` processes the arguments, leaving any args not consumed by the options as the `program.args` array. + +### Default option value + +You can specify a default value for an option which takes a value. + +```js +const program = require('commander'); + +program + .option('-c, --cheese ', 'add the specified type of cheese', 'blue'); + +program.parse(process.argv); + +console.log(`cheese: ${program.cheese}`); +``` + +```bash +$ pizza-options +cheese: blue +$ pizza-options --cheese stilton +cheese: stilton +``` + +### Other option types, negatable boolean and flag|value + +You can specify a boolean option long name with a leading `no-` to set the option value to false when used. +Defined alone this also makes the option true by default. + +If you define `--foo` first, adding `--no-foo` does not change the default value from what it would +otherwise be. You can specify a default boolean value for a boolean flag and it can be overridden on command line. + +```js +const program = require('commander'); + +program + .option('--no-sauce', 'Remove sauce') + .option('--cheese ', 'cheese flavour', 'mozzarella') + .option('--no-cheese', 'plain with no cheese') + .parse(process.argv); + +const sauceStr = program.sauce ? 'sauce' : 'no sauce'; +const cheeseStr = (program.cheese === false) ? 'no cheese' : `${program.cheese} cheese`; +console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`); +``` + +```bash +$ pizza-options +You ordered a pizza with sauce and mozzarella cheese +$ pizza-options --sauce +error: unknown option '--sauce' +$ pizza-options --cheese=blue +You ordered a pizza with sauce and blue cheese +$ pizza-options --no-sauce --no-cheese +You ordered a pizza with no sauce and no cheese +``` + +You can specify an option which functions as a flag but may also take a value (declared using square brackets). + +```js +const program = require('commander'); + +program + .option('-c, --cheese [type]', 'Add cheese with optional type'); + +program.parse(process.argv); + +if (program.cheese === undefined) console.log('no cheese'); +else if (program.cheese === true) console.log('add cheese'); +else console.log(`add cheese type ${program.cheese}`); +``` + +```bash +$ pizza-options +no cheese +$ pizza-options --cheese +add cheese +$ pizza-options --cheese mozzarella +add cheese type mozzarella +``` + +### Custom option processing + +You may specify a function to do custom processing of option values. The callback function receives two parameters, the user specified value and the +previous value for the option. It returns the new value for the option. + +This allows you to coerce the option value to the desired type, or accumulate values, or do entirely custom processing. + +You can optionally specify the default/starting value for the option after the function. + +```js +const program = require('commander'); + +function myParseInt(value, dummyPrevious) { + // parseInt takes a string and an optional radix + return parseInt(value); +} + +function increaseVerbosity(dummyValue, previous) { + return previous + 1; +} + +function collect(value, previous) { + return previous.concat([value]); +} + +function commaSeparatedList(value, dummyPrevious) { + return value.split(','); +} + +program + .option('-f, --float ', 'float argument', parseFloat) + .option('-i, --integer ', 'integer argument', myParseInt) + .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0) + .option('-c, --collect ', 'repeatable value', collect, []) + .option('-l, --list ', 'comma separated list', commaSeparatedList) +; + +program.parse(process.argv); + +if (program.float !== undefined) console.log(`float: ${program.float}`); +if (program.integer !== undefined) console.log(`integer: ${program.integer}`); +if (program.verbose > 0) console.log(`verbosity: ${program.verbose}`); +if (program.collect.length > 0) console.log(program.collect); +if (program.list !== undefined) console.log(program.list); +``` + +```bash +$ custom -f 1e2 +float: 100 +$ custom --integer 2 +integer: 2 +$ custom -v -v -v +verbose: 3 +$ custom -c a -c b -c c +[ 'a', 'b', 'c' ] +$ custom --list x,y,z +[ 'x', 'y', 'z' ] +``` + +### Required option + +You may specify a required (mandatory) option using `.requiredOption`. The option must be specified on the command line, or by having a default value. The method is otherwise the same as `.option` in format, taking flags and description, and optional default value or custom processing. + +```js +const program = require('commander'); + +program + .requiredOption('-c, --cheese ', 'pizza must have cheese'); + +program.parse(process.argv); +``` + +``` +$ pizza +error: required option '-c, --cheese ' not specified +``` + +### Version option + +The optional `version` method adds handling for displaying the command version. The default option flags are `-V` and `--version`, and when present the command prints the version number and exits. + +```js +program.version('0.0.1'); +``` + +```bash +$ ./examples/pizza -V +0.0.1 +``` + +You may change the flags and description by passing additional parameters to the `version` method, using +the same syntax for flags as the `option` method. The version flags can be named anything, but a long name is required. + +```js +program.version('0.0.1', '-v, --vers', 'output the current version'); +``` + +## Commands + +You can specify (sub)commands for your top-level command using `.command`. There are two ways these can be implemented: using an action handler attached to the command, or as a separate executable file (described in more detail later). In the first parameter to `.command` you specify the command name and any command arguments. The arguments may be `` or `[optional]`, and the last argument may also be `variadic...`. + +For example: + +```js +// Command implemented using action handler (description is supplied separately to `.command`) +// Returns new command for configuring. +program + .command('clone [destination]') + .description('clone a repository into a newly created directory') + .action((source, destination) => { + console.log('clone command called'); + }); + +// Command implemented using separate executable file (description is second parameter to `.command`) +// Returns top-level command for adding more commands. +program + .command('start ', 'start named service') + .command('stop [service]', 'stop named service, or all if no name supplied'); +``` + +### Specify the argument syntax + +You use `.arguments` to specify the arguments for the top-level command, and for subcommands they are included in the `.command` call. Angled brackets (e.g. ``) indicate required input. Square brackets (e.g. `[optional]`) indicate optional input. + +```js +const program = require('commander'); + +program + .version('0.1.0') + .arguments(' [env]') + .action(function (cmd, env) { + cmdValue = cmd; + envValue = env; + }); + +program.parse(process.argv); + +if (typeof cmdValue === 'undefined') { + console.error('no command given!'); + process.exit(1); +} +console.log('command:', cmdValue); +console.log('environment:', envValue || "no environment given"); +``` + + The last argument of a command can be variadic, and only the last argument. To make an argument variadic you + append `...` to the argument name. For example: + +```js +const program = require('commander'); + +program + .version('0.1.0') + .command('rmdir [otherDirs...]') + .action(function (dir, otherDirs) { + console.log('rmdir %s', dir); + if (otherDirs) { + otherDirs.forEach(function (oDir) { + console.log('rmdir %s', oDir); + }); + } + }); + +program.parse(process.argv); +``` + +The variadic argument is passed to the action handler as an array. (And this also applies to `program.args`.) + +### Action handler (sub)commands + +You can add options to a command that uses an action handler. +The action handler gets passed a parameter for each argument you declared, and one additional argument which is the +command object itself. This command argument has the values for the command-specific options added as properties. + +```js +const program = require('commander'); + +program + .command('rm ') + .option('-r, --recursive', 'Remove recursively') + .action(function (dir, cmdObj) { + console.log('remove ' + dir + (cmdObj.recursive ? ' recursively' : '')) + }) + +program.parse(process.argv) +``` + +You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`. + +```js +async function run() { /* code goes here */ } + +async function main() { + program + .command('run') + .action(run); + await program.parseAsync(process.argv); +} +``` + +A command's options on the command line are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated. + +Configuration options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the command from the generated help output. + +### Git-style executable (sub)commands + +When `.command()` is invoked with a description argument, this tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools. +Commander will search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-subcommand`, like `pm-install`, `pm-search`. +You can specify a custom name with the `executableFile` configuration option. + +You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level. + +```js +// file: ./examples/pm +const program = require('commander'); + +program + .version('0.1.0') + .command('install [name]', 'install one or more packages') + .command('search [query]', 'search with optional query') + .command('update', 'update installed packages', {executableFile: 'myUpdateSubCommand'}) + .command('list', 'list packages installed', {isDefault: true}) + .parse(process.argv); +``` + +Configuration options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the command from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified. +Specifying a name with `executableFile` will override the default constructed name. + +If the program is designed to be installed globally, make sure the executables have proper modes, like `755`. + +## Automated --help + + The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free: + +```bash +$ ./examples/pizza --help +Usage: pizza [options] + +An application for pizzas ordering + +Options: + -V, --version output the version number + -p, --peppers Add peppers + -P, --pineapple Add pineapple + -b, --bbq Add bbq sauce + -c, --cheese Add the specified type of cheese (default: "marble") + -C, --no-cheese You do not want any cheese + -h, --help output usage information +``` + +### Custom help + + You can display arbitrary `-h, --help` information + by listening for "--help". Commander will automatically + exit once you are done so that the remainder of your program + does not execute causing undesired behaviors, for example + in the following executable "stuff" will not output when + `--help` is used. + +```js +#!/usr/bin/env node + +const program = require('commander'); + +program + .version('0.1.0') + .option('-f, --foo', 'enable some foo') + .option('-b, --bar', 'enable some bar') + .option('-B, --baz', 'enable some baz'); + +// must be before .parse() since +// node's emit() is immediate + +program.on('--help', function(){ + console.log('') + console.log('Examples:'); + console.log(' $ custom-help --help'); + console.log(' $ custom-help -h'); +}); + +program.parse(process.argv); + +console.log('stuff'); +``` + +Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run: + +```Text +Usage: custom-help [options] + +Options: + -h, --help output usage information + -V, --version output the version number + -f, --foo enable some foo + -b, --bar enable some bar + -B, --baz enable some baz + +Examples: + $ custom-help --help + $ custom-help -h +``` + +### .usage and .name + +These allow you to customise the usage description in the first line of the help. The name is otherwise +deduced from the (full) program arguments. Given: + +```js +program + .name("my-command") + .usage("[global options] command") +``` + +The help will start with: + +```Text +Usage: my-command [global options] command +``` + +### .outputHelp(cb) + +Output help information without exiting. +Optional callback cb allows post-processing of help text before it is displayed. + +If you want to display help by default (e.g. if no command was provided), you can use something like: + +```js +const program = require('commander'); +const colors = require('colors'); + +program + .version('0.1.0') + .command('getstream [url]', 'get stream URL') + .parse(process.argv); + +if (!process.argv.slice(2).length) { + program.outputHelp(make_red); +} + +function make_red(txt) { + return colors.red(txt); //display the help text in red on the console +} +``` + +### .helpOption(flags, description) + + Override the default help flags and description. + +```js +program + .helpOption('-e, --HELP', 'read more information'); +``` + +### .help(cb) + + Output help information and exit immediately. + Optional callback cb allows post-processing of help text before it is displayed. + +## Custom event listeners + + You can execute custom actions by listening to command and option events. + +```js +program.on('option:verbose', function () { + process.env.VERBOSE = this.verbose; +}); + +// error on unknown commands +program.on('command:*', function () { + console.error('Invalid command: %s\nSee --help for a list of available commands.', program.args.join(' ')); + process.exit(1); +}); +``` + +## Bits and pieces + +### Avoiding option name clashes + +The original and default behaviour is that the option values are stored +as properties on the program, and the action handler is passed a +command object with the options values stored as properties. +This is very convenient to code, but the downside is possible clashes with +existing properties of Command. + +There are two new routines to change the behaviour, and the default behaviour may change in the future: + +- `storeOptionsAsProperties`: whether to store option values as properties on command object, or store separately (specify false) and access using `.opts()` +- `passCommandToAction`: whether to pass command to action handler, +or just the options (specify false) + +```js +// file: ./examples/storeOptionsAsProperties.action.js +program + .storeOptionsAsProperties(false) + .passCommandToAction(false); + +program + .name('my-program-name') + .option('-n,--name '); + +program + .command('show') + .option('-a,--action ') + .action((options) => { + console.log(options.action); + }); + +program.parse(process.argv); + +const programOptions = program.opts(); +console.log(programOptions.name); +``` + +### TypeScript + +The Commander package includes its TypeScript Definition file, but also requires the node types which you need to install yourself. e.g. + +```bash +npm install commander +npm install --save-dev @types/node +``` + +If you use `ts-node` and git-style sub-commands written as `.ts` files, you need to call your program through node to get the sub-commands called correctly. e.g. + +```bash +node -r ts-node/register pm.ts +``` + +### Node options such as `--harmony` + +You can enable `--harmony` option in two ways: + +- Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. (Note Windows does not support this pattern.) +- Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning sub-command process. + +### Node debugging + +If you are using the node inspector for [debugging](https://nodejs.org/en/docs/guides/debugging-getting-started/) git-style executable (sub)commands using `node --inspect` et al, +the inspector port is incremented by 1 for the spawned subcommand. + +### Override exit handling + +By default Commander calls `process.exit` when it detects errors, or after displaying the help or version. You can override +this behaviour and optionally supply a callback. The default override throws a `CommanderError`. + +The override callback is passed a `CommanderError` with properties `exitCode` number, `code` string, and `message`. The default override behaviour is to throw the error, except for async handling of executable subcommand completion which carries on. The normal display of error messages or version or help +is not affected by the override which is called after the display. + +``` js +program.exitOverride(); + +try { + program.parse(process.argv); +} catch (err) { + // custom processing... +} +``` + +## Examples + +```js +const program = require('commander'); + +program + .version('0.1.0') + .option('-C, --chdir ', 'change the working directory') + .option('-c, --config ', 'set config path. defaults to ./deploy.conf') + .option('-T, --no-tests', 'ignore test hook'); + +program + .command('setup [env]') + .description('run setup commands for all envs') + .option("-s, --setup_mode [mode]", "Which setup mode to use") + .action(function(env, options){ + const mode = options.setup_mode || "normal"; + env = env || 'all'; + console.log('setup for %s env(s) with %s mode', env, mode); + }); + +program + .command('exec ') + .alias('ex') + .description('execute the given remote cmd') + .option("-e, --exec_mode ", "Which exec mode to use") + .action(function(cmd, options){ + console.log('exec "%s" using %s mode', cmd, options.exec_mode); + }).on('--help', function() { + console.log(''); + console.log('Examples:'); + console.log(''); + console.log(' $ deploy exec sequential'); + console.log(' $ deploy exec async'); + }); + +program + .command('*') + .action(function(env){ + console.log('deploying "%s"', env); + }); + +program.parse(process.argv); +``` + +More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory. + +## License + +[MIT](https://github.com/tj/commander.js/blob/master/LICENSE) + +## Support + +Commander 4.x is supported on Node 8 and above, and is likely to work with Node 6 but not tested. +(For versions of Node below Node 6, use Commander 3.x or 2.x.) + +The main forum for free and community support is the project [Issues](https://github.com/tj/commander.js/issues) on GitHub. + +### Commander for enterprise + +Available as part of the Tidelift Subscription + +The maintainers of Commander and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-commander?utm_source=npm-commander&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/node_modules/commander/index.js b/node_modules/commander/index.js new file mode 100644 index 000000000..37d20cc5e --- /dev/null +++ b/node_modules/commander/index.js @@ -0,0 +1,1649 @@ +/** + * Module dependencies. + */ + +var EventEmitter = require('events').EventEmitter; +var spawn = require('child_process').spawn; +var path = require('path'); +var dirname = path.dirname; +var basename = path.basename; +var fs = require('fs'); + +/** + * Inherit `Command` from `EventEmitter.prototype`. + */ + +require('util').inherits(Command, EventEmitter); + +/** + * Expose the root command. + */ + +exports = module.exports = new Command(); + +/** + * Expose `Command`. + */ + +exports.Command = Command; + +/** + * Expose `Option`. + */ + +exports.Option = Option; + +/** + * Initialize a new `Option` with the given `flags` and `description`. + * + * @param {String} flags + * @param {String} description + * @api public + */ + +function Option(flags, description) { + this.flags = flags; + this.required = flags.indexOf('<') >= 0; // A value must be supplied when the option is specified. + this.optional = flags.indexOf('[') >= 0; // A value is optional when the option is specified. + this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line. + this.negate = flags.indexOf('-no-') !== -1; + flags = flags.split(/[ ,|]+/); + if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift(); + this.long = flags.shift(); + this.description = description || ''; +} + +/** + * Return option name. + * + * @return {String} + * @api private + */ + +Option.prototype.name = function() { + return this.long.replace(/^--/, ''); +}; + +/** + * Return option name, in a camelcase format that can be used + * as a object attribute key. + * + * @return {String} + * @api private + */ + +Option.prototype.attributeName = function() { + return camelcase(this.name().replace(/^no-/, '')); +}; + +/** + * Check if `arg` matches the short or long flag. + * + * @param {String} arg + * @return {Boolean} + * @api private + */ + +Option.prototype.is = function(arg) { + return this.short === arg || this.long === arg; +}; + +/** + * CommanderError class + * @class + */ +class CommanderError extends Error { + /** + * Constructs the CommanderError class + * @param {Number} exitCode suggested exit code which could be used with process.exit + * @param {String} code an id string representing the error + * @param {String} message human-readable description of the error + * @constructor + */ + constructor(exitCode, code, message) { + super(message); + // properly capture stack trace in Node.js + Error.captureStackTrace(this, this.constructor); + this.name = this.constructor.name; + this.code = code; + this.exitCode = exitCode; + } +} + +exports.CommanderError = CommanderError; + +/** + * Initialize a new `Command`. + * + * @param {String} [name] + * @api public + */ + +function Command(name) { + this.commands = []; + this.options = []; + this._execs = new Set(); + this._allowUnknownOption = false; + this._args = []; + this._name = name || ''; + this._optionValues = {}; + this._storeOptionsAsProperties = true; // backwards compatible by default + this._passCommandToAction = true; // backwards compatible by default + this._actionResults = []; + + this._helpFlags = '-h, --help'; + this._helpDescription = 'output usage information'; + this._helpShortFlag = '-h'; + this._helpLongFlag = '--help'; +} + +/** + * Define a command. + * + * There are two styles of command: pay attention to where to put the description. + * + * Examples: + * + * // Command implemented using action handler (description is supplied separately to `.command`) + * program + * .command('clone [destination]') + * .description('clone a repository into a newly created directory') + * .action((source, destination) => { + * console.log('clone command called'); + * }); + * + * // Command implemented using separate executable file (description is second parameter to `.command`) + * program + * .command('start ', 'start named service') + * .command('stop [service]', 'stop named service, or all if no name supplied'); + * + * @param {string} nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...` + * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable) + * @param {Object} [execOpts] - configuration options (for executable) + * @return {Command} returns new command for action handler, or top-level command for executable command + * @api public + */ + +Command.prototype.command = function(nameAndArgs, actionOptsOrExecDesc, execOpts) { + var desc = actionOptsOrExecDesc; + var opts = execOpts; + if (typeof desc === 'object' && desc !== null) { + opts = desc; + desc = null; + } + opts = opts || {}; + var args = nameAndArgs.split(/ +/); + var cmd = new Command(args.shift()); + + if (desc) { + cmd.description(desc); + this.executables = true; + this._execs.add(cmd._name); + if (opts.isDefault) this.defaultExecutable = cmd._name; + } + cmd._noHelp = !!opts.noHelp; + cmd._helpFlags = this._helpFlags; + cmd._helpDescription = this._helpDescription; + cmd._helpShortFlag = this._helpShortFlag; + cmd._helpLongFlag = this._helpLongFlag; + cmd._exitCallback = this._exitCallback; + cmd._storeOptionsAsProperties = this._storeOptionsAsProperties; + cmd._passCommandToAction = this._passCommandToAction; + + cmd._executableFile = opts.executableFile; // Custom name for executable file + this.commands.push(cmd); + cmd.parseExpectedArgs(args); + cmd.parent = this; + + if (desc) return this; + return cmd; +}; + +/** + * Define argument syntax for the top-level command. + * + * @api public + */ + +Command.prototype.arguments = function(desc) { + return this.parseExpectedArgs(desc.split(/ +/)); +}; + +/** + * Add an implicit `help [cmd]` subcommand + * which invokes `--help` for the given command. + * + * @api private + */ + +Command.prototype.addImplicitHelpCommand = function() { + this.command('help [cmd]', 'display help for [cmd]'); +}; + +/** + * Parse expected `args`. + * + * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. + * + * @param {Array} args + * @return {Command} for chaining + * @api public + */ + +Command.prototype.parseExpectedArgs = function(args) { + if (!args.length) return; + var self = this; + args.forEach(function(arg) { + var argDetails = { + required: false, + name: '', + variadic: false + }; + + switch (arg[0]) { + case '<': + argDetails.required = true; + argDetails.name = arg.slice(1, -1); + break; + case '[': + argDetails.name = arg.slice(1, -1); + break; + } + + if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') { + argDetails.variadic = true; + argDetails.name = argDetails.name.slice(0, -3); + } + if (argDetails.name) { + self._args.push(argDetails); + } + }); + return this; +}; + +/** + * Register callback to use as replacement for calling process.exit. + * + * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing + * @return {Command} for chaining + * @api public + */ + +Command.prototype.exitOverride = function(fn) { + if (fn) { + this._exitCallback = fn; + } else { + this._exitCallback = function(err) { + if (err.code !== 'commander.executeSubCommandAsync') { + throw err; + } else { + // Async callback from spawn events, not useful to throw. + } + }; + } + return this; +}; + +/** + * Call process.exit, and _exitCallback if defined. + * + * @param {Number} exitCode exit code for using with process.exit + * @param {String} code an id string representing the error + * @param {String} message human-readable description of the error + * @return never + * @api private + */ + +Command.prototype._exit = function(exitCode, code, message) { + if (this._exitCallback) { + this._exitCallback(new CommanderError(exitCode, code, message)); + // Expecting this line is not reached. + } + process.exit(exitCode); +}; + +/** + * Register callback `fn` for the command. + * + * Examples: + * + * program + * .command('help') + * .description('display verbose help') + * .action(function() { + * // output help here + * }); + * + * @param {Function} fn + * @return {Command} for chaining + * @api public + */ + +Command.prototype.action = function(fn) { + var self = this; + var listener = function(args, unknown) { + // Parse any so-far unknown options + args = args || []; + unknown = unknown || []; + + var parsed = self.parseOptions(unknown); + + // Output help if necessary + outputHelpIfRequested(self, parsed.unknown); + self._checkForMissingMandatoryOptions(); + + // If there are still any unknown options, then we simply + // die, unless someone asked for help, in which case we give it + // to them, and then we die. + if (parsed.unknown.length > 0) { + self.unknownOption(parsed.unknown[0]); + } + + // Leftover arguments need to be pushed back. Fixes issue #56 + if (parsed.args.length) args = parsed.args.concat(args); + + self._args.forEach(function(arg, i) { + if (arg.required && args[i] == null) { + self.missingArgument(arg.name); + } else if (arg.variadic) { + if (i !== self._args.length - 1) { + self.variadicArgNotLast(arg.name); + } + + args[i] = args.splice(i); + } + }); + + // The .action callback takes an extra parameter which is the command itself. + var expectedArgsCount = self._args.length; + var actionArgs = args.slice(0, expectedArgsCount); + if (self._passCommandToAction) { + actionArgs[expectedArgsCount] = self; + } else { + actionArgs[expectedArgsCount] = self.opts(); + } + // Add the extra arguments so available too. + if (args.length > expectedArgsCount) { + actionArgs.push(args.slice(expectedArgsCount)); + } + + const actionResult = fn.apply(self, actionArgs); + // Remember result in case it is async. Assume parseAsync getting called on root. + let rootCommand = self; + while (rootCommand.parent) { + rootCommand = rootCommand.parent; + } + rootCommand._actionResults.push(actionResult); + }; + var parent = this.parent || this; + var name = parent === this ? '*' : this._name; + parent.on('command:' + name, listener); + if (this._alias) parent.on('command:' + this._alias, listener); + return this; +}; + +/** + * Internal implementation shared by .option() and .requiredOption() + * + * @param {Object} config + * @param {String} flags + * @param {String} description + * @param {Function|*} [fn] - custom option processing function or default vaue + * @param {*} [defaultValue] + * @return {Command} for chaining + * @api private + */ + +Command.prototype._optionEx = function(config, flags, description, fn, defaultValue) { + var self = this, + option = new Option(flags, description), + oname = option.name(), + name = option.attributeName(); + option.mandatory = !!config.mandatory; + + // default as 3rd arg + if (typeof fn !== 'function') { + if (fn instanceof RegExp) { + // This is a bit simplistic (especially no error messages), and probably better handled by caller using custom option processing. + // No longer documented in README, but still present for backwards compatibility. + var regex = fn; + fn = function(val, def) { + var m = regex.exec(val); + return m ? m[0] : def; + }; + } else { + defaultValue = fn; + fn = null; + } + } + + // preassign default value for --no-*, [optional], , or plain flag if boolean value + if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') { + // when --no-foo we make sure default is true, unless a --foo option is already defined + if (option.negate) { + const positiveLongFlag = option.long.replace(/^--no-/, '--'); + defaultValue = self.optionFor(positiveLongFlag) ? self._getOptionValue(name) : true; + } + // preassign only if we have a default + if (defaultValue !== undefined) { + self._setOptionValue(name, defaultValue); + option.defaultValue = defaultValue; + } + } + + // register the option + this.options.push(option); + + // when it's passed assign the value + // and conditionally invoke the callback + this.on('option:' + oname, function(val) { + // coercion + if (val !== null && fn) { + val = fn(val, self._getOptionValue(name) === undefined ? defaultValue : self._getOptionValue(name)); + } + + // unassigned or boolean value + if (typeof self._getOptionValue(name) === 'boolean' || typeof self._getOptionValue(name) === 'undefined') { + // if no value, negate false, and we have a default, then use it! + if (val == null) { + self._setOptionValue(name, option.negate + ? false + : defaultValue || true); + } else { + self._setOptionValue(name, val); + } + } else if (val !== null) { + // reassign + self._setOptionValue(name, option.negate ? false : val); + } + }); + + return this; +}; + +/** + * Define option with `flags`, `description` and optional + * coercion `fn`. + * + * The `flags` string should contain both the short and long flags, + * separated by comma, a pipe or space. The following are all valid + * all will output this way when `--help` is used. + * + * "-p, --pepper" + * "-p|--pepper" + * "-p --pepper" + * + * Examples: + * + * // simple boolean defaulting to undefined + * program.option('-p, --pepper', 'add pepper'); + * + * program.pepper + * // => undefined + * + * --pepper + * program.pepper + * // => true + * + * // simple boolean defaulting to true (unless non-negated option is also defined) + * program.option('-C, --no-cheese', 'remove cheese'); + * + * program.cheese + * // => true + * + * --no-cheese + * program.cheese + * // => false + * + * // required argument + * program.option('-C, --chdir ', 'change the working directory'); + * + * --chdir /tmp + * program.chdir + * // => "/tmp" + * + * // optional argument + * program.option('-c, --cheese [type]', 'add cheese [marble]'); + * + * @param {String} flags + * @param {String} description + * @param {Function|*} [fn] - custom option processing function or default vaue + * @param {*} [defaultValue] + * @return {Command} for chaining + * @api public + */ + +Command.prototype.option = function(flags, description, fn, defaultValue) { + return this._optionEx({}, flags, description, fn, defaultValue); +}; + +/* + * Add a required option which must have a value after parsing. This usually means + * the option must be specified on the command line. (Otherwise the same as .option().) + * + * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space. + * + * @param {String} flags + * @param {String} description + * @param {Function|*} [fn] - custom option processing function or default vaue + * @param {*} [defaultValue] + * @return {Command} for chaining + * @api public + */ + +Command.prototype.requiredOption = function(flags, description, fn, defaultValue) { + return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue); +}; + +/** + * Allow unknown options on the command line. + * + * @param {Boolean} arg if `true` or omitted, no error will be thrown + * for unknown options. + * @api public + */ +Command.prototype.allowUnknownOption = function(arg) { + this._allowUnknownOption = arguments.length === 0 || arg; + return this; +}; + +/** + * Whether to store option values as properties on command object, + * or store separately (specify false). In both cases the option values can be accessed using .opts(). + * + * @param {boolean} value + * @return {Command} Command for chaining + * @api public + */ + +Command.prototype.storeOptionsAsProperties = function(value) { + this._storeOptionsAsProperties = (value === undefined) || value; + if (this.options.length) { + // This is for programmer, not end user. + console.error('Commander usage error: call storeOptionsAsProperties before adding options'); + } + return this; +}; + +/** + * Whether to pass command to action handler, + * or just the options (specify false). + * + * @param {boolean} value + * @return {Command} Command for chaining + * @api public + */ + +Command.prototype.passCommandToAction = function(value) { + this._passCommandToAction = (value === undefined) || value; + return this; +}; + +/** + * Store option value + * + * @param {String} key + * @param {Object} value + * @api private + */ + +Command.prototype._setOptionValue = function(key, value) { + if (this._storeOptionsAsProperties) { + this[key] = value; + } else { + this._optionValues[key] = value; + } +}; + +/** + * Retrieve option value + * + * @param {String} key + * @return {Object} value + * @api private + */ + +Command.prototype._getOptionValue = function(key) { + if (this._storeOptionsAsProperties) { + return this[key]; + } + return this._optionValues[key]; +}; + +/** + * Parse `argv`, setting options and invoking commands when defined. + * + * @param {Array} argv + * @return {Command} for chaining + * @api public + */ + +Command.prototype.parse = function(argv) { + // implicit help + if (this.executables) this.addImplicitHelpCommand(); + + // store raw args + this.rawArgs = argv; + + // guess name + this._name = this._name || basename(argv[1], '.js'); + + // github-style sub-commands with no sub-command + if (this.executables && argv.length < 3 && !this.defaultExecutable) { + // this user needs help + argv.push(this._helpLongFlag); + } + + // process argv + var normalized = this.normalize(argv.slice(2)); + var parsed = this.parseOptions(normalized); + var args = this.args = parsed.args; + + var result = this.parseArgs(this.args, parsed.unknown); + + if (args[0] === 'help' && args.length === 1) this.help(); + + // Note for future: we could return early if we found an action handler in parseArgs, as none of following code needed? + + // --help + if (args[0] === 'help') { + args[0] = args[1]; + args[1] = this._helpLongFlag; + } else { + // If calling through to executable subcommand we could check for help flags before failing, + // but a somewhat unlikely case since program options not passed to executable subcommands. + // Wait for reports to see if check needed and what usage pattern is. + this._checkForMissingMandatoryOptions(); + } + + // executable sub-commands + // (Debugging note for future: args[0] is not right if an action has been called) + var name = result.args[0]; + var subCommand = null; + + // Look for subcommand + if (name) { + subCommand = this.commands.find(function(command) { + return command._name === name; + }); + } + + // Look for alias + if (!subCommand && name) { + subCommand = this.commands.find(function(command) { + return command.alias() === name; + }); + if (subCommand) { + name = subCommand._name; + args[0] = name; + } + } + + // Look for default subcommand + if (!subCommand && this.defaultExecutable) { + name = this.defaultExecutable; + args.unshift(name); + subCommand = this.commands.find(function(command) { + return command._name === name; + }); + } + + if (this._execs.has(name)) { + return this.executeSubCommand(argv, args, parsed.unknown, subCommand ? subCommand._executableFile : undefined); + } + + return result; +}; + +/** + * Parse `argv`, setting options and invoking commands when defined. + * + * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise. + * + * @param {Array} argv + * @return {Promise} + * @api public + */ +Command.prototype.parseAsync = function(argv) { + this.parse(argv); + return Promise.all(this._actionResults); +}; + +/** + * Execute a sub-command executable. + * + * @param {Array} argv + * @param {Array} args + * @param {Array} unknown + * @param {String} executableFile + * @api private + */ + +Command.prototype.executeSubCommand = function(argv, args, unknown, executableFile) { + args = args.concat(unknown); + + if (!args.length) this.help(); + + var isExplicitJS = false; // Whether to use node to launch "executable" + + // executable + var pm = argv[1]; + // name of the subcommand, like `pm-install` + var bin = basename(pm, path.extname(pm)) + '-' + args[0]; + if (executableFile != null) { + bin = executableFile; + // Check for same extensions as we scan for below so get consistent launch behaviour. + var executableExt = path.extname(executableFile); + isExplicitJS = executableExt === '.js' || executableExt === '.ts' || executableExt === '.mjs'; + } + + // In case of globally installed, get the base dir where executable + // subcommand file should be located at + var baseDir; + + var resolvedLink = fs.realpathSync(pm); + + baseDir = dirname(resolvedLink); + + // prefer local `./` to bin in the $PATH + var localBin = path.join(baseDir, bin); + + // whether bin file is a js script with explicit `.js` or `.ts` extension + if (exists(localBin + '.js')) { + bin = localBin + '.js'; + isExplicitJS = true; + } else if (exists(localBin + '.ts')) { + bin = localBin + '.ts'; + isExplicitJS = true; + } else if (exists(localBin + '.mjs')) { + bin = localBin + '.mjs'; + isExplicitJS = true; + } else if (exists(localBin)) { + bin = localBin; + } + + args = args.slice(1); + + var proc; + if (process.platform !== 'win32') { + if (isExplicitJS) { + args.unshift(bin); + // add executable arguments to spawn + args = incrementNodeInspectorPort(process.execArgv).concat(args); + + proc = spawn(process.argv[0], args, { stdio: 'inherit' }); + } else { + proc = spawn(bin, args, { stdio: 'inherit' }); + } + } else { + args.unshift(bin); + // add executable arguments to spawn + args = incrementNodeInspectorPort(process.execArgv).concat(args); + proc = spawn(process.execPath, args, { stdio: 'inherit' }); + } + + var signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP']; + signals.forEach(function(signal) { + process.on(signal, function() { + if (proc.killed === false && proc.exitCode === null) { + proc.kill(signal); + } + }); + }); + + // By default terminate process when spawned process terminates. + // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running! + const exitCallback = this._exitCallback; + if (!exitCallback) { + proc.on('close', process.exit.bind(process)); + } else { + proc.on('close', () => { + exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)')); + }); + } + proc.on('error', function(err) { + if (err.code === 'ENOENT') { + console.error('error: %s(1) does not exist, try --help', bin); + } else if (err.code === 'EACCES') { + console.error('error: %s(1) not executable. try chmod or run with root', bin); + } + if (!exitCallback) { + process.exit(1); + } else { + const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)'); + wrappedError.nestedError = err; + exitCallback(wrappedError); + } + }); + + // Store the reference to the child process + this.runningCommand = proc; +}; + +/** + * Normalize `args`, splitting joined short flags. For example + * the arg "-abc" is equivalent to "-a -b -c". + * This also normalizes equal sign and splits "--abc=def" into "--abc def". + * + * @param {Array} args + * @return {Array} + * @api private + */ + +Command.prototype.normalize = function(args) { + var ret = [], + arg, + lastOpt, + index, + short, + opt; + + for (var i = 0, len = args.length; i < len; ++i) { + arg = args[i]; + if (i > 0) { + lastOpt = this.optionFor(args[i - 1]); + } + + if (arg === '--') { + // Honor option terminator + ret = ret.concat(args.slice(i)); + break; + } else if (lastOpt && lastOpt.required) { + ret.push(arg); + } else if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') { + short = arg.slice(0, 2); + opt = this.optionFor(short); + if (opt && (opt.required || opt.optional)) { + ret.push(short); + ret.push(arg.slice(2)); + } else { + arg.slice(1).split('').forEach(function(c) { + ret.push('-' + c); + }); + } + } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) { + ret.push(arg.slice(0, index), arg.slice(index + 1)); + } else { + ret.push(arg); + } + } + + return ret; +}; + +/** + * Parse command `args`. + * + * When listener(s) are available those + * callbacks are invoked, otherwise the "*" + * event is emitted and those actions are invoked. + * + * @param {Array} args + * @return {Command} for chaining + * @api private + */ + +Command.prototype.parseArgs = function(args, unknown) { + var name; + + if (args.length) { + name = args[0]; + if (this.listeners('command:' + name).length) { + this.emit('command:' + args.shift(), args, unknown); + } else { + this.emit('command:*', args, unknown); + } + } else { + outputHelpIfRequested(this, unknown); + + // If there were no args and we have unknown options, + // then they are extraneous and we need to error. + if (unknown.length > 0 && !this.defaultExecutable) { + this.unknownOption(unknown[0]); + } + if (this.commands.length === 0 && + this._args.filter(function(a) { return a.required; }).length === 0) { + this.emit('command:*'); + } + } + + return this; +}; + +/** + * Return an option matching `arg` if any. + * + * @param {String} arg + * @return {Option} + * @api private + */ + +Command.prototype.optionFor = function(arg) { + for (var i = 0, len = this.options.length; i < len; ++i) { + if (this.options[i].is(arg)) { + return this.options[i]; + } + } +}; + +/** + * Display an error message if a mandatory option does not have a value. + * + * @api private + */ + +Command.prototype._checkForMissingMandatoryOptions = function() { + // Walk up hierarchy so can call from action handler after checking for displaying help. + for (var cmd = this; cmd; cmd = cmd.parent) { + cmd.options.forEach((anOption) => { + if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) { + cmd.missingMandatoryOptionValue(anOption); + } + }); + } +}; + +/** + * Parse options from `argv` returning `argv` + * void of these options. + * + * @param {Array} argv + * @return {{args: Array, unknown: Array}} + * @api public + */ + +Command.prototype.parseOptions = function(argv) { + var args = [], + len = argv.length, + literal, + option, + arg; + + var unknownOptions = []; + + // parse options + for (var i = 0; i < len; ++i) { + arg = argv[i]; + + // literal args after -- + if (literal) { + args.push(arg); + continue; + } + + if (arg === '--') { + literal = true; + continue; + } + + // find matching Option + option = this.optionFor(arg); + + // option is defined + if (option) { + // requires arg + if (option.required) { + arg = argv[++i]; + if (arg == null) return this.optionMissingArgument(option); + this.emit('option:' + option.name(), arg); + // optional arg + } else if (option.optional) { + arg = argv[i + 1]; + if (arg == null || (arg[0] === '-' && arg !== '-')) { + arg = null; + } else { + ++i; + } + this.emit('option:' + option.name(), arg); + // flag + } else { + this.emit('option:' + option.name()); + } + continue; + } + + // looks like an option + if (arg.length > 1 && arg[0] === '-') { + unknownOptions.push(arg); + + // If the next argument looks like it might be + // an argument for this option, we pass it on. + // If it isn't, then it'll simply be ignored + if ((i + 1) < argv.length && (argv[i + 1][0] !== '-' || argv[i + 1] === '-')) { + unknownOptions.push(argv[++i]); + } + continue; + } + + // arg + args.push(arg); + } + + return { args: args, unknown: unknownOptions }; +}; + +/** + * Return an object containing options as key-value pairs + * + * @return {Object} + * @api public + */ +Command.prototype.opts = function() { + if (this._storeOptionsAsProperties) { + // Preserve original behaviour so backwards compatible when still using properties + var result = {}, + len = this.options.length; + + for (var i = 0; i < len; i++) { + var key = this.options[i].attributeName(); + result[key] = key === this._versionOptionName ? this._version : this[key]; + } + return result; + } + + return this._optionValues; +}; + +/** + * Argument `name` is missing. + * + * @param {String} name + * @api private + */ + +Command.prototype.missingArgument = function(name) { + const message = `error: missing required argument '${name}'`; + console.error(message); + this._exit(1, 'commander.missingArgument', message); +}; + +/** + * `Option` is missing an argument, but received `flag` or nothing. + * + * @param {Option} option + * @param {String} [flag] + * @api private + */ + +Command.prototype.optionMissingArgument = function(option, flag) { + let message; + if (flag) { + message = `error: option '${option.flags}' argument missing, got '${flag}'`; + } else { + message = `error: option '${option.flags}' argument missing`; + } + console.error(message); + this._exit(1, 'commander.optionMissingArgument', message); +}; + +/** + * `Option` does not have a value, and is a mandatory option. + * + * @param {Option} option + * @api private + */ + +Command.prototype.missingMandatoryOptionValue = function(option) { + const message = `error: required option '${option.flags}' not specified`; + console.error(message); + this._exit(1, 'commander.missingMandatoryOptionValue', message); +}; + +/** + * Unknown option `flag`. + * + * @param {String} flag + * @api private + */ + +Command.prototype.unknownOption = function(flag) { + if (this._allowUnknownOption) return; + const message = `error: unknown option '${flag}'`; + console.error(message); + this._exit(1, 'commander.unknownOption', message); +}; + +/** + * Variadic argument with `name` is not the last argument as required. + * + * @param {String} name + * @api private + */ + +Command.prototype.variadicArgNotLast = function(name) { + const message = `error: variadic arguments must be last '${name}'`; + console.error(message); + this._exit(1, 'commander.variadicArgNotLast', message); +}; + +/** + * Set the program version to `str`. + * + * This method auto-registers the "-V, --version" flag + * which will print the version number when passed. + * + * You can optionally supply the flags and description to override the defaults. + * + * @param {String} str + * @param {String} [flags] + * @param {String} [description] + * @return {Command} for chaining + * @api public + */ + +Command.prototype.version = function(str, flags, description) { + if (arguments.length === 0) return this._version; + this._version = str; + flags = flags || '-V, --version'; + description = description || 'output the version number'; + var versionOption = new Option(flags, description); + this._versionOptionName = versionOption.long.substr(2) || 'version'; + this.options.push(versionOption); + var self = this; + this.on('option:' + this._versionOptionName, function() { + process.stdout.write(str + '\n'); + self._exit(0, 'commander.version', str); + }); + return this; +}; + +/** + * Set the description to `str`. + * + * @param {String} str + * @param {Object} [argsDescription] + * @return {String|Command} + * @api public + */ + +Command.prototype.description = function(str, argsDescription) { + if (arguments.length === 0) return this._description; + this._description = str; + this._argsDescription = argsDescription; + return this; +}; + +/** + * Set an alias for the command + * + * @param {String} alias + * @return {String|Command} + * @api public + */ + +Command.prototype.alias = function(alias) { + var command = this; + if (this.commands.length !== 0) { + command = this.commands[this.commands.length - 1]; + } + + if (arguments.length === 0) return command._alias; + + if (alias === command._name) throw new Error('Command alias can\'t be the same as its name'); + + command._alias = alias; + return this; +}; + +/** + * Set / get the command usage `str`. + * + * @param {String} [str] + * @return {String|Command} + * @api public + */ + +Command.prototype.usage = function(str) { + var args = this._args.map(function(arg) { + return humanReadableArgName(arg); + }); + + var usage = '[options]' + + (this.commands.length ? ' [command]' : '') + + (this._args.length ? ' ' + args.join(' ') : ''); + + if (arguments.length === 0) return this._usage || usage; + this._usage = str; + + return this; +}; + +/** + * Get or set the name of the command + * + * @param {String} [str] + * @return {String|Command} + * @api public + */ + +Command.prototype.name = function(str) { + if (arguments.length === 0) return this._name; + this._name = str; + return this; +}; + +/** + * Return prepared commands. + * + * @return {Array} + * @api private + */ + +Command.prototype.prepareCommands = function() { + return this.commands.filter(function(cmd) { + return !cmd._noHelp; + }).map(function(cmd) { + var args = cmd._args.map(function(arg) { + return humanReadableArgName(arg); + }).join(' '); + + return [ + cmd._name + + (cmd._alias ? '|' + cmd._alias : '') + + (cmd.options.length ? ' [options]' : '') + + (args ? ' ' + args : ''), + cmd._description + ]; + }); +}; + +/** + * Return the largest command length. + * + * @return {Number} + * @api private + */ + +Command.prototype.largestCommandLength = function() { + var commands = this.prepareCommands(); + return commands.reduce(function(max, command) { + return Math.max(max, command[0].length); + }, 0); +}; + +/** + * Return the largest option length. + * + * @return {Number} + * @api private + */ + +Command.prototype.largestOptionLength = function() { + var options = [].slice.call(this.options); + options.push({ + flags: this._helpFlags + }); + + return options.reduce(function(max, option) { + return Math.max(max, option.flags.length); + }, 0); +}; + +/** + * Return the largest arg length. + * + * @return {Number} + * @api private + */ + +Command.prototype.largestArgLength = function() { + return this._args.reduce(function(max, arg) { + return Math.max(max, arg.name.length); + }, 0); +}; + +/** + * Return the pad width. + * + * @return {Number} + * @api private + */ + +Command.prototype.padWidth = function() { + var width = this.largestOptionLength(); + if (this._argsDescription && this._args.length) { + if (this.largestArgLength() > width) { + width = this.largestArgLength(); + } + } + + if (this.commands && this.commands.length) { + if (this.largestCommandLength() > width) { + width = this.largestCommandLength(); + } + } + + return width; +}; + +/** + * Return help for options. + * + * @return {String} + * @api private + */ + +Command.prototype.optionHelp = function() { + var width = this.padWidth(); + + var columns = process.stdout.columns || 80; + var descriptionWidth = columns - width - 4; + + // Append the help information + return this.options.map(function(option) { + const fullDesc = option.description + + ((!option.negate && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : ''); + return pad(option.flags, width) + ' ' + optionalWrap(fullDesc, descriptionWidth, width + 2); + }).concat([pad(this._helpFlags, width) + ' ' + optionalWrap(this._helpDescription, descriptionWidth, width + 2)]) + .join('\n'); +}; + +/** + * Return command help documentation. + * + * @return {String} + * @api private + */ + +Command.prototype.commandHelp = function() { + if (!this.commands.length) return ''; + + var commands = this.prepareCommands(); + var width = this.padWidth(); + + var columns = process.stdout.columns || 80; + var descriptionWidth = columns - width - 4; + + return [ + 'Commands:', + commands.map(function(cmd) { + var desc = cmd[1] ? ' ' + cmd[1] : ''; + return (desc ? pad(cmd[0], width) : cmd[0]) + optionalWrap(desc, descriptionWidth, width + 2); + }).join('\n').replace(/^/gm, ' '), + '' + ].join('\n'); +}; + +/** + * Return program help documentation. + * + * @return {String} + * @api private + */ + +Command.prototype.helpInformation = function() { + var desc = []; + if (this._description) { + desc = [ + this._description, + '' + ]; + + var argsDescription = this._argsDescription; + if (argsDescription && this._args.length) { + var width = this.padWidth(); + var columns = process.stdout.columns || 80; + var descriptionWidth = columns - width - 5; + desc.push('Arguments:'); + desc.push(''); + this._args.forEach(function(arg) { + desc.push(' ' + pad(arg.name, width) + ' ' + wrap(argsDescription[arg.name], descriptionWidth, width + 4)); + }); + desc.push(''); + } + } + + var cmdName = this._name; + if (this._alias) { + cmdName = cmdName + '|' + this._alias; + } + var parentCmdNames = ''; + for (var parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) { + parentCmdNames = parentCmd.name() + ' ' + parentCmdNames; + } + var usage = [ + 'Usage: ' + parentCmdNames + cmdName + ' ' + this.usage(), + '' + ]; + + var cmds = []; + var commandHelp = this.commandHelp(); + if (commandHelp) cmds = [commandHelp]; + + var options = [ + 'Options:', + '' + this.optionHelp().replace(/^/gm, ' '), + '' + ]; + + return usage + .concat(desc) + .concat(options) + .concat(cmds) + .join('\n'); +}; + +/** + * Output help information for this command. + * + * When listener(s) are available for the helpLongFlag + * those callbacks are invoked. + * + * @api public + */ + +Command.prototype.outputHelp = function(cb) { + if (!cb) { + cb = function(passthru) { + return passthru; + }; + } + const cbOutput = cb(this.helpInformation()); + if (typeof cbOutput !== 'string' && !Buffer.isBuffer(cbOutput)) { + throw new Error('outputHelp callback must return a string or a Buffer'); + } + process.stdout.write(cbOutput); + this.emit(this._helpLongFlag); +}; + +/** + * You can pass in flags and a description to override the help + * flags and help description for your command. + * + * @param {String} [flags] + * @param {String} [description] + * @return {Command} + * @api public + */ + +Command.prototype.helpOption = function(flags, description) { + this._helpFlags = flags || this._helpFlags; + this._helpDescription = description || this._helpDescription; + + var splitFlags = this._helpFlags.split(/[ ,|]+/); + + if (splitFlags.length > 1) this._helpShortFlag = splitFlags.shift(); + + this._helpLongFlag = splitFlags.shift(); + + return this; +}; + +/** + * Output help information and exit. + * + * @param {Function} [cb] + * @api public + */ + +Command.prototype.help = function(cb) { + this.outputHelp(cb); + // exitCode: preserving original behaviour which was calling process.exit() + // message: do not have all displayed text available so only passing placeholder. + this._exit(process.exitCode || 0, 'commander.help', '(outputHelp)'); +}; + +/** + * Camel-case the given `flag` + * + * @param {String} flag + * @return {String} + * @api private + */ + +function camelcase(flag) { + return flag.split('-').reduce(function(str, word) { + return str + word[0].toUpperCase() + word.slice(1); + }); +} + +/** + * Pad `str` to `width`. + * + * @param {String} str + * @param {Number} width + * @return {String} + * @api private + */ + +function pad(str, width) { + var len = Math.max(0, width - str.length); + return str + Array(len + 1).join(' '); +} + +/** + * Wraps the given string with line breaks at the specified width while breaking + * words and indenting every but the first line on the left. + * + * @param {String} str + * @param {Number} width + * @param {Number} indent + * @return {String} + * @api private + */ +function wrap(str, width, indent) { + var regex = new RegExp('.{1,' + (width - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g'); + var lines = str.match(regex) || []; + return lines.map(function(line, i) { + if (line.slice(-1) === '\n') { + line = line.slice(0, line.length - 1); + } + return ((i > 0 && indent) ? Array(indent + 1).join(' ') : '') + line.trimRight(); + }).join('\n'); +} + +/** + * Optionally wrap the given str to a max width of width characters per line + * while indenting with indent spaces. Do not wrap if insufficient width or + * string is manually formatted. + * + * @param {String} str + * @param {Number} width + * @param {Number} indent + * @return {String} + * @api private + */ +function optionalWrap(str, width, indent) { + // Detect manually wrapped and indented strings by searching for line breaks + // followed by multiple spaces/tabs. + if (str.match(/[\n]\s+/)) return str; + // Do not wrap to narrow columns (or can end up with a word per line). + const minWidth = 40; + if (width < minWidth) return str; + + return wrap(str, width, indent); +} + +/** + * Output help information if help flags specified + * + * @param {Command} cmd - command to output help for + * @param {Array} options - array of options to search for -h or --help + * @api private + */ + +function outputHelpIfRequested(cmd, options) { + options = options || []; + + for (var i = 0; i < options.length; i++) { + if (options[i] === cmd._helpLongFlag || options[i] === cmd._helpShortFlag) { + cmd.outputHelp(); + // (Do not have all displayed text available so only passing placeholder.) + cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)'); + } + } +} + +/** + * Takes an argument and returns its human readable equivalent for help usage. + * + * @param {Object} arg + * @return {String} + * @api private + */ + +function humanReadableArgName(arg) { + var nameOutput = arg.name + (arg.variadic === true ? '...' : ''); + + return arg.required + ? '<' + nameOutput + '>' + : '[' + nameOutput + ']'; +} + +// for versions before node v0.8 when there weren't `fs.existsSync` +function exists(file) { + try { + if (fs.statSync(file).isFile()) { + return true; + } + } catch (e) { + return false; + } +} + +/** + * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command). + * + * @param {string[]} args - array of arguments from node.execArgv + * @returns {string[]} + * @api private + */ + +function incrementNodeInspectorPort(args) { + // Testing for these options: + // --inspect[=[host:]port] + // --inspect-brk[=[host:]port] + // --inspect-port=[host:]port + return args.map((arg) => { + var result = arg; + if (arg.indexOf('--inspect') === 0) { + var debugOption; + var debugHost = '127.0.0.1'; + var debugPort = '9229'; + var match; + if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) { + // e.g. --inspect + debugOption = match[1]; + } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) { + debugOption = match[1]; + if (/^\d+$/.test(match[3])) { + // e.g. --inspect=1234 + debugPort = match[3]; + } else { + // e.g. --inspect=localhost + debugHost = match[3]; + } + } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) { + // e.g. --inspect=localhost:1234 + debugOption = match[1]; + debugHost = match[3]; + debugPort = match[4]; + } + + if (debugOption && debugPort !== '0') { + result = `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`; + } + } + return result; + }); +} diff --git a/node_modules/commander/package.json b/node_modules/commander/package.json new file mode 100644 index 000000000..e4781e5b6 --- /dev/null +++ b/node_modules/commander/package.json @@ -0,0 +1,41 @@ +{ + "name": "commander", + "version": "4.1.1", + "description": "the complete solution for node.js command-line programs", + "keywords": [ + "commander", + "command", + "option", + "parser" + ], + "author": "TJ Holowaychuk ", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/tj/commander.js.git" + }, + "scripts": { + "lint": "eslint index.js \"tests/**/*.js\"", + "test": "jest && npm run test-typings", + "test-typings": "tsc -p tsconfig.json" + }, + "main": "index", + "files": [ + "index.js", + "typings/index.d.ts" + ], + "dependencies": {}, + "devDependencies": { + "@types/jest": "^24.0.23", + "@types/node": "^12.12.11", + "eslint": "^6.7.0", + "eslint-plugin-jest": "^22.21.0", + "jest": "^24.8.0", + "standard": "^14.3.1", + "typescript": "^3.7.2" + }, + "typings": "typings/index.d.ts", + "engines": { + "node": ">= 6" + } +} diff --git a/node_modules/commander/typings/index.d.ts b/node_modules/commander/typings/index.d.ts new file mode 100644 index 000000000..082a3a3c2 --- /dev/null +++ b/node_modules/commander/typings/index.d.ts @@ -0,0 +1,311 @@ +// Type definitions for commander +// Original definitions by: Alan Agius , Marcelo Dezem , vvakame , Jules Randolph + +/// + +declare namespace commander { + + interface CommanderError extends Error { + code: string; + exitCode: number; + message: string; + nestedError?: string; + } + type CommanderErrorConstructor = { new (exitCode: number, code: string, message: string): CommanderError }; + + interface Option { + flags: string; + required: boolean; // A value must be supplied when the option is specified. + optional: boolean; // A value is optional when the option is specified. + mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line. + bool: boolean; + short?: string; + long: string; + description: string; + } + type OptionConstructor = { new (flags: string, description?: string): Option }; + + interface Command extends NodeJS.EventEmitter { + [key: string]: any; // options as properties + + args: string[]; + + /** + * Set the program version to `str`. + * + * This method auto-registers the "-V, --version" flag + * which will print the version number when passed. + * + * You can optionally supply the flags and description to override the defaults. + */ + version(str: string, flags?: string, description?: string): Command; + + /** + * Define a command, implemented using an action handler. + * + * @remarks + * The command description is supplied using `.description`, not as a parameter to `.command`. + * + * @example + * ```ts + * program + * .command('clone [destination]') + * .description('clone a repository into a newly created directory') + * .action((source, destination) => { + * console.log('clone command called'); + * }); + * ``` + * + * @param nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...` + * @param opts - configuration options + * @returns new command + */ + command(nameAndArgs: string, opts?: CommandOptions): Command; + /** + * Define a command, implemented in a separate executable file. + * + * @remarks + * The command description is supplied as the second parameter to `.command`. + * + * @example + * ```ts + * program + * .command('start ', 'start named service') + * .command('stop [service]', 'stop named serice, or all if no name supplied'); + * ``` + * + * @param nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...` + * @param description - description of executable command + * @param opts - configuration options + * @returns top level command for chaining more command definitions + */ + command(nameAndArgs: string, description: string, opts?: commander.CommandOptions): Command; + + /** + * Define argument syntax for the top-level command. + * + * @returns Command for chaining + */ + arguments(desc: string): Command; + + /** + * Parse expected `args`. + * + * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. + * + * @returns Command for chaining + */ + parseExpectedArgs(args: string[]): Command; + + /** + * Register callback to use as replacement for calling process.exit. + */ + exitOverride(callback?: (err: CommanderError) => never|void): Command; + + /** + * Register callback `fn` for the command. + * + * @example + * program + * .command('help') + * .description('display verbose help') + * .action(function() { + * // output help here + * }); + * + * @returns Command for chaining + */ + action(fn: (...args: any[]) => void | Promise): Command; + + /** + * Define option with `flags`, `description` and optional + * coercion `fn`. + * + * The `flags` string should contain both the short and long flags, + * separated by comma, a pipe or space. The following are all valid + * all will output this way when `--help` is used. + * + * "-p, --pepper" + * "-p|--pepper" + * "-p --pepper" + * + * @example + * // simple boolean defaulting to false + * program.option('-p, --pepper', 'add pepper'); + * + * --pepper + * program.pepper + * // => Boolean + * + * // simple boolean defaulting to true + * program.option('-C, --no-cheese', 'remove cheese'); + * + * program.cheese + * // => true + * + * --no-cheese + * program.cheese + * // => false + * + * // required argument + * program.option('-C, --chdir ', 'change the working directory'); + * + * --chdir /tmp + * program.chdir + * // => "/tmp" + * + * // optional argument + * program.option('-c, --cheese [type]', 'add cheese [marble]'); + * + * @returns Command for chaining + */ + option(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command; + option(flags: string, description?: string, defaultValue?: any): Command; + + /** + * Define a required option, which must have a value after parsing. This usually means + * the option must be specified on the command line. (Otherwise the same as .option().) + * + * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space. + */ + requiredOption(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command; + requiredOption(flags: string, description?: string, defaultValue?: any): Command; + + + /** + * Whether to store option values as properties on command object, + * or store separately (specify false). In both cases the option values can be accessed using .opts(). + * + * @return Command for chaining + */ + storeOptionsAsProperties(value?: boolean): Command; + + /** + * Whether to pass command to action handler, + * or just the options (specify false). + * + * @return Command for chaining + */ + passCommandToAction(value?: boolean): Command; + + /** + * Allow unknown options on the command line. + * + * @param [arg] if `true` or omitted, no error will be thrown for unknown options. + * @returns Command for chaining + */ + allowUnknownOption(arg?: boolean): Command; + + /** + * Parse `argv`, setting options and invoking commands when defined. + * + * @returns Command for chaining + */ + parse(argv: string[]): Command; + + /** + * Parse `argv`, setting options and invoking commands when defined. + * + * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise. + * + * @returns Promise + */ + parseAsync(argv: string[]): Promise; + + /** + * Parse options from `argv` returning `argv` void of these options. + */ + parseOptions(argv: string[]): commander.ParseOptionsResult; + + /** + * Return an object containing options as key-value pairs + */ + opts(): { [key: string]: any }; + + /** + * Set the description. + * + * @returns Command for chaining + */ + description(str: string, argsDescription?: {[argName: string]: string}): Command; + /** + * Get the description. + */ + description(): string; + + /** + * Set an alias for the command. + * + * @returns Command for chaining + */ + alias(alias: string): Command; + /** + * Get alias for the command. + */ + alias(): string; + + /** + * Set the command usage. + * + * @returns Command for chaining + */ + usage(str: string): Command; + /** + * Get the command usage. + */ + usage(): string; + + /** + * Set the name of the command. + * + * @returns Command for chaining + */ + name(str: string): Command; + /** + * Get the name of the command. + */ + name(): string; + + /** + * Output help information for this command. + * + * When listener(s) are available for the helpLongFlag + * those callbacks are invoked. + */ + outputHelp(cb?: (str: string) => string): void; + + /** + * You can pass in flags and a description to override the help + * flags and help description for your command. + */ + helpOption(flags?: string, description?: string): Command; + + /** + * Output help information and exit. + */ + help(cb?: (str: string) => string): never; + } + type CommandConstructor = { new (name?: string): Command }; + + + interface CommandOptions { + noHelp?: boolean; + isDefault?: boolean; + executableFile?: string; + } + + interface ParseOptionsResult { + args: string[]; + unknown: string[]; + } + + interface CommanderStatic extends Command { + Command: CommandConstructor; + Option: OptionConstructor; + CommanderError:CommanderErrorConstructor; + } + +} + +declare const commander: commander.CommanderStatic; +export = commander; diff --git a/node_modules/cookiejar/LICENSE b/node_modules/cookiejar/LICENSE new file mode 100644 index 000000000..58a23ecee --- /dev/null +++ b/node_modules/cookiejar/LICENSE @@ -0,0 +1,9 @@ +The MIT License (MIT) +Copyright (c) 2013 Bradley Meck + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/cookiejar/cookiejar.js b/node_modules/cookiejar/cookiejar.js new file mode 100644 index 000000000..df2925cdb --- /dev/null +++ b/node_modules/cookiejar/cookiejar.js @@ -0,0 +1,281 @@ +/* jshint node: true */ +(function () { + "use strict"; + + function CookieAccessInfo(domain, path, secure, script) { + if (this instanceof CookieAccessInfo) { + this.domain = domain || undefined; + this.path = path || "/"; + this.secure = !!secure; + this.script = !!script; + return this; + } + return new CookieAccessInfo(domain, path, secure, script); + } + CookieAccessInfo.All = Object.freeze(Object.create(null)); + exports.CookieAccessInfo = CookieAccessInfo; + + function Cookie(cookiestr, request_domain, request_path) { + if (cookiestr instanceof Cookie) { + return cookiestr; + } + if (this instanceof Cookie) { + this.name = null; + this.value = null; + this.expiration_date = Infinity; + this.path = String(request_path || "/"); + this.explicit_path = false; + this.domain = request_domain || null; + this.explicit_domain = false; + this.secure = false; //how to define default? + this.noscript = false; //httponly + if (cookiestr) { + this.parse(cookiestr, request_domain, request_path); + } + return this; + } + return new Cookie(cookiestr, request_domain, request_path); + } + exports.Cookie = Cookie; + + Cookie.prototype.toString = function toString() { + var str = [this.name + "=" + this.value]; + if (this.expiration_date !== Infinity) { + str.push("expires=" + (new Date(this.expiration_date)).toGMTString()); + } + if (this.domain) { + str.push("domain=" + this.domain); + } + if (this.path) { + str.push("path=" + this.path); + } + if (this.secure) { + str.push("secure"); + } + if (this.noscript) { + str.push("httponly"); + } + return str.join("; "); + }; + + Cookie.prototype.toValueString = function toValueString() { + return this.name + "=" + this.value; + }; + + var cookie_str_splitter = /[:](?=\s*[a-zA-Z0-9_\-]+\s*[=])/g; + Cookie.prototype.parse = function parse(str, request_domain, request_path) { + if (this instanceof Cookie) { + if ( str.length > 32768 ) { + console.warn("Cookie too long for parsing (>32768 characters)"); + return; + } + + var parts = str.split(";").filter(function (value) { + return !!value; + }); + var i; + + var pair = parts[0].match(/([^=]+)=([\s\S]*)/); + if (!pair) { + console.warn("Invalid cookie header encountered. Header: '"+str+"'"); + return; + } + + var key = pair[1]; + var value = pair[2]; + if ( typeof key !== 'string' || key.length === 0 || typeof value !== 'string' ) { + console.warn("Unable to extract values from cookie header. Cookie: '"+str+"'"); + return; + } + + this.name = key; + this.value = value; + + for (i = 1; i < parts.length; i += 1) { + pair = parts[i].match(/([^=]+)(?:=([\s\S]*))?/); + key = pair[1].trim().toLowerCase(); + value = pair[2]; + switch (key) { + case "httponly": + this.noscript = true; + break; + case "expires": + this.expiration_date = value ? + Number(Date.parse(value)) : + Infinity; + break; + case "path": + this.path = value ? + value.trim() : + ""; + this.explicit_path = true; + break; + case "domain": + this.domain = value ? + value.trim() : + ""; + this.explicit_domain = !!this.domain; + break; + case "secure": + this.secure = true; + break; + } + } + + if (!this.explicit_path) { + this.path = request_path || "/"; + } + if (!this.explicit_domain) { + this.domain = request_domain; + } + + return this; + } + return new Cookie().parse(str, request_domain, request_path); + }; + + Cookie.prototype.matches = function matches(access_info) { + if (access_info === CookieAccessInfo.All) { + return true; + } + if (this.noscript && access_info.script || + this.secure && !access_info.secure || + !this.collidesWith(access_info)) { + return false; + } + return true; + }; + + Cookie.prototype.collidesWith = function collidesWith(access_info) { + if ((this.path && !access_info.path) || (this.domain && !access_info.domain)) { + return false; + } + if (this.path && access_info.path.indexOf(this.path) !== 0) { + return false; + } + if (this.explicit_path && access_info.path.indexOf( this.path ) !== 0) { + return false; + } + var access_domain = access_info.domain && access_info.domain.replace(/^[\.]/,''); + var cookie_domain = this.domain && this.domain.replace(/^[\.]/,''); + if (cookie_domain === access_domain) { + return true; + } + if (cookie_domain) { + if (!this.explicit_domain) { + return false; // we already checked if the domains were exactly the same + } + var wildcard = access_domain.indexOf(cookie_domain); + if (wildcard === -1 || wildcard !== access_domain.length - cookie_domain.length) { + return false; + } + return true; + } + return true; + }; + + function CookieJar() { + var cookies, cookies_list, collidable_cookie; + if (this instanceof CookieJar) { + cookies = Object.create(null); //name: [Cookie] + + this.setCookie = function setCookie(cookie, request_domain, request_path) { + var remove, i; + cookie = new Cookie(cookie, request_domain, request_path); + //Delete the cookie if the set is past the current time + remove = cookie.expiration_date <= Date.now(); + if (cookies[cookie.name] !== undefined) { + cookies_list = cookies[cookie.name]; + for (i = 0; i < cookies_list.length; i += 1) { + collidable_cookie = cookies_list[i]; + if (collidable_cookie.collidesWith(cookie)) { + if (remove) { + cookies_list.splice(i, 1); + if (cookies_list.length === 0) { + delete cookies[cookie.name]; + } + return false; + } + cookies_list[i] = cookie; + return cookie; + } + } + if (remove) { + return false; + } + cookies_list.push(cookie); + return cookie; + } + if (remove) { + return false; + } + cookies[cookie.name] = [cookie]; + return cookies[cookie.name]; + }; + //returns a cookie + this.getCookie = function getCookie(cookie_name, access_info) { + var cookie, i; + cookies_list = cookies[cookie_name]; + if (!cookies_list) { + return; + } + for (i = 0; i < cookies_list.length; i += 1) { + cookie = cookies_list[i]; + if (cookie.expiration_date <= Date.now()) { + if (cookies_list.length === 0) { + delete cookies[cookie.name]; + } + continue; + } + + if (cookie.matches(access_info)) { + return cookie; + } + } + }; + //returns a list of cookies + this.getCookies = function getCookies(access_info) { + var matches = [], cookie_name, cookie; + for (cookie_name in cookies) { + cookie = this.getCookie(cookie_name, access_info); + if (cookie) { + matches.push(cookie); + } + } + matches.toString = function toString() { + return matches.join(":"); + }; + matches.toValueString = function toValueString() { + return matches.map(function (c) { + return c.toValueString(); + }).join('; '); + }; + return matches; + }; + + return this; + } + return new CookieJar(); + } + exports.CookieJar = CookieJar; + + //returns list of cookies that were set correctly. Cookies that are expired and removed are not returned. + CookieJar.prototype.setCookies = function setCookies(cookies, request_domain, request_path) { + cookies = Array.isArray(cookies) ? + cookies : + cookies.split(cookie_str_splitter); + var successful = [], + i, + cookie; + cookies = cookies.map(function(item){ + return new Cookie(item, request_domain, request_path); + }); + for (i = 0; i < cookies.length; i += 1) { + cookie = cookies[i]; + if (this.setCookie(cookie, request_domain, request_path)) { + successful.push(cookie); + } + } + return successful; + }; +}()); diff --git a/node_modules/cookiejar/package.json b/node_modules/cookiejar/package.json new file mode 100644 index 000000000..be1316f92 --- /dev/null +++ b/node_modules/cookiejar/package.json @@ -0,0 +1,26 @@ +{ + "name": "cookiejar", + "version": "2.1.4", + "author": { + "name": "bradleymeck" + }, + "main": "cookiejar.js", + "description": "simple persistent cookiejar system", + "files": [ + "cookiejar.js" + ], + "license": "MIT", + "jshintConfig": { + "node": true + }, + "scripts": { + "test": "node tests/test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/bmeck/node-cookiejar.git" + }, + "devDependencies": { + "jshint": "^2.9.4" + } +} diff --git a/node_modules/cookiejar/readme.md b/node_modules/cookiejar/readme.md new file mode 100644 index 000000000..71a9f233b --- /dev/null +++ b/node_modules/cookiejar/readme.md @@ -0,0 +1,60 @@ +# CookieJar + +[![NPM version](http://img.shields.io/npm/v/cookiejar.svg)](https://www.npmjs.org/package/cookiejar) +[![devDependency Status](https://david-dm.org/bmeck/node-cookiejar/dev-status.svg)](https://david-dm.org/bmeck/node-cookiejar?type=dev) + +Simple robust cookie library + +## Exports + +### CookieAccessInfo(domain,path,secure,script) + +class to determine matching qualities of a cookie + +##### Properties + +* String domain - domain to match +* String path - path to match +* Boolean secure - access is secure (ssl generally) +* Boolean script - access is from a script + + +### Cookie(cookiestr_or_cookie, request_domain, request_path) + +It turns input into a Cookie (singleton if given a Cookie), +the `request_domain` argument is used to default the domain if it is not explicit in the cookie string, +the `request_path` argument is used to set the path if it is not explicit in a cookie String. + +Explicit domains/paths will cascade, implied domains/paths must *exactly* match (see http://en.wikipedia.org/wiki/HTTP_cookie#Domain_and_Pat). + +##### Properties + +* String name - name of the cookie +* String value - string associated with the cookie +* String domain - domain to match (on a cookie a '.' at the start means a wildcard matching anything ending in the rest) +* Boolean explicit_domain - if the domain was explicitly set via the cookie string +* String path - base path to match (matches any path starting with this '/' is root) +* Boolean explicit_path - if the path was explicitly set via the cookie string +* Boolean noscript - if it should be kept from scripts +* Boolean secure - should it only be transmitted over secure means +* Number expiration_date - number of millis since 1970 at which this should be removed + +##### Methods + +* `String toString()` - the __set-cookie:__ string for this cookie +* `String toValueString()` - the __cookie:__ string for this cookie +* `Cookie parse(cookiestr, request_domain, request_path)` - parses the string onto this cookie or a new one if called directly +* `Boolean matches(access_info)` - returns true if the access_info allows retrieval of this cookie +* `Boolean collidesWith(cookie)` - returns true if the cookies cannot exist in the same space (domain and path match) + + +### CookieJar() + +class to hold numerous cookies from multiple domains correctly + +##### Methods + +* `Cookie setCookie(cookie, request_domain, request_path)` - modify (or add if not already-existing) a cookie to the jar +* `Cookie[] setCookies(cookiestr_or_list, request_domain, request_path)` - modify (or add if not already-existing) a large number of cookies to the jar +* `Cookie getCookie(cookie_name,access_info)` - get a cookie with the name and access_info matching +* `Cookie[] getCookies(access_info)` - grab all cookies matching this access_info diff --git a/node_modules/define-data-property/.eslintrc b/node_modules/define-data-property/.eslintrc new file mode 100644 index 000000000..75443e81e --- /dev/null +++ b/node_modules/define-data-property/.eslintrc @@ -0,0 +1,24 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "complexity": 0, + "id-length": 0, + "new-cap": ["error", { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "max-lines-per-function": "off", + }, + }, + ], +} diff --git a/node_modules/define-data-property/.github/FUNDING.yml b/node_modules/define-data-property/.github/FUNDING.yml new file mode 100644 index 000000000..3e17725dd --- /dev/null +++ b/node_modules/define-data-property/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/define-data-property +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/define-data-property/.nycrc b/node_modules/define-data-property/.nycrc new file mode 100644 index 000000000..1826526e0 --- /dev/null +++ b/node_modules/define-data-property/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/define-data-property/CHANGELOG.md b/node_modules/define-data-property/CHANGELOG.md new file mode 100644 index 000000000..4eed75ea9 --- /dev/null +++ b/node_modules/define-data-property/CHANGELOG.md @@ -0,0 +1,70 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.4](https://github.com/ljharb/define-data-property/compare/v1.1.3...v1.1.4) - 2024-02-13 + +### Commits + +- [Refactor] use `es-define-property` [`90f2f4c`](https://github.com/ljharb/define-data-property/commit/90f2f4cc20298401e71c28e1e08888db12021453) +- [Dev Deps] update `@types/object.getownpropertydescriptors` [`cd929d9`](https://github.com/ljharb/define-data-property/commit/cd929d9a04f5f2fdcfa9d5be140940b91a083153) + +## [v1.1.3](https://github.com/ljharb/define-data-property/compare/v1.1.2...v1.1.3) - 2024-02-12 + +### Commits + +- [types] hand-write d.ts instead of emitting it [`0cbc988`](https://github.com/ljharb/define-data-property/commit/0cbc988203c105f2d97948327c7167ebd33bd318) +- [meta] simplify `exports` [`690781e`](https://github.com/ljharb/define-data-property/commit/690781eed28bbf2d6766237efda0ba6dd591609e) +- [Dev Deps] update `hasown`; clean up DT packages [`6cdfd1c`](https://github.com/ljharb/define-data-property/commit/6cdfd1cb2d91d791bfd18cda5d5cab232fd5d8fc) +- [actions] cleanup [`3142bc6`](https://github.com/ljharb/define-data-property/commit/3142bc6a4bc406a51f5b04f31e98562a27f35ffd) +- [meta] add `funding` [`8474423`](https://github.com/ljharb/define-data-property/commit/847442391a79779af3e0f1bf0b5bb923552b7804) +- [Deps] update `get-intrinsic` [`3e9be00`](https://github.com/ljharb/define-data-property/commit/3e9be00e07784ba34e7c77d8bc0fdbc832ad61de) + +## [v1.1.2](https://github.com/ljharb/define-data-property/compare/v1.1.1...v1.1.2) - 2024-02-05 + +### Commits + +- [Dev Deps] update @types packages, `object-inspect`, `tape`, `typescript` [`df41bf8`](https://github.com/ljharb/define-data-property/commit/df41bf84ca3456be6226055caab44e38e3a7fd2f) +- [Dev Deps] update DT packages, `aud`, `npmignore`, `tape`, typescript` [`fab0e4e`](https://github.com/ljharb/define-data-property/commit/fab0e4ec709ee02b79f42d6db3ee5f26e0a34b8a) +- [Dev Deps] use `hasown` instead of `has` [`aa51ef9`](https://github.com/ljharb/define-data-property/commit/aa51ef93f6403d49d9bb72a807bcdb6e418978c0) +- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`d89be50`](https://github.com/ljharb/define-data-property/commit/d89be50571175888d391238605122679f7e65ffc) +- [Deps] update `has-property-descriptors` [`7af887c`](https://github.com/ljharb/define-data-property/commit/7af887c9083b59b195b0079e04815cfed9fcee2b) +- [Deps] update `get-intrinsic` [`bb8728e`](https://github.com/ljharb/define-data-property/commit/bb8728ec42cd998505a7157ae24853a560c20646) + +## [v1.1.1](https://github.com/ljharb/define-data-property/compare/v1.1.0...v1.1.1) - 2023-10-12 + +### Commits + +- [Tests] fix tests in ES3 engines [`5c6920e`](https://github.com/ljharb/define-data-property/commit/5c6920edd1f52f675b02f417e539c28135b43f94) +- [Dev Deps] update `@types/es-value-fixtures`, `@types/for-each`, `@types/gopd`, `@types/has-property-descriptors`, `tape`, `typescript` [`7d82dfc`](https://github.com/ljharb/define-data-property/commit/7d82dfc20f778b4465bba06335dd53f6f431aea3) +- [Fix] IE 8 has a broken `Object.defineProperty` [`0672e1a`](https://github.com/ljharb/define-data-property/commit/0672e1af2a9fcc787e7c23b96dea60d290df5548) +- [meta] emit types on prepack [`73acb1f`](https://github.com/ljharb/define-data-property/commit/73acb1f903c21b314ec7156bf10f73c7910530c0) +- [Dev Deps] update `tape`, `typescript` [`9489a77`](https://github.com/ljharb/define-data-property/commit/9489a7738bf2ecf0ac71d5b78ec4ca6ad7ba0142) + +## [v1.1.0](https://github.com/ljharb/define-data-property/compare/v1.0.1...v1.1.0) - 2023-09-13 + +### Commits + +- [New] add `loose` arg [`155235a`](https://github.com/ljharb/define-data-property/commit/155235a4c4d7741f6de01cd87c99599a56654b72) +- [New] allow `null` to be passed for the non* args [`7d2fa5f`](https://github.com/ljharb/define-data-property/commit/7d2fa5f06be0392736c13b126f7cd38979f34792) + +## [v1.0.1](https://github.com/ljharb/define-data-property/compare/v1.0.0...v1.0.1) - 2023-09-12 + +### Commits + +- [meta] add TS types [`43d763c`](https://github.com/ljharb/define-data-property/commit/43d763c6c883f652de1c9c02ef6216ee507ffa69) +- [Dev Deps] update `@types/tape`, `typescript` [`f444985`](https://github.com/ljharb/define-data-property/commit/f444985811c36f3e6448a03ad2f9b7898917f4c7) +- [meta] add `safe-publish-latest`, [`172bb10`](https://github.com/ljharb/define-data-property/commit/172bb10890896ebb160e64398f6ee55760107bee) + +## v1.0.0 - 2023-09-12 + +### Commits + +- Initial implementation, tests, readme [`5b43d6b`](https://github.com/ljharb/define-data-property/commit/5b43d6b44e675a904810467a7d4e0adb7efc3196) +- Initial commit [`35e577a`](https://github.com/ljharb/define-data-property/commit/35e577a6ba59a98befa97776d70d90f3bea9009d) +- npm init [`82a0a04`](https://github.com/ljharb/define-data-property/commit/82a0a04a321ca7de220af02d41e2745e8a9962ed) +- Only apps should have lockfiles [`96df244`](https://github.com/ljharb/define-data-property/commit/96df244a3c6f426f9a2437be825d1c6f5dd7158e) +- [meta] use `npmignore` to autogenerate an npmignore file [`a87ff18`](https://github.com/ljharb/define-data-property/commit/a87ff18cb79e14c2eb5720486c4759fd9a189375) diff --git a/node_modules/define-data-property/LICENSE b/node_modules/define-data-property/LICENSE new file mode 100644 index 000000000..b4213ac64 --- /dev/null +++ b/node_modules/define-data-property/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/define-data-property/README.md b/node_modules/define-data-property/README.md new file mode 100644 index 000000000..f2304daef --- /dev/null +++ b/node_modules/define-data-property/README.md @@ -0,0 +1,67 @@ +# define-data-property [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Define a data property on an object. Will fall back to assignment in an engine without descriptors. + +The three `non*` argument can also be passed `null`, which will use the existing state if available. + +The `loose` argument will mean that if you attempt to set a non-normal data property, in an environment without descriptor support, it will fall back to normal assignment. + +## Usage + +```javascript +var defineDataProperty = require('define-data-property'); +var assert = require('assert'); + +var obj = {}; +defineDataProperty(obj, 'key', 'value'); +defineDataProperty( + obj, + 'key2', + 'value', + true, // nonEnumerable, optional + false, // nonWritable, optional + true, // nonConfigurable, optional + false // loose, optional +); + +assert.deepEqual( + Object.getOwnPropertyDescriptors(obj), + { + key: { + configurable: true, + enumerable: true, + value: 'value', + writable: true, + }, + key2: { + configurable: false, + enumerable: false, + value: 'value', + writable: true, + }, + } +); +``` + +[package-url]: https://npmjs.org/package/define-data-property +[npm-version-svg]: https://versionbadg.es/ljharb/define-data-property.svg +[deps-svg]: https://david-dm.org/ljharb/define-data-property.svg +[deps-url]: https://david-dm.org/ljharb/define-data-property +[dev-deps-svg]: https://david-dm.org/ljharb/define-data-property/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/define-data-property#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/define-data-property.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/define-data-property.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/define-data-property.svg +[downloads-url]: https://npm-stat.com/charts.html?package=define-data-property +[codecov-image]: https://codecov.io/gh/ljharb/define-data-property/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/define-data-property/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/define-data-property +[actions-url]: https://github.com/ljharb/define-data-property/actions diff --git a/node_modules/define-data-property/index.d.ts b/node_modules/define-data-property/index.d.ts new file mode 100644 index 000000000..b56a77da8 --- /dev/null +++ b/node_modules/define-data-property/index.d.ts @@ -0,0 +1,12 @@ + +declare function defineDataProperty( + obj: Record, + property: keyof typeof obj, + value: typeof obj[typeof property], + nonEnumerable?: boolean | null, + nonWritable?: boolean | null, + nonConfigurable?: boolean | null, + loose?: boolean +): void; + +export = defineDataProperty; \ No newline at end of file diff --git a/node_modules/define-data-property/index.js b/node_modules/define-data-property/index.js new file mode 100644 index 000000000..e1a38c07b --- /dev/null +++ b/node_modules/define-data-property/index.js @@ -0,0 +1,56 @@ +'use strict'; + +var $defineProperty = require('es-define-property'); + +var $SyntaxError = require('es-errors/syntax'); +var $TypeError = require('es-errors/type'); + +var gopd = require('gopd'); + +/** @type {import('.')} */ +module.exports = function defineDataProperty( + obj, + property, + value +) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new $TypeError('`obj` must be an object or a function`'); + } + if (typeof property !== 'string' && typeof property !== 'symbol') { + throw new $TypeError('`property` must be a string or a symbol`'); + } + if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) { + throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null'); + } + if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) { + throw new $TypeError('`nonWritable`, if provided, must be a boolean or null'); + } + if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) { + throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null'); + } + if (arguments.length > 6 && typeof arguments[6] !== 'boolean') { + throw new $TypeError('`loose`, if provided, must be a boolean'); + } + + var nonEnumerable = arguments.length > 3 ? arguments[3] : null; + var nonWritable = arguments.length > 4 ? arguments[4] : null; + var nonConfigurable = arguments.length > 5 ? arguments[5] : null; + var loose = arguments.length > 6 ? arguments[6] : false; + + /* @type {false | TypedPropertyDescriptor} */ + var desc = !!gopd && gopd(obj, property); + + if ($defineProperty) { + $defineProperty(obj, property, { + configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, + enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, + value: value, + writable: nonWritable === null && desc ? desc.writable : !nonWritable + }); + } else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) { + // must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable + obj[property] = value; // eslint-disable-line no-param-reassign + } else { + throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.'); + } +}; diff --git a/node_modules/define-data-property/package.json b/node_modules/define-data-property/package.json new file mode 100644 index 000000000..eec40971e --- /dev/null +++ b/node_modules/define-data-property/package.json @@ -0,0 +1,106 @@ +{ + "name": "define-data-property", + "version": "1.1.4", + "description": "Define a data property on an object. Will fall back to assignment in an engine without descriptors.", + "main": "index.js", + "types": "./index.d.ts", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "tsc": "tsc -p .", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "npm run tsc", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/define-data-property.git" + }, + "keywords": [ + "define", + "data", + "property", + "object", + "accessor", + "javascript", + "ecmascript", + "enumerable", + "configurable", + "writable" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/define-data-property/issues" + }, + "homepage": "https://github.com/ljharb/define-data-property#readme", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "@types/call-bind": "^1.0.5", + "@types/define-properties": "^1.1.5", + "@types/es-value-fixtures": "^1.4.4", + "@types/for-each": "^0.3.3", + "@types/get-intrinsic": "^1.2.2", + "@types/gopd": "^1.0.3", + "@types/has-property-descriptors": "^1.0.3", + "@types/object-inspect": "^1.8.4", + "@types/object.getownpropertydescriptors": "^2.1.4", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "hasown": "^2.0.1", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.1", + "object.getownpropertydescriptors": "^2.1.7", + "reflect.ownkeys": "^1.1.4", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.4", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "types/reflect.ownkeys" + ] + } +} diff --git a/node_modules/define-data-property/test/index.js b/node_modules/define-data-property/test/index.js new file mode 100644 index 000000000..68204c66b --- /dev/null +++ b/node_modules/define-data-property/test/index.js @@ -0,0 +1,392 @@ +'use strict'; + +var test = require('tape'); +var v = require('es-value-fixtures'); +var forEach = require('for-each'); +var inspect = require('object-inspect'); +var hasOwn = require('hasown'); +var hasPropertyDescriptors = require('has-property-descriptors')(); +var getOwnPropertyDescriptors = require('object.getownpropertydescriptors'); +var ownKeys = require('reflect.ownkeys'); + +var defineDataProperty = require('../'); + +test('defineDataProperty', function (t) { + t.test('argument validation', function (st) { + forEach(v.primitives, function (nonObject) { + st['throws']( + // @ts-expect-error + function () { defineDataProperty(nonObject, 'key', 'value'); }, + TypeError, + 'throws on non-object input: ' + inspect(nonObject) + ); + }); + + forEach(v.nonPropertyKeys, function (nonPropertyKey) { + st['throws']( + // @ts-expect-error + function () { defineDataProperty({}, nonPropertyKey, 'value'); }, + TypeError, + 'throws on non-PropertyKey input: ' + inspect(nonPropertyKey) + ); + }); + + forEach(v.nonBooleans, function (nonBoolean) { + if (nonBoolean !== null) { + st['throws']( + // @ts-expect-error + function () { defineDataProperty({}, 'key', 'value', nonBoolean); }, + TypeError, + 'throws on non-boolean nonEnumerable: ' + inspect(nonBoolean) + ); + + st['throws']( + // @ts-expect-error + function () { defineDataProperty({}, 'key', 'value', false, nonBoolean); }, + TypeError, + 'throws on non-boolean nonWritable: ' + inspect(nonBoolean) + ); + + st['throws']( + // @ts-expect-error + function () { defineDataProperty({}, 'key', 'value', false, false, nonBoolean); }, + TypeError, + 'throws on non-boolean nonConfigurable: ' + inspect(nonBoolean) + ); + } + }); + + st.end(); + }); + + t.test('normal data property', function (st) { + /** @type {Record} */ + var obj = { existing: 'existing property' }; + st.ok(hasOwn(obj, 'existing'), 'has initial own property'); + st.equal(obj.existing, 'existing property', 'has expected initial value'); + + var res = defineDataProperty(obj, 'added', 'added property'); + st.equal(res, void undefined, 'returns `undefined`'); + st.ok(hasOwn(obj, 'added'), 'has expected own property'); + st.equal(obj.added, 'added property', 'has expected value'); + + defineDataProperty(obj, 'existing', 'new value'); + st.ok(hasOwn(obj, 'existing'), 'still has expected own property'); + st.equal(obj.existing, 'new value', 'has new expected value'); + + defineDataProperty(obj, 'explicit1', 'new value', false); + st.ok(hasOwn(obj, 'explicit1'), 'has expected own property (explicit enumerable)'); + st.equal(obj.explicit1, 'new value', 'has new expected value (explicit enumerable)'); + + defineDataProperty(obj, 'explicit2', 'new value', false, false); + st.ok(hasOwn(obj, 'explicit2'), 'has expected own property (explicit writable)'); + st.equal(obj.explicit2, 'new value', 'has new expected value (explicit writable)'); + + defineDataProperty(obj, 'explicit3', 'new value', false, false, false); + st.ok(hasOwn(obj, 'explicit3'), 'has expected own property (explicit configurable)'); + st.equal(obj.explicit3, 'new value', 'has new expected value (explicit configurable)'); + + st.end(); + }); + + t.test('loose mode', { skip: !hasPropertyDescriptors }, function (st) { + var obj = { existing: 'existing property' }; + + defineDataProperty(obj, 'added', 'added value 1', true, null, null, true); + st.deepEqual( + getOwnPropertyDescriptors(obj), + { + existing: { + configurable: true, + enumerable: true, + value: 'existing property', + writable: true + }, + added: { + configurable: true, + enumerable: !hasPropertyDescriptors, + value: 'added value 1', + writable: true + } + }, + 'in loose mode, obj still adds property 1' + ); + + defineDataProperty(obj, 'added', 'added value 2', false, true, null, true); + st.deepEqual( + getOwnPropertyDescriptors(obj), + { + existing: { + configurable: true, + enumerable: true, + value: 'existing property', + writable: true + }, + added: { + configurable: true, + enumerable: true, + value: 'added value 2', + writable: !hasPropertyDescriptors + } + }, + 'in loose mode, obj still adds property 2' + ); + + defineDataProperty(obj, 'added', 'added value 3', false, false, true, true); + st.deepEqual( + getOwnPropertyDescriptors(obj), + { + existing: { + configurable: true, + enumerable: true, + value: 'existing property', + writable: true + }, + added: { + configurable: !hasPropertyDescriptors, + enumerable: true, + value: 'added value 3', + writable: true + } + }, + 'in loose mode, obj still adds property 3' + ); + + st.end(); + }); + + t.test('non-normal data property, ES3', { skip: hasPropertyDescriptors }, function (st) { + /** @type {Record} */ + var obj = { existing: 'existing property' }; + + st['throws']( + function () { defineDataProperty(obj, 'added', 'added value', true); }, + SyntaxError, + 'nonEnumerable throws a Syntax Error' + ); + + st['throws']( + function () { defineDataProperty(obj, 'added', 'added value', false, true); }, + SyntaxError, + 'nonWritable throws a Syntax Error' + ); + + st['throws']( + function () { defineDataProperty(obj, 'added', 'added value', false, false, true); }, + SyntaxError, + 'nonWritable throws a Syntax Error' + ); + + st.deepEqual( + ownKeys(obj), + ['existing'], + 'obj still has expected keys' + ); + st.equal(obj.existing, 'existing property', 'obj still has expected values'); + + st.end(); + }); + + t.test('new non-normal data property, ES5+', { skip: !hasPropertyDescriptors }, function (st) { + /** @type {Record} */ + var obj = { existing: 'existing property' }; + + defineDataProperty(obj, 'nonEnum', null, true); + defineDataProperty(obj, 'nonWrit', null, false, true); + defineDataProperty(obj, 'nonConf', null, false, false, true); + + st.deepEqual( + getOwnPropertyDescriptors(obj), + { + existing: { + configurable: true, + enumerable: true, + value: 'existing property', + writable: true + }, + nonEnum: { + configurable: true, + enumerable: false, + value: null, + writable: true + }, + nonWrit: { + configurable: true, + enumerable: true, + value: null, + writable: false + }, + nonConf: { + configurable: false, + enumerable: true, + value: null, + writable: true + } + }, + 'obj has expected property descriptors' + ); + + st.end(); + }); + + t.test('existing non-normal data property, ES5+', { skip: !hasPropertyDescriptors }, function (st) { + // test case changing an existing non-normal property + + /** @type {Record} */ + var obj = {}; + Object.defineProperty(obj, 'nonEnum', { configurable: true, enumerable: false, value: null, writable: true }); + Object.defineProperty(obj, 'nonWrit', { configurable: true, enumerable: true, value: null, writable: false }); + Object.defineProperty(obj, 'nonConf', { configurable: false, enumerable: true, value: null, writable: true }); + + st.deepEqual( + getOwnPropertyDescriptors(obj), + { + nonEnum: { + configurable: true, + enumerable: false, + value: null, + writable: true + }, + nonWrit: { + configurable: true, + enumerable: true, + value: null, + writable: false + }, + nonConf: { + configurable: false, + enumerable: true, + value: null, + writable: true + } + }, + 'obj initially has expected property descriptors' + ); + + defineDataProperty(obj, 'nonEnum', 'new value', false); + defineDataProperty(obj, 'nonWrit', 'new value', false, false); + st['throws']( + function () { defineDataProperty(obj, 'nonConf', 'new value', false, false, false); }, + TypeError, + 'can not alter a nonconfigurable property' + ); + + st.deepEqual( + getOwnPropertyDescriptors(obj), + { + nonEnum: { + configurable: true, + enumerable: true, + value: 'new value', + writable: true + }, + nonWrit: { + configurable: true, + enumerable: true, + value: 'new value', + writable: true + }, + nonConf: { + configurable: false, + enumerable: true, + value: null, + writable: true + } + }, + 'obj ends up with expected property descriptors' + ); + + st.end(); + }); + + t.test('frozen object, ES5+', { skip: !hasPropertyDescriptors }, function (st) { + var frozen = Object.freeze({ existing: true }); + + st['throws']( + function () { defineDataProperty(frozen, 'existing', 'new value'); }, + TypeError, + 'frozen object can not modify an existing property' + ); + + st['throws']( + function () { defineDataProperty(frozen, 'new', 'new property'); }, + TypeError, + 'frozen object can not add a new property' + ); + + st.end(); + }); + + t.test('sealed object, ES5+', { skip: !hasPropertyDescriptors }, function (st) { + var sealed = Object.seal({ existing: true }); + st.deepEqual( + Object.getOwnPropertyDescriptor(sealed, 'existing'), + { + configurable: false, + enumerable: true, + value: true, + writable: true + }, + 'existing value on sealed object has expected descriptor' + ); + + defineDataProperty(sealed, 'existing', 'new value'); + + st.deepEqual( + Object.getOwnPropertyDescriptor(sealed, 'existing'), + { + configurable: false, + enumerable: true, + value: 'new value', + writable: true + }, + 'existing value on sealed object has changed descriptor' + ); + + st['throws']( + function () { defineDataProperty(sealed, 'new', 'new property'); }, + TypeError, + 'sealed object can not add a new property' + ); + + st.end(); + }); + + t.test('nonextensible object, ES5+', { skip: !hasPropertyDescriptors }, function (st) { + var nonExt = Object.preventExtensions({ existing: true }); + + st.deepEqual( + Object.getOwnPropertyDescriptor(nonExt, 'existing'), + { + configurable: true, + enumerable: true, + value: true, + writable: true + }, + 'existing value on non-extensible object has expected descriptor' + ); + + defineDataProperty(nonExt, 'existing', 'new value', true); + + st.deepEqual( + Object.getOwnPropertyDescriptor(nonExt, 'existing'), + { + configurable: true, + enumerable: false, + value: 'new value', + writable: true + }, + 'existing value on non-extensible object has changed descriptor' + ); + + st['throws']( + function () { defineDataProperty(nonExt, 'new', 'new property'); }, + TypeError, + 'non-extensible object can not add a new property' + ); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/define-data-property/tsconfig.json b/node_modules/define-data-property/tsconfig.json new file mode 100644 index 000000000..69f060dcc --- /dev/null +++ b/node_modules/define-data-property/tsconfig.json @@ -0,0 +1,59 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + + /* Language and Environment */ + "target": "es2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + "typeRoots": ["types"], /* Specify multiple folders that act like './node_modules/@types'. */ + "resolveJsonModule": true, /* Enable importing .json files. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + + /* Interop Constraints */ + "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + + /* Completeness */ + // "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "exclude": [ + "coverage" + ] +} diff --git a/node_modules/es-define-property/.eslintrc b/node_modules/es-define-property/.eslintrc new file mode 100644 index 000000000..46f3b120b --- /dev/null +++ b/node_modules/es-define-property/.eslintrc @@ -0,0 +1,13 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "new-cap": ["error", { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, +} diff --git a/node_modules/es-define-property/.github/FUNDING.yml b/node_modules/es-define-property/.github/FUNDING.yml new file mode 100644 index 000000000..4445451fb --- /dev/null +++ b/node_modules/es-define-property/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/es-define-property +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/es-define-property/.nycrc b/node_modules/es-define-property/.nycrc new file mode 100644 index 000000000..bdd626ce9 --- /dev/null +++ b/node_modules/es-define-property/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/es-define-property/CHANGELOG.md b/node_modules/es-define-property/CHANGELOG.md new file mode 100644 index 000000000..4dce2ec58 --- /dev/null +++ b/node_modules/es-define-property/CHANGELOG.md @@ -0,0 +1,15 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## v1.0.0 - 2024-02-12 + +### Commits + +- Initial implementation, tests, readme, types [`3e154e1`](https://github.com/ljharb/es-define-property/commit/3e154e11a2fee09127220f5e503bf2c0a31dd480) +- Initial commit [`07d98de`](https://github.com/ljharb/es-define-property/commit/07d98de34a4dc31ff5e83a37c0c3f49e0d85cd50) +- npm init [`c4eb634`](https://github.com/ljharb/es-define-property/commit/c4eb6348b0d3886aac36cef34ad2ee0665ea6f3e) +- Only apps should have lockfiles [`7af86ec`](https://github.com/ljharb/es-define-property/commit/7af86ec1d311ec0b17fdfe616a25f64276903856) diff --git a/node_modules/es-define-property/LICENSE b/node_modules/es-define-property/LICENSE new file mode 100644 index 000000000..f82f38963 --- /dev/null +++ b/node_modules/es-define-property/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/es-define-property/README.md b/node_modules/es-define-property/README.md new file mode 100644 index 000000000..9b291bddb --- /dev/null +++ b/node_modules/es-define-property/README.md @@ -0,0 +1,49 @@ +# es-define-property [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +`Object.defineProperty`, but not IE 8's broken one. + +## Example + +```js +const assert = require('assert'); + +const $defineProperty = require('es-define-property'); + +if ($defineProperty) { + assert.equal($defineProperty, Object.defineProperty); +} else if (Object.defineProperty) { + assert.equal($defineProperty, false, 'this is IE 8'); +} else { + assert.equal($defineProperty, false, 'this is an ES3 engine'); +} +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/es-define-property +[npm-version-svg]: https://versionbadg.es/ljharb/es-define-property.svg +[deps-svg]: https://david-dm.org/ljharb/es-define-property.svg +[deps-url]: https://david-dm.org/ljharb/es-define-property +[dev-deps-svg]: https://david-dm.org/ljharb/es-define-property/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/es-define-property#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/es-define-property.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/es-define-property.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/es-define-property.svg +[downloads-url]: https://npm-stat.com/charts.html?package=es-define-property +[codecov-image]: https://codecov.io/gh/ljharb/es-define-property/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/es-define-property/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/es-define-property +[actions-url]: https://github.com/ljharb/es-define-property/actions diff --git a/node_modules/es-define-property/index.d.ts b/node_modules/es-define-property/index.d.ts new file mode 100644 index 000000000..6012247c4 --- /dev/null +++ b/node_modules/es-define-property/index.d.ts @@ -0,0 +1,3 @@ +declare const defineProperty: false | typeof Object.defineProperty; + +export = defineProperty; \ No newline at end of file diff --git a/node_modules/es-define-property/index.js b/node_modules/es-define-property/index.js new file mode 100644 index 000000000..f32737d24 --- /dev/null +++ b/node_modules/es-define-property/index.js @@ -0,0 +1,16 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +/** @type {import('.')} */ +var $defineProperty = GetIntrinsic('%Object.defineProperty%', true) || false; +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = false; + } +} + +module.exports = $defineProperty; diff --git a/node_modules/es-define-property/package.json b/node_modules/es-define-property/package.json new file mode 100644 index 000000000..45bc90f3e --- /dev/null +++ b/node_modules/es-define-property/package.json @@ -0,0 +1,81 @@ +{ + "name": "es-define-property", + "version": "1.0.0", + "description": "`Object.defineProperty`, but not IE 8's broken one.", + "main": "index.js", + "types": "./index.d.ts", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/es-define-property.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "object", + "define", + "property", + "defineProperty", + "Object.defineProperty" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/es-define-property/issues" + }, + "homepage": "https://github.com/ljharb/es-define-property#readme", + "dependencies": { + "get-intrinsic": "^1.2.4" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "@types/get-intrinsic": "^1.2.2", + "@types/gopd": "^1.0.3", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "eslint": "^8.8.0", + "evalmd": "^0.0.19", + "gopd": "^1.0.1", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.4", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/es-define-property/test/index.js b/node_modules/es-define-property/test/index.js new file mode 100644 index 000000000..dbc054efe --- /dev/null +++ b/node_modules/es-define-property/test/index.js @@ -0,0 +1,55 @@ +'use strict'; + +var $defineProperty = require('../'); + +var test = require('tape'); +var gOPD = require('gopd'); + +test('defineProperty: supported', { skip: !$defineProperty }, function (t) { + t.plan(4); + + t.equal(typeof $defineProperty, 'function', 'defineProperty is supported'); + if ($defineProperty && gOPD) { // this `if` check is just to shut TS up + var o = { a: 1 }; + + $defineProperty(o, 'b', { enumerable: true, value: 2 }); + t.deepEqual( + gOPD(o, 'b'), + { + configurable: false, + enumerable: true, + value: 2, + writable: false + }, + 'property descriptor is as expected' + ); + + $defineProperty(o, 'c', { enumerable: false, value: 3, writable: true }); + t.deepEqual( + gOPD(o, 'c'), + { + configurable: false, + enumerable: false, + value: 3, + writable: true + }, + 'property descriptor is as expected' + ); + } + + t.equal($defineProperty, Object.defineProperty, 'defineProperty is Object.defineProperty'); + + t.end(); +}); + +test('defineProperty: not supported', { skip: !!$defineProperty }, function (t) { + t.notOk($defineProperty, 'defineProperty is not supported'); + + t.match( + typeof $defineProperty, + /^(?:undefined|boolean)$/, + '`typeof defineProperty` is `undefined` or `boolean`' + ); + + t.end(); +}); diff --git a/node_modules/es-define-property/tsconfig.json b/node_modules/es-define-property/tsconfig.json new file mode 100644 index 000000000..fdfa1550d --- /dev/null +++ b/node_modules/es-define-property/tsconfig.json @@ -0,0 +1,50 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Projects */ + + /* Language and Environment */ + "target": "es2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": ["types"], /* Specify multiple folders that act like `./node_modules/@types`. */ + "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declarationMap": true, /* Create sourcemaps for d.ts files. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + + /* Interop Constraints */ + "allowSyntheticDefaultImports": true, /* Allow `import x from y` when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + + /* Completeness */ + // "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "exclude": [ + "coverage", + "test/list-exports" + ], +} diff --git a/node_modules/es-errors/.eslintrc b/node_modules/es-errors/.eslintrc new file mode 100644 index 000000000..3b5d9e90e --- /dev/null +++ b/node_modules/es-errors/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/node_modules/es-errors/.github/FUNDING.yml b/node_modules/es-errors/.github/FUNDING.yml new file mode 100644 index 000000000..f1b880554 --- /dev/null +++ b/node_modules/es-errors/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/es-errors +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/es-errors/CHANGELOG.md b/node_modules/es-errors/CHANGELOG.md new file mode 100644 index 000000000..204a9e904 --- /dev/null +++ b/node_modules/es-errors/CHANGELOG.md @@ -0,0 +1,40 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.3.0](https://github.com/ljharb/es-errors/compare/v1.2.1...v1.3.0) - 2024-02-05 + +### Commits + +- [New] add `EvalError` and `URIError` [`1927627`](https://github.com/ljharb/es-errors/commit/1927627ba68cb6c829d307231376c967db53acdf) + +## [v1.2.1](https://github.com/ljharb/es-errors/compare/v1.2.0...v1.2.1) - 2024-02-04 + +### Commits + +- [Fix] add missing `exports` entry [`5bb5f28`](https://github.com/ljharb/es-errors/commit/5bb5f280f98922701109d6ebb82eea2257cecc7e) + +## [v1.2.0](https://github.com/ljharb/es-errors/compare/v1.1.0...v1.2.0) - 2024-02-04 + +### Commits + +- [New] add `ReferenceError` [`6d8cf5b`](https://github.com/ljharb/es-errors/commit/6d8cf5bbb6f3f598d02cf6f30e468ba2caa8e143) + +## [v1.1.0](https://github.com/ljharb/es-errors/compare/v1.0.0...v1.1.0) - 2024-02-04 + +### Commits + +- [New] add base Error [`2983ab6`](https://github.com/ljharb/es-errors/commit/2983ab65f7bc5441276cb021dc3aa03c78881698) + +## v1.0.0 - 2024-02-03 + +### Commits + +- Initial implementation, tests, readme, type [`8f47631`](https://github.com/ljharb/es-errors/commit/8f476317e9ad76f40ad648081829b1a1a3a1288b) +- Initial commit [`ea5d099`](https://github.com/ljharb/es-errors/commit/ea5d099ef18e550509ab9e2be000526afd81c385) +- npm init [`6f5ebf9`](https://github.com/ljharb/es-errors/commit/6f5ebf9cead474dadd72b9e63dad315820a089ae) +- Only apps should have lockfiles [`e1a0aeb`](https://github.com/ljharb/es-errors/commit/e1a0aeb7b80f5cfc56be54d6b2100e915d47def8) +- [meta] add `sideEffects` flag [`a9c7d46`](https://github.com/ljharb/es-errors/commit/a9c7d460a492f1d8a241c836bc25a322a19cc043) diff --git a/node_modules/es-errors/LICENSE b/node_modules/es-errors/LICENSE new file mode 100644 index 000000000..f82f38963 --- /dev/null +++ b/node_modules/es-errors/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/es-errors/README.md b/node_modules/es-errors/README.md new file mode 100644 index 000000000..8dbfacfea --- /dev/null +++ b/node_modules/es-errors/README.md @@ -0,0 +1,55 @@ +# es-errors [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +A simple cache for a few of the JS Error constructors. + +## Example + +```js +const assert = require('assert'); + +const Base = require('es-errors'); +const Eval = require('es-errors/eval'); +const Range = require('es-errors/range'); +const Ref = require('es-errors/ref'); +const Syntax = require('es-errors/syntax'); +const Type = require('es-errors/type'); +const URI = require('es-errors/uri'); + +assert.equal(Base, Error); +assert.equal(Eval, EvalError); +assert.equal(Range, RangeError); +assert.equal(Ref, ReferenceError); +assert.equal(Syntax, SyntaxError); +assert.equal(Type, TypeError); +assert.equal(URI, URIError); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/es-errors +[npm-version-svg]: https://versionbadg.es/ljharb/es-errors.svg +[deps-svg]: https://david-dm.org/ljharb/es-errors.svg +[deps-url]: https://david-dm.org/ljharb/es-errors +[dev-deps-svg]: https://david-dm.org/ljharb/es-errors/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/es-errors#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/es-errors.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/es-errors.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/es-errors.svg +[downloads-url]: https://npm-stat.com/charts.html?package=es-errors +[codecov-image]: https://codecov.io/gh/ljharb/es-errors/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/es-errors/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/es-errors +[actions-url]: https://github.com/ljharb/es-errors/actions diff --git a/node_modules/es-errors/eval.d.ts b/node_modules/es-errors/eval.d.ts new file mode 100644 index 000000000..e4210e01e --- /dev/null +++ b/node_modules/es-errors/eval.d.ts @@ -0,0 +1,3 @@ +declare const EvalError: EvalErrorConstructor; + +export = EvalError; diff --git a/node_modules/es-errors/eval.js b/node_modules/es-errors/eval.js new file mode 100644 index 000000000..725ccb61a --- /dev/null +++ b/node_modules/es-errors/eval.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./eval')} */ +module.exports = EvalError; diff --git a/node_modules/es-errors/index.d.ts b/node_modules/es-errors/index.d.ts new file mode 100644 index 000000000..69bdbc92e --- /dev/null +++ b/node_modules/es-errors/index.d.ts @@ -0,0 +1,3 @@ +declare const Error: ErrorConstructor; + +export = Error; diff --git a/node_modules/es-errors/index.js b/node_modules/es-errors/index.js new file mode 100644 index 000000000..cc0c52124 --- /dev/null +++ b/node_modules/es-errors/index.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('.')} */ +module.exports = Error; diff --git a/node_modules/es-errors/package.json b/node_modules/es-errors/package.json new file mode 100644 index 000000000..ff8c2a531 --- /dev/null +++ b/node_modules/es-errors/package.json @@ -0,0 +1,80 @@ +{ + "name": "es-errors", + "version": "1.3.0", + "description": "A simple cache for a few of the JS Error constructors.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./eval": "./eval.js", + "./range": "./range.js", + "./ref": "./ref.js", + "./syntax": "./syntax.js", + "./type": "./type.js", + "./uri": "./uri.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/**/*.js'", + "posttest": "aud --production", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git' | grep -v dist/)", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/es-errors.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "error", + "typeerror", + "syntaxerror", + "rangeerror" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/es-errors/issues" + }, + "homepage": "https://github.com/ljharb/es-errors#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "eclint": "^2.8.1", + "eslint": "^8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.4", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/es-errors/range.d.ts b/node_modules/es-errors/range.d.ts new file mode 100644 index 000000000..3a12e8642 --- /dev/null +++ b/node_modules/es-errors/range.d.ts @@ -0,0 +1,3 @@ +declare const RangeError: RangeErrorConstructor; + +export = RangeError; diff --git a/node_modules/es-errors/range.js b/node_modules/es-errors/range.js new file mode 100644 index 000000000..2044fe036 --- /dev/null +++ b/node_modules/es-errors/range.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./range')} */ +module.exports = RangeError; diff --git a/node_modules/es-errors/ref.d.ts b/node_modules/es-errors/ref.d.ts new file mode 100644 index 000000000..a13107e24 --- /dev/null +++ b/node_modules/es-errors/ref.d.ts @@ -0,0 +1,3 @@ +declare const ReferenceError: ReferenceErrorConstructor; + +export = ReferenceError; diff --git a/node_modules/es-errors/ref.js b/node_modules/es-errors/ref.js new file mode 100644 index 000000000..d7c430fdb --- /dev/null +++ b/node_modules/es-errors/ref.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./ref')} */ +module.exports = ReferenceError; diff --git a/node_modules/es-errors/syntax.d.ts b/node_modules/es-errors/syntax.d.ts new file mode 100644 index 000000000..6a0c53c5b --- /dev/null +++ b/node_modules/es-errors/syntax.d.ts @@ -0,0 +1,3 @@ +declare const SyntaxError: SyntaxErrorConstructor; + +export = SyntaxError; diff --git a/node_modules/es-errors/syntax.js b/node_modules/es-errors/syntax.js new file mode 100644 index 000000000..5f5fddeec --- /dev/null +++ b/node_modules/es-errors/syntax.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./syntax')} */ +module.exports = SyntaxError; diff --git a/node_modules/es-errors/test/index.js b/node_modules/es-errors/test/index.js new file mode 100644 index 000000000..1ff027721 --- /dev/null +++ b/node_modules/es-errors/test/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var test = require('tape'); + +var E = require('../'); +var R = require('../range'); +var Ref = require('../ref'); +var S = require('../syntax'); +var T = require('../type'); + +test('errors', function (t) { + t.equal(E, Error); + t.equal(R, RangeError); + t.equal(Ref, ReferenceError); + t.equal(S, SyntaxError); + t.equal(T, TypeError); + + t.end(); +}); diff --git a/node_modules/es-errors/tsconfig.json b/node_modules/es-errors/tsconfig.json new file mode 100644 index 000000000..99dfeb6c8 --- /dev/null +++ b/node_modules/es-errors/tsconfig.json @@ -0,0 +1,49 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Projects */ + + /* Language and Environment */ + "target": "es5", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": ["types"], /* Specify multiple folders that act like `./node_modules/@types`. */ + "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declarationMap": true, /* Create sourcemaps for d.ts files. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + + /* Interop Constraints */ + "allowSyntheticDefaultImports": true, /* Allow `import x from y` when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + + /* Completeness */ + // "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/es-errors/type.d.ts b/node_modules/es-errors/type.d.ts new file mode 100644 index 000000000..576fb5161 --- /dev/null +++ b/node_modules/es-errors/type.d.ts @@ -0,0 +1,3 @@ +declare const TypeError: TypeErrorConstructor + +export = TypeError; diff --git a/node_modules/es-errors/type.js b/node_modules/es-errors/type.js new file mode 100644 index 000000000..9769e44e3 --- /dev/null +++ b/node_modules/es-errors/type.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./type')} */ +module.exports = TypeError; diff --git a/node_modules/es-errors/uri.d.ts b/node_modules/es-errors/uri.d.ts new file mode 100644 index 000000000..c3261c91e --- /dev/null +++ b/node_modules/es-errors/uri.d.ts @@ -0,0 +1,3 @@ +declare const URIError: URIErrorConstructor; + +export = URIError; diff --git a/node_modules/es-errors/uri.js b/node_modules/es-errors/uri.js new file mode 100644 index 000000000..e9cd1c787 --- /dev/null +++ b/node_modules/es-errors/uri.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./uri')} */ +module.exports = URIError; diff --git a/node_modules/fast-safe-stringify/.travis.yml b/node_modules/fast-safe-stringify/.travis.yml new file mode 100644 index 000000000..2b06d253e --- /dev/null +++ b/node_modules/fast-safe-stringify/.travis.yml @@ -0,0 +1,8 @@ +language: node_js +sudo: false +node_js: +- '4' +- '6' +- '8' +- '9' +- '10' diff --git a/node_modules/fast-safe-stringify/CHANGELOG.md b/node_modules/fast-safe-stringify/CHANGELOG.md new file mode 100644 index 000000000..55f2d082f --- /dev/null +++ b/node_modules/fast-safe-stringify/CHANGELOG.md @@ -0,0 +1,17 @@ +# Changelog + +## v.2.0.0 + +Features + +- Added stable-stringify (see documentation) +- Support replacer +- Support spacer +- toJSON support without forceDecirc property +- Improved performance + +Breaking changes + +- Manipulating the input value in a `toJSON` function is not possible anymore in + all cases (see documentation) +- Dropped support for e.g. IE8 and Node.js < 4 diff --git a/node_modules/fast-safe-stringify/LICENSE b/node_modules/fast-safe-stringify/LICENSE new file mode 100644 index 000000000..d310c2d17 --- /dev/null +++ b/node_modules/fast-safe-stringify/LICENSE @@ -0,0 +1,23 @@ +The MIT License (MIT) + +Copyright (c) 2016 David Mark Clements +Copyright (c) 2017 David Mark Clements & Matteo Collina +Copyright (c) 2018 David Mark Clements, Matteo Collina & Ruben Bridgewater + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/fast-safe-stringify/benchmark.js b/node_modules/fast-safe-stringify/benchmark.js new file mode 100644 index 000000000..7ba5e9f54 --- /dev/null +++ b/node_modules/fast-safe-stringify/benchmark.js @@ -0,0 +1,137 @@ +const Benchmark = require('benchmark') +const suite = new Benchmark.Suite() +const { inspect } = require('util') +const jsonStringifySafe = require('json-stringify-safe') +const fastSafeStringify = require('./') + +const array = new Array(10).fill(0).map((_, i) => i) +const obj = { foo: array } +const circ = JSON.parse(JSON.stringify(obj)) +circ.o = { obj: circ, array } +const circGetters = JSON.parse(JSON.stringify(obj)) +Object.assign(circGetters, { get o () { return { obj: circGetters, array } } }) + +const deep = require('./package.json') +deep.deep = JSON.parse(JSON.stringify(deep)) +deep.deep.deep = JSON.parse(JSON.stringify(deep)) +deep.deep.deep.deep = JSON.parse(JSON.stringify(deep)) +deep.array = array + +const deepCirc = JSON.parse(JSON.stringify(deep)) +deepCirc.deep.deep.deep.circ = deepCirc +deepCirc.deep.deep.circ = deepCirc +deepCirc.deep.circ = deepCirc +deepCirc.array = array + +const deepCircGetters = JSON.parse(JSON.stringify(deep)) +for (let i = 0; i < 10; i++) { + deepCircGetters[i.toString()] = { + deep: { + deep: { + get circ () { return deep.deep }, + deep: { get circ () { return deep.deep.deep } } + }, + get circ () { return deep } + }, + get array () { return array } + } +} + +const deepCircNonCongifurableGetters = JSON.parse(JSON.stringify(deep)) +Object.defineProperty(deepCircNonCongifurableGetters.deep.deep.deep, 'circ', { + get: () => deepCircNonCongifurableGetters, + enumerable: true, + configurable: false +}) +Object.defineProperty(deepCircNonCongifurableGetters.deep.deep, 'circ', { + get: () => deepCircNonCongifurableGetters, + enumerable: true, + configurable: false +}) +Object.defineProperty(deepCircNonCongifurableGetters.deep, 'circ', { + get: () => deepCircNonCongifurableGetters, + enumerable: true, + configurable: false +}) +Object.defineProperty(deepCircNonCongifurableGetters, 'array', { + get: () => array, + enumerable: true, + configurable: false +}) + +suite.add('util.inspect: simple object ', function () { + inspect(obj, { showHidden: false, depth: null }) +}) +suite.add('util.inspect: circular ', function () { + inspect(circ, { showHidden: false, depth: null }) +}) +suite.add('util.inspect: circular getters ', function () { + inspect(circGetters, { showHidden: false, depth: null }) +}) +suite.add('util.inspect: deep ', function () { + inspect(deep, { showHidden: false, depth: null }) +}) +suite.add('util.inspect: deep circular ', function () { + inspect(deepCirc, { showHidden: false, depth: null }) +}) +suite.add('util.inspect: large deep circular getters ', function () { + inspect(deepCircGetters, { showHidden: false, depth: null }) +}) +suite.add('util.inspect: deep non-conf circular getters', function () { + inspect(deepCircNonCongifurableGetters, { showHidden: false, depth: null }) +}) + +suite.add('\njson-stringify-safe: simple object ', function () { + jsonStringifySafe(obj) +}) +suite.add('json-stringify-safe: circular ', function () { + jsonStringifySafe(circ) +}) +suite.add('json-stringify-safe: circular getters ', function () { + jsonStringifySafe(circGetters) +}) +suite.add('json-stringify-safe: deep ', function () { + jsonStringifySafe(deep) +}) +suite.add('json-stringify-safe: deep circular ', function () { + jsonStringifySafe(deepCirc) +}) +suite.add('json-stringify-safe: large deep circular getters ', function () { + jsonStringifySafe(deepCircGetters) +}) +suite.add('json-stringify-safe: deep non-conf circular getters', function () { + jsonStringifySafe(deepCircNonCongifurableGetters) +}) + +suite.add('\nfast-safe-stringify: simple object ', function () { + fastSafeStringify(obj) +}) +suite.add('fast-safe-stringify: circular ', function () { + fastSafeStringify(circ) +}) +suite.add('fast-safe-stringify: circular getters ', function () { + fastSafeStringify(circGetters) +}) +suite.add('fast-safe-stringify: deep ', function () { + fastSafeStringify(deep) +}) +suite.add('fast-safe-stringify: deep circular ', function () { + fastSafeStringify(deepCirc) +}) +suite.add('fast-safe-stringify: large deep circular getters ', function () { + fastSafeStringify(deepCircGetters) +}) +suite.add('fast-safe-stringify: deep non-conf circular getters', function () { + fastSafeStringify(deepCircNonCongifurableGetters) +}) + +// add listeners +suite.on('cycle', function (event) { + console.log(String(event.target)) +}) + +suite.on('complete', function () { + console.log('\nFastest is ' + this.filter('fastest').map('name')) +}) + +suite.run({ delay: 1, minSamples: 150 }) diff --git a/node_modules/fast-safe-stringify/index.d.ts b/node_modules/fast-safe-stringify/index.d.ts new file mode 100644 index 000000000..9a9b1f00e --- /dev/null +++ b/node_modules/fast-safe-stringify/index.d.ts @@ -0,0 +1,23 @@ +declare function stringify( + value: any, + replacer?: (key: string, value: any) => any, + space?: string | number, + options?: { depthLimit: number | undefined; edgesLimit: number | undefined } +): string; + +declare namespace stringify { + export function stable( + value: any, + replacer?: (key: string, value: any) => any, + space?: string | number, + options?: { depthLimit: number | undefined; edgesLimit: number | undefined } + ): string; + export function stableStringify( + value: any, + replacer?: (key: string, value: any) => any, + space?: string | number, + options?: { depthLimit: number | undefined; edgesLimit: number | undefined } + ): string; +} + +export default stringify; diff --git a/node_modules/fast-safe-stringify/index.js b/node_modules/fast-safe-stringify/index.js new file mode 100644 index 000000000..ecf7e5190 --- /dev/null +++ b/node_modules/fast-safe-stringify/index.js @@ -0,0 +1,229 @@ +module.exports = stringify +stringify.default = stringify +stringify.stable = deterministicStringify +stringify.stableStringify = deterministicStringify + +var LIMIT_REPLACE_NODE = '[...]' +var CIRCULAR_REPLACE_NODE = '[Circular]' + +var arr = [] +var replacerStack = [] + +function defaultOptions () { + return { + depthLimit: Number.MAX_SAFE_INTEGER, + edgesLimit: Number.MAX_SAFE_INTEGER + } +} + +// Regular stringify +function stringify (obj, replacer, spacer, options) { + if (typeof options === 'undefined') { + options = defaultOptions() + } + + decirc(obj, '', 0, [], undefined, 0, options) + var res + try { + if (replacerStack.length === 0) { + res = JSON.stringify(obj, replacer, spacer) + } else { + res = JSON.stringify(obj, replaceGetterValues(replacer), spacer) + } + } catch (_) { + return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]') + } finally { + while (arr.length !== 0) { + var part = arr.pop() + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]) + } else { + part[0][part[1]] = part[2] + } + } + } + return res +} + +function setReplace (replace, val, k, parent) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: replace }) + arr.push([parent, k, val, propertyDescriptor]) + } else { + replacerStack.push([val, k, replace]) + } + } else { + parent[k] = replace + arr.push([parent, k, val]) + } +} + +function decirc (val, k, edgeIndex, stack, parent, depth, options) { + depth += 1 + var i + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k, parent) + return + } + } + + if ( + typeof options.depthLimit !== 'undefined' && + depth > options.depthLimit + ) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent) + return + } + + if ( + typeof options.edgesLimit !== 'undefined' && + edgeIndex + 1 > options.edgesLimit + ) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent) + return + } + + stack.push(val) + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + decirc(val[i], i, i, stack, val, depth, options) + } + } else { + var keys = Object.keys(val) + for (i = 0; i < keys.length; i++) { + var key = keys[i] + decirc(val[key], key, i, stack, val, depth, options) + } + } + stack.pop() + } +} + +// Stable-stringify +function compareFunction (a, b) { + if (a < b) { + return -1 + } + if (a > b) { + return 1 + } + return 0 +} + +function deterministicStringify (obj, replacer, spacer, options) { + if (typeof options === 'undefined') { + options = defaultOptions() + } + + var tmp = deterministicDecirc(obj, '', 0, [], undefined, 0, options) || obj + var res + try { + if (replacerStack.length === 0) { + res = JSON.stringify(tmp, replacer, spacer) + } else { + res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer) + } + } catch (_) { + return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]') + } finally { + // Ensure that we restore the object as it was. + while (arr.length !== 0) { + var part = arr.pop() + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]) + } else { + part[0][part[1]] = part[2] + } + } + } + return res +} + +function deterministicDecirc (val, k, edgeIndex, stack, parent, depth, options) { + depth += 1 + var i + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k, parent) + return + } + } + try { + if (typeof val.toJSON === 'function') { + return + } + } catch (_) { + return + } + + if ( + typeof options.depthLimit !== 'undefined' && + depth > options.depthLimit + ) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent) + return + } + + if ( + typeof options.edgesLimit !== 'undefined' && + edgeIndex + 1 > options.edgesLimit + ) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent) + return + } + + stack.push(val) + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + deterministicDecirc(val[i], i, i, stack, val, depth, options) + } + } else { + // Create a temporary object in the required way + var tmp = {} + var keys = Object.keys(val).sort(compareFunction) + for (i = 0; i < keys.length; i++) { + var key = keys[i] + deterministicDecirc(val[key], key, i, stack, val, depth, options) + tmp[key] = val[key] + } + if (typeof parent !== 'undefined') { + arr.push([parent, k, val]) + parent[k] = tmp + } else { + return tmp + } + } + stack.pop() + } +} + +// wraps replacer function to handle values we couldn't replace +// and mark them as replaced value +function replaceGetterValues (replacer) { + replacer = + typeof replacer !== 'undefined' + ? replacer + : function (k, v) { + return v + } + return function (key, val) { + if (replacerStack.length > 0) { + for (var i = 0; i < replacerStack.length; i++) { + var part = replacerStack[i] + if (part[1] === key && part[0] === val) { + val = part[2] + replacerStack.splice(i, 1) + break + } + } + } + return replacer.call(this, key, val) + } +} diff --git a/node_modules/fast-safe-stringify/package.json b/node_modules/fast-safe-stringify/package.json new file mode 100644 index 000000000..206a59198 --- /dev/null +++ b/node_modules/fast-safe-stringify/package.json @@ -0,0 +1,46 @@ +{ + "name": "fast-safe-stringify", + "version": "2.1.1", + "description": "Safely and quickly serialize JavaScript objects", + "keywords": [ + "stable", + "stringify", + "JSON", + "JSON.stringify", + "safe", + "serialize" + ], + "main": "index.js", + "scripts": { + "test": "standard && tap --no-esm test.js test-stable.js", + "benchmark": "node benchmark.js" + }, + "author": "David Mark Clements", + "contributors": [ + "Ruben Bridgewater", + "Matteo Collina", + "Ben Gourley", + "Gabriel Lesperance", + "Alex Liu", + "Christoph Walcher", + "Nicholas Young" + ], + "license": "MIT", + "typings": "index", + "devDependencies": { + "benchmark": "^2.1.4", + "clone": "^2.1.0", + "json-stringify-safe": "^5.0.1", + "standard": "^11.0.0", + "tap": "^12.0.0" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/davidmarkclements/fast-safe-stringify.git" + }, + "bugs": { + "url": "https://github.com/davidmarkclements/fast-safe-stringify/issues" + }, + "homepage": "https://github.com/davidmarkclements/fast-safe-stringify#readme", + "dependencies": {} +} diff --git a/node_modules/fast-safe-stringify/readme.md b/node_modules/fast-safe-stringify/readme.md new file mode 100644 index 000000000..47179c94a --- /dev/null +++ b/node_modules/fast-safe-stringify/readme.md @@ -0,0 +1,170 @@ +# fast-safe-stringify + +Safe and fast serialization alternative to [JSON.stringify][]. + +Gracefully handles circular structures instead of throwing in most cases. +It could return an error string if the circular object is too complex to analyze, +e.g. in case there are proxies involved. + +Provides a deterministic ("stable") version as well that will also gracefully +handle circular structures. See the example below for further information. + +## Usage + +The same as [JSON.stringify][]. + +`stringify(value[, replacer[, space[, options]]])` + +```js +const safeStringify = require('fast-safe-stringify') +const o = { a: 1 } +o.o = o + +console.log(safeStringify(o)) +// '{"a":1,"o":"[Circular]"}' +console.log(JSON.stringify(o)) +// TypeError: Converting circular structure to JSON + +function replacer(key, value) { + console.log('Key:', JSON.stringify(key), 'Value:', JSON.stringify(value)) + // Remove the circular structure + if (value === '[Circular]') { + return + } + return value +} + +// those are also defaults limits when no options object is passed into safeStringify +// configure it to lower the limit. +const options = { + depthLimit: Number.MAX_SAFE_INTEGER, + edgesLimit: Number.MAX_SAFE_INTEGER +}; + +const serialized = safeStringify(o, replacer, 2, options) +// Key: "" Value: {"a":1,"o":"[Circular]"} +// Key: "a" Value: 1 +// Key: "o" Value: "[Circular]" +console.log(serialized) +// { +// "a": 1 +// } +``` + + +Using the deterministic version also works the same: + +```js +const safeStringify = require('fast-safe-stringify') +const o = { b: 1, a: 0 } +o.o = o + +console.log(safeStringify(o)) +// '{"b":1,"a":0,"o":"[Circular]"}' +console.log(safeStringify.stableStringify(o)) +// '{"a":0,"b":1,"o":"[Circular]"}' +console.log(JSON.stringify(o)) +// TypeError: Converting circular structure to JSON +``` + +A faster and side-effect free implementation is available in the +[safe-stable-stringify][] module. However it is still considered experimental +due to a new and more complex implementation. + +### Replace strings constants + +- `[Circular]` - when same reference is found +- `[...]` - when some limit from options object is reached + +## Differences to JSON.stringify + +In general the behavior is identical to [JSON.stringify][]. The [`replacer`][] +and [`space`][] options are also available. + +A few exceptions exist to [JSON.stringify][] while using [`toJSON`][] or +[`replacer`][]: + +### Regular safe stringify + +- Manipulating a circular structure of the passed in value in a `toJSON` or the + `replacer` is not possible! It is possible for any other value and property. + +- In case a circular structure is detected and the [`replacer`][] is used it + will receive the string `[Circular]` as the argument instead of the circular + object itself. + +### Deterministic ("stable") safe stringify + +- Manipulating the input object either in a [`toJSON`][] or the [`replacer`][] + function will not have any effect on the output. The output entirely relies on + the shape the input value had at the point passed to the stringify function! + +- In case a circular structure is detected and the [`replacer`][] is used it + will receive the string `[Circular]` as the argument instead of the circular + object itself. + +A side effect free variation without these limitations can be found as well +([`safe-stable-stringify`][]). It is also faster than the current +implementation. It is still considered experimental due to a new and more +complex implementation. + +## Benchmarks + +Although not JSON, the Node.js `util.inspect` method can be used for similar +purposes (e.g. logging) and also handles circular references. + +Here we compare `fast-safe-stringify` with some alternatives: +(Lenovo T450s with a i7-5600U CPU using Node.js 8.9.4) + +```md +fast-safe-stringify: simple object x 1,121,497 ops/sec ±0.75% (97 runs sampled) +fast-safe-stringify: circular x 560,126 ops/sec ±0.64% (96 runs sampled) +fast-safe-stringify: deep x 32,472 ops/sec ±0.57% (95 runs sampled) +fast-safe-stringify: deep circular x 32,513 ops/sec ±0.80% (92 runs sampled) + +util.inspect: simple object x 272,837 ops/sec ±1.48% (90 runs sampled) +util.inspect: circular x 116,896 ops/sec ±1.19% (95 runs sampled) +util.inspect: deep x 19,382 ops/sec ±0.66% (92 runs sampled) +util.inspect: deep circular x 18,717 ops/sec ±0.63% (96 runs sampled) + +json-stringify-safe: simple object x 233,621 ops/sec ±0.97% (94 runs sampled) +json-stringify-safe: circular x 110,409 ops/sec ±1.85% (95 runs sampled) +json-stringify-safe: deep x 8,705 ops/sec ±0.87% (96 runs sampled) +json-stringify-safe: deep circular x 8,336 ops/sec ±2.20% (93 runs sampled) +``` + +For stable stringify comparisons, see the performance benchmarks in the +[`safe-stable-stringify`][] readme. + +## Protip + +Whether `fast-safe-stringify` or alternatives are used: if the use case +consists of deeply nested objects without circular references the following +pattern will give best results. +Shallow or one level nested objects on the other hand will slow down with it. +It is entirely dependant on the use case. + +```js +const stringify = require('fast-safe-stringify') + +function tryJSONStringify (obj) { + try { return JSON.stringify(obj) } catch (_) {} +} + +const serializedString = tryJSONStringify(deep) || stringify(deep) +``` + +## Acknowledgements + +Sponsored by [nearForm](http://nearform.com) + +## License + +MIT + +[`replacer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The%20replacer%20parameter +[`safe-stable-stringify`]: https://github.com/BridgeAR/safe-stable-stringify +[`space`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The%20space%20argument +[`toJSON`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON()_behavior +[benchmark]: https://github.com/epoberezkin/fast-json-stable-stringify/blob/67f688f7441010cfef91a6147280cc501701e83b/benchmark +[JSON.stringify]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify diff --git a/node_modules/fast-safe-stringify/test-stable.js b/node_modules/fast-safe-stringify/test-stable.js new file mode 100644 index 000000000..c55b95ca1 --- /dev/null +++ b/node_modules/fast-safe-stringify/test-stable.js @@ -0,0 +1,404 @@ +const test = require('tap').test +const fss = require('./').stable +const clone = require('clone') +const s = JSON.stringify +const stream = require('stream') + +test('circular reference to root', function (assert) { + const fixture = { name: 'Tywin Lannister' } + fixture.circle = fixture + const expected = s({ circle: '[Circular]', name: 'Tywin Lannister' }) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('circular getter reference to root', function (assert) { + const fixture = { + name: 'Tywin Lannister', + get circle () { + return fixture + } + } + + const expected = s({ circle: '[Circular]', name: 'Tywin Lannister' }) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('nested circular reference to root', function (assert) { + const fixture = { name: 'Tywin Lannister' } + fixture.id = { circle: fixture } + const expected = s({ id: { circle: '[Circular]' }, name: 'Tywin Lannister' }) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('child circular reference', function (assert) { + const fixture = { + name: 'Tywin Lannister', + child: { name: 'Tyrion Lannister' } + } + fixture.child.dinklage = fixture.child + const expected = s({ + child: { + dinklage: '[Circular]', + name: 'Tyrion Lannister' + }, + name: 'Tywin Lannister' + }) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('nested child circular reference', function (assert) { + const fixture = { + name: 'Tywin Lannister', + child: { name: 'Tyrion Lannister' } + } + fixture.child.actor = { dinklage: fixture.child } + const expected = s({ + child: { + actor: { dinklage: '[Circular]' }, + name: 'Tyrion Lannister' + }, + name: 'Tywin Lannister' + }) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('circular objects in an array', function (assert) { + const fixture = { name: 'Tywin Lannister' } + fixture.hand = [fixture, fixture] + const expected = s({ + hand: ['[Circular]', '[Circular]'], + name: 'Tywin Lannister' + }) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('nested circular references in an array', function (assert) { + const fixture = { + name: 'Tywin Lannister', + offspring: [{ name: 'Tyrion Lannister' }, { name: 'Cersei Lannister' }] + } + fixture.offspring[0].dinklage = fixture.offspring[0] + fixture.offspring[1].headey = fixture.offspring[1] + + const expected = s({ + name: 'Tywin Lannister', + offspring: [ + { dinklage: '[Circular]', name: 'Tyrion Lannister' }, + { headey: '[Circular]', name: 'Cersei Lannister' } + ] + }) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('circular arrays', function (assert) { + const fixture = [] + fixture.push(fixture, fixture) + const expected = s(['[Circular]', '[Circular]']) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('nested circular arrays', function (assert) { + const fixture = [] + fixture.push( + { name: 'Jon Snow', bastards: fixture }, + { name: 'Ramsay Bolton', bastards: fixture } + ) + const expected = s([ + { bastards: '[Circular]', name: 'Jon Snow' }, + { bastards: '[Circular]', name: 'Ramsay Bolton' } + ]) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('repeated non-circular references in objects', function (assert) { + const daenerys = { name: 'Daenerys Targaryen' } + const fixture = { + motherOfDragons: daenerys, + queenOfMeereen: daenerys + } + const expected = s(fixture) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('repeated non-circular references in arrays', function (assert) { + const daenerys = { name: 'Daenerys Targaryen' } + const fixture = [daenerys, daenerys] + const expected = s(fixture) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('double child circular reference', function (assert) { + // create circular reference + const child = { name: 'Tyrion Lannister' } + child.dinklage = child + + // include it twice in the fixture + const fixture = { name: 'Tywin Lannister', childA: child, childB: child } + const cloned = clone(fixture) + const expected = s({ + childA: { + dinklage: '[Circular]', + name: 'Tyrion Lannister' + }, + childB: { + dinklage: '[Circular]', + name: 'Tyrion Lannister' + }, + name: 'Tywin Lannister' + }) + const actual = fss(fixture) + assert.equal(actual, expected) + + // check if the fixture has not been modified + assert.same(fixture, cloned) + assert.end() +}) + +test('child circular reference with toJSON', function (assert) { + // Create a test object that has an overridden `toJSON` property + TestObject.prototype.toJSON = function () { + return { special: 'case' } + } + function TestObject (content) {} + + // Creating a simple circular object structure + const parentObject = {} + parentObject.childObject = new TestObject() + parentObject.childObject.parentObject = parentObject + + // Creating a simple circular object structure + const otherParentObject = new TestObject() + otherParentObject.otherChildObject = {} + otherParentObject.otherChildObject.otherParentObject = otherParentObject + + // Making sure our original tests work + assert.same(parentObject.childObject.parentObject, parentObject) + assert.same( + otherParentObject.otherChildObject.otherParentObject, + otherParentObject + ) + + // Should both be idempotent + assert.equal(fss(parentObject), '{"childObject":{"special":"case"}}') + assert.equal(fss(otherParentObject), '{"special":"case"}') + + // Therefore the following assertion should be `true` + assert.same(parentObject.childObject.parentObject, parentObject) + assert.same( + otherParentObject.otherChildObject.otherParentObject, + otherParentObject + ) + + assert.end() +}) + +test('null object', function (assert) { + const expected = s(null) + const actual = fss(null) + assert.equal(actual, expected) + assert.end() +}) + +test('null property', function (assert) { + const expected = s({ f: null }) + const actual = fss({ f: null }) + assert.equal(actual, expected) + assert.end() +}) + +test('nested child circular reference in toJSON', function (assert) { + var circle = { some: 'data' } + circle.circle = circle + var a = { + b: { + toJSON: function () { + a.b = 2 + return '[Redacted]' + } + }, + baz: { + circle, + toJSON: function () { + a.baz = circle + return '[Redacted]' + } + } + } + var o = { + a, + bar: a + } + + const expected = s({ + a: { + b: '[Redacted]', + baz: '[Redacted]' + }, + bar: { + // TODO: This is a known limitation of the current implementation. + // The ideal result would be: + // + // b: 2, + // baz: { + // circle: '[Circular]', + // some: 'data' + // } + // + b: '[Redacted]', + baz: '[Redacted]' + } + }) + const actual = fss(o) + assert.equal(actual, expected) + assert.end() +}) + +test('circular getters are restored when stringified', function (assert) { + const fixture = { + name: 'Tywin Lannister', + get circle () { + return fixture + } + } + fss(fixture) + + assert.equal(fixture.circle, fixture) + assert.end() +}) + +test('non-configurable circular getters use a replacer instead of markers', function (assert) { + const fixture = { name: 'Tywin Lannister' } + Object.defineProperty(fixture, 'circle', { + configurable: false, + get: function () { + return fixture + }, + enumerable: true + }) + + fss(fixture) + + assert.equal(fixture.circle, fixture) + assert.end() +}) + +test('getter child circular reference', function (assert) { + const fixture = { + name: 'Tywin Lannister', + child: { + name: 'Tyrion Lannister', + get dinklage () { + return fixture.child + } + }, + get self () { + return fixture + } + } + + const expected = s({ + child: { + dinklage: '[Circular]', + name: 'Tyrion Lannister' + }, + name: 'Tywin Lannister', + self: '[Circular]' + }) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('Proxy throwing', function (assert) { + assert.plan(1) + const s = new stream.PassThrough() + s.resume() + s.write('', () => { + assert.end() + }) + const actual = fss({ s, p: new Proxy({}, { get () { throw new Error('kaboom') } }) }) + assert.equal(actual, '"[unable to serialize, circular reference is too complex to analyze]"') +}) + +test('depthLimit option - will replace deep objects', function (assert) { + const fixture = { + name: 'Tywin Lannister', + child: { + name: 'Tyrion Lannister' + }, + get self () { + return fixture + } + } + + const expected = s({ + child: '[...]', + name: 'Tywin Lannister', + self: '[Circular]' + }) + const actual = fss(fixture, undefined, undefined, { + depthLimit: 1, + edgesLimit: 1 + }) + assert.equal(actual, expected) + assert.end() +}) + +test('edgesLimit option - will replace deep objects', function (assert) { + const fixture = { + object: { + 1: { test: 'test' }, + 2: { test: 'test' }, + 3: { test: 'test' }, + 4: { test: 'test' } + }, + array: [ + { test: 'test' }, + { test: 'test' }, + { test: 'test' }, + { test: 'test' } + ], + get self () { + return fixture + } + } + + const expected = s({ + array: [{ test: 'test' }, { test: 'test' }, { test: 'test' }, '[...]'], + object: { + 1: { test: 'test' }, + 2: { test: 'test' }, + 3: { test: 'test' }, + 4: '[...]' + }, + self: '[Circular]' + }) + const actual = fss(fixture, undefined, undefined, { + depthLimit: 3, + edgesLimit: 3 + }) + assert.equal(actual, expected) + assert.end() +}) diff --git a/node_modules/fast-safe-stringify/test.js b/node_modules/fast-safe-stringify/test.js new file mode 100644 index 000000000..a4170e96c --- /dev/null +++ b/node_modules/fast-safe-stringify/test.js @@ -0,0 +1,397 @@ +const test = require('tap').test +const fss = require('./') +const clone = require('clone') +const s = JSON.stringify +const stream = require('stream') + +test('circular reference to root', function (assert) { + const fixture = { name: 'Tywin Lannister' } + fixture.circle = fixture + const expected = s({ name: 'Tywin Lannister', circle: '[Circular]' }) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('circular getter reference to root', function (assert) { + const fixture = { + name: 'Tywin Lannister', + get circle () { + return fixture + } + } + const expected = s({ name: 'Tywin Lannister', circle: '[Circular]' }) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('nested circular reference to root', function (assert) { + const fixture = { name: 'Tywin Lannister' } + fixture.id = { circle: fixture } + const expected = s({ name: 'Tywin Lannister', id: { circle: '[Circular]' } }) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('child circular reference', function (assert) { + const fixture = { + name: 'Tywin Lannister', + child: { name: 'Tyrion Lannister' } + } + fixture.child.dinklage = fixture.child + const expected = s({ + name: 'Tywin Lannister', + child: { + name: 'Tyrion Lannister', + dinklage: '[Circular]' + } + }) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('nested child circular reference', function (assert) { + const fixture = { + name: 'Tywin Lannister', + child: { name: 'Tyrion Lannister' } + } + fixture.child.actor = { dinklage: fixture.child } + const expected = s({ + name: 'Tywin Lannister', + child: { + name: 'Tyrion Lannister', + actor: { dinklage: '[Circular]' } + } + }) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('circular objects in an array', function (assert) { + const fixture = { name: 'Tywin Lannister' } + fixture.hand = [fixture, fixture] + const expected = s({ + name: 'Tywin Lannister', + hand: ['[Circular]', '[Circular]'] + }) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('nested circular references in an array', function (assert) { + const fixture = { + name: 'Tywin Lannister', + offspring: [{ name: 'Tyrion Lannister' }, { name: 'Cersei Lannister' }] + } + fixture.offspring[0].dinklage = fixture.offspring[0] + fixture.offspring[1].headey = fixture.offspring[1] + + const expected = s({ + name: 'Tywin Lannister', + offspring: [ + { name: 'Tyrion Lannister', dinklage: '[Circular]' }, + { name: 'Cersei Lannister', headey: '[Circular]' } + ] + }) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('circular arrays', function (assert) { + const fixture = [] + fixture.push(fixture, fixture) + const expected = s(['[Circular]', '[Circular]']) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('nested circular arrays', function (assert) { + const fixture = [] + fixture.push( + { name: 'Jon Snow', bastards: fixture }, + { name: 'Ramsay Bolton', bastards: fixture } + ) + const expected = s([ + { name: 'Jon Snow', bastards: '[Circular]' }, + { name: 'Ramsay Bolton', bastards: '[Circular]' } + ]) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('repeated non-circular references in objects', function (assert) { + const daenerys = { name: 'Daenerys Targaryen' } + const fixture = { + motherOfDragons: daenerys, + queenOfMeereen: daenerys + } + const expected = s(fixture) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('repeated non-circular references in arrays', function (assert) { + const daenerys = { name: 'Daenerys Targaryen' } + const fixture = [daenerys, daenerys] + const expected = s(fixture) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('double child circular reference', function (assert) { + // create circular reference + const child = { name: 'Tyrion Lannister' } + child.dinklage = child + + // include it twice in the fixture + const fixture = { name: 'Tywin Lannister', childA: child, childB: child } + const cloned = clone(fixture) + const expected = s({ + name: 'Tywin Lannister', + childA: { + name: 'Tyrion Lannister', + dinklage: '[Circular]' + }, + childB: { + name: 'Tyrion Lannister', + dinklage: '[Circular]' + } + }) + const actual = fss(fixture) + assert.equal(actual, expected) + + // check if the fixture has not been modified + assert.same(fixture, cloned) + assert.end() +}) + +test('child circular reference with toJSON', function (assert) { + // Create a test object that has an overridden `toJSON` property + TestObject.prototype.toJSON = function () { + return { special: 'case' } + } + function TestObject (content) {} + + // Creating a simple circular object structure + const parentObject = {} + parentObject.childObject = new TestObject() + parentObject.childObject.parentObject = parentObject + + // Creating a simple circular object structure + const otherParentObject = new TestObject() + otherParentObject.otherChildObject = {} + otherParentObject.otherChildObject.otherParentObject = otherParentObject + + // Making sure our original tests work + assert.same(parentObject.childObject.parentObject, parentObject) + assert.same( + otherParentObject.otherChildObject.otherParentObject, + otherParentObject + ) + + // Should both be idempotent + assert.equal(fss(parentObject), '{"childObject":{"special":"case"}}') + assert.equal(fss(otherParentObject), '{"special":"case"}') + + // Therefore the following assertion should be `true` + assert.same(parentObject.childObject.parentObject, parentObject) + assert.same( + otherParentObject.otherChildObject.otherParentObject, + otherParentObject + ) + + assert.end() +}) + +test('null object', function (assert) { + const expected = s(null) + const actual = fss(null) + assert.equal(actual, expected) + assert.end() +}) + +test('null property', function (assert) { + const expected = s({ f: null }) + const actual = fss({ f: null }) + assert.equal(actual, expected) + assert.end() +}) + +test('nested child circular reference in toJSON', function (assert) { + const circle = { some: 'data' } + circle.circle = circle + const a = { + b: { + toJSON: function () { + a.b = 2 + return '[Redacted]' + } + }, + baz: { + circle, + toJSON: function () { + a.baz = circle + return '[Redacted]' + } + } + } + const o = { + a, + bar: a + } + + const expected = s({ + a: { + b: '[Redacted]', + baz: '[Redacted]' + }, + bar: { + b: 2, + baz: { + some: 'data', + circle: '[Circular]' + } + } + }) + const actual = fss(o) + assert.equal(actual, expected) + assert.end() +}) + +test('circular getters are restored when stringified', function (assert) { + const fixture = { + name: 'Tywin Lannister', + get circle () { + return fixture + } + } + fss(fixture) + + assert.equal(fixture.circle, fixture) + assert.end() +}) + +test('non-configurable circular getters use a replacer instead of markers', function (assert) { + const fixture = { name: 'Tywin Lannister' } + Object.defineProperty(fixture, 'circle', { + configurable: false, + get: function () { + return fixture + }, + enumerable: true + }) + + fss(fixture) + + assert.equal(fixture.circle, fixture) + assert.end() +}) + +test('getter child circular reference are replaced instead of marked', function (assert) { + const fixture = { + name: 'Tywin Lannister', + child: { + name: 'Tyrion Lannister', + get dinklage () { + return fixture.child + } + }, + get self () { + return fixture + } + } + + const expected = s({ + name: 'Tywin Lannister', + child: { + name: 'Tyrion Lannister', + dinklage: '[Circular]' + }, + self: '[Circular]' + }) + const actual = fss(fixture) + assert.equal(actual, expected) + assert.end() +}) + +test('Proxy throwing', function (assert) { + assert.plan(1) + const s = new stream.PassThrough() + s.resume() + s.write('', () => { + assert.end() + }) + const actual = fss({ s, p: new Proxy({}, { get () { throw new Error('kaboom') } }) }) + assert.equal(actual, '"[unable to serialize, circular reference is too complex to analyze]"') +}) + +test('depthLimit option - will replace deep objects', function (assert) { + const fixture = { + name: 'Tywin Lannister', + child: { + name: 'Tyrion Lannister' + }, + get self () { + return fixture + } + } + + const expected = s({ + name: 'Tywin Lannister', + child: '[...]', + self: '[Circular]' + }) + const actual = fss(fixture, undefined, undefined, { + depthLimit: 1, + edgesLimit: 1 + }) + assert.equal(actual, expected) + assert.end() +}) + +test('edgesLimit option - will replace deep objects', function (assert) { + const fixture = { + object: { + 1: { test: 'test' }, + 2: { test: 'test' }, + 3: { test: 'test' }, + 4: { test: 'test' } + }, + array: [ + { test: 'test' }, + { test: 'test' }, + { test: 'test' }, + { test: 'test' } + ], + get self () { + return fixture + } + } + + const expected = s({ + object: { + 1: { test: 'test' }, + 2: { test: 'test' }, + 3: { test: 'test' }, + 4: '[...]' + }, + array: [{ test: 'test' }, { test: 'test' }, { test: 'test' }, '[...]'], + self: '[Circular]' + }) + const actual = fss(fixture, undefined, undefined, { + depthLimit: 3, + edgesLimit: 3 + }) + assert.equal(actual, expected) + assert.end() +}) diff --git a/node_modules/formidable/LICENSE b/node_modules/formidable/LICENSE new file mode 100644 index 000000000..38d3c9cf4 --- /dev/null +++ b/node_modules/formidable/LICENSE @@ -0,0 +1,7 @@ +Copyright (C) 2011 Felix Geisendörfer + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/formidable/Readme.md b/node_modules/formidable/Readme.md new file mode 100644 index 000000000..3af3291b1 --- /dev/null +++ b/node_modules/formidable/Readme.md @@ -0,0 +1,448 @@ +

+ npm formidable package logo +

+ +# formidable [![npm version][npmv-img]][npmv-url] [![MIT license][license-img]][license-url] [![Libera Manifesto][libera-manifesto-img]][libera-manifesto-url] + +> A Node.js module for parsing form data, especially file uploads. + +### Important Notes + +For more info, check the [CHANGELOG](https://github.com/node-formidable/formidable/blob/master/CHANGELOG.md) on the master branch. + +#### v1 is deprecated + +All `v1` versions are deprecated in NPM for over 2 years. You can find it at `formidable@v1` or `formidable@legacy` on NPM, and on [v1-legacy branch][v1branch] on GitHub. +We highly recommend to use `v2` or `v3`. Both are already in use by many, especially `v2` which was on `formidable@canary` for 2 years. + +- **Status: Not Maintained!** +- We won't provide support or accept reports on that version. +- **No Backporting:** bugfixes, security fixes, or new features WILL NOT happen! +- Please move to at least **v2**! +- Try with installing `formidable@v2` and if still have the problem - report! + +--- + +#### v2 is the new `latest` +The `v2` will be simultaneously on two places for some time - `formidable@latest` and `formidable@v2`. +The source code be available **only** on [v2 branch][v2branch]. +If you want to use v2, it's recommended to use the v2 dist-tag `formidable@v2`. + +**Main Differences from v1:** +- Better organization and modernized code, requiring newer Node.js versions (>= v10). +- A lot of bugfixes, closed issues, merged or closed PRs. +- **Backward compatible to v1!** Should not have problems, the major version bump is just for ensurance. +- Better docs, new features (plugins, parsers, options) and optimizations. + +--- + +#### v3 - ESModules, Promises, Monorepo structure +We recommend to use `formidable@v3`, as it uses more modern Node.js Streams, has support for Promises and more stuff. +You can see more info and track some ideas on [issue#635](https://github.com/node-formidable/formidable/issues/635). + +- The source code can be found on the [master branch](https://github.com/node-formidable/formidable) on GitHub. +- It will be published on `formidable@latest` after some time. +- Dropping older Node.js versions, requiring higher than v12-v14. +- Dropping v1 compatibility. +- Rewritten to ESModules, more optimizations. +- Moving to monorepo structure, more plugins & helper utils. + +[v1branch]: https://github.com/node-formidable/formidable/tree/v1-legacy +[v2branch]: https://github.com/node-formidable/formidable/tree/v2 +[v3branch]: https://github.com/node-formidable/formidable/tree/v3 + +--- + +[![Code style][codestyle-img]][codestyle-url] +[![codecoverage][codecov-img]][codecov-url] +[![linux build status][linux-build-img]][build-url] +[![windows build status][windows-build-img]][build-url] +[![macos build status][macos-build-img]][build-url] + +If you have any _how-to_ kind of questions, please read the [Contributing +Guide][contributing-url] and [Code of Conduct][code_of_conduct-url] +documents.
For bugs reports and feature requests, [please create an +issue][open-issue-url] or ping [@tunnckoCore](https://twitter.com/tunnckoCore) +at Twitter. + +[![Conventional Commits][ccommits-img]][ccommits-url] +[![Minimum Required Nodejs][nodejs-img]][npmv-url] +[![Tidelift Subcsription][tidelift-img]][tidelift-url] +[![Buy me a Kofi][kofi-img]][kofi-url] +[![Renovate App Status][renovateapp-img]][renovateapp-url] +[![Make A Pull Request][prs-welcome-img]][prs-welcome-url] + +This project is [semantically versioned](https://semver.org) and available as +part of the [Tidelift Subscription][tidelift-url] for professional grade +assurances, enhanced support and security. +[Learn more.](https://tidelift.com/subscription/pkg/npm-formidable?utm_source=npm-formidable&utm_medium=referral&utm_campaign=enterprise) + +_The maintainers of `formidable` and thousands of other packages are working +with Tidelift to deliver commercial support and maintenance for the Open Source +dependencies you use to build your applications. Save time, reduce risk, and +improve code health, while paying the maintainers of the exact dependencies you +use._ + +[![][npm-weekly-img]][npmv-url] [![][npm-monthly-img]][npmv-url] +[![][npm-yearly-img]][npmv-url] [![][npm-alltime-img]][npmv-url] + +## v1 status: not maintained! + +## Project Status: Maintained + +This module was initially developed by +[**@felixge**](https://github.com/felixge) for +[Transloadit](http://transloadit.com/), a service focused on uploading and +encoding images and videos. It has been battle-tested against hundreds of GBs of +file uploads from a large variety of clients and is considered production-ready +and is used in production for years. + +Currently, we are few maintainers trying to deal with it. :) More contributors +are always welcome! :heart: Jump on +[issue #412](https://github.com/felixge/node-formidable/issues/412) which is +closed, but if you are interested we can discuss it and add you after strict +rules, like enabling Two-Factor Auth in your npm and GitHub accounts. + +## Features + +* Fast (~500mb/sec), non-buffering multipart parser +* Automatically writing file uploads to disk +* Low memory footprint +* Graceful error handling +* Very high test coverage + +## Installation + +```sh +npm install formidable@v1 +npm install formidable@v2 +npm install formidable@v3 +``` + +This is a low-level package, and if you're using a high-level framework it may already be included. However, [Express v4](http://expressjs.com) does not include any multipart handling, nor does [body-parser](https://github.com/expressjs/body-parser). + +Note: Formidable requires [gently](http://github.com/felixge/node-gently) to run the unit tests, but you won't need it for just using the library. + +## Example + +Parse an incoming file upload. +```javascript +var formidable = require('formidable'), + http = require('http'), + util = require('util'); + +http.createServer(function(req, res) { + if (req.url == '/upload' && req.method.toLowerCase() == 'post') { + // parse a file upload + var form = new formidable.IncomingForm(); + + form.parse(req, function(err, fields, files) { + res.writeHead(200, {'content-type': 'text/plain'}); + res.write('received upload:\n\n'); + res.end(util.inspect({fields: fields, files: files})); + }); + + return; + } + + // show a file upload form + res.writeHead(200, {'content-type': 'text/html'}); + res.end( + '
'+ + '
'+ + '
'+ + ''+ + '
' + ); +}).listen(8080); +``` +## API + +### Formidable.IncomingForm +```javascript +var form = new formidable.IncomingForm() +``` +Creates a new incoming form. + +```javascript +form.encoding = 'utf-8'; +``` +Sets encoding for incoming form fields. + +```javascript +form.uploadDir = "/my/dir"; +``` +Sets the directory for placing file uploads in. You can move them later on using +`fs.rename()`. The default is `os.tmpdir()`. + +```javascript +form.keepExtensions = false; +``` +If you want the files written to `form.uploadDir` to include the extensions of the original files, set this property to `true`. + +```javascript +form.type +``` +Either 'multipart' or 'urlencoded' depending on the incoming request. + +```javascript +form.maxFieldsSize = 20 * 1024 * 1024; +``` +Limits the amount of memory all fields together (except files) can allocate in bytes. +If this value is exceeded, an `'error'` event is emitted. The default +size is 20MB. + +```javascript +form.maxFileSize = 200 * 1024 * 1024; +``` +Limits the size of uploaded file. +If this value is exceeded, an `'error'` event is emitted. The default +size is 200MB. + +```javascript +form.maxFields = 1000; +``` +Limits the number of fields that the querystring parser will decode. Defaults +to 1000 (0 for unlimited). + +```javascript +form.hash = false; +``` +If you want checksums calculated for incoming files, set this to either `'sha1'` or `'md5'`. + +```javascript +form.multiples = false; +``` +If this option is enabled, when you call `form.parse`, the `files` argument will contain arrays of files for inputs which submit multiple files using the HTML5 `multiple` attribute. + +```javascript +form.bytesReceived +``` +The amount of bytes received for this form so far. + +```javascript +form.bytesExpected +``` +The expected number of bytes in this form. + +```javascript +form.parse(request, [cb]); +``` +Parses an incoming node.js `request` containing form data. If `cb` is provided, all fields and files are collected and passed to the callback: + + +```javascript +form.parse(req, function(err, fields, files) { + // ... +}); + +form.onPart(part); +``` +You may overwrite this method if you are interested in directly accessing the multipart stream. Doing so will disable any `'field'` / `'file'` events processing which would occur otherwise, making you fully responsible for handling the processing. + +```javascript +form.onPart = function(part) { + part.addListener('data', function() { + // ... + }); +} +``` +If you want to use formidable to only handle certain parts for you, you can do so: +```javascript +form.onPart = function(part) { + if (!part.filename) { + // let formidable handle all non-file parts + form.handlePart(part); + } +} +``` +Check the code in this method for further inspiration. + + +### Formidable.File +```javascript +file.size = 0 +``` +The size of the uploaded file in bytes. If the file is still being uploaded (see `'fileBegin'` event), this property says how many bytes of the file have been written to disk yet. +```javascript +file.path = null +``` +The path this file is being written to. You can modify this in the `'fileBegin'` event in +case you are unhappy with the way formidable generates a temporary path for your files. +```javascript +file.name = null +``` +The name this file had according to the uploading client. +```javascript +file.type = null +``` +The mime type of this file, according to the uploading client. +```javascript +file.lastModifiedDate = null +``` +A date object (or `null`) containing the time this file was last written to. Mostly +here for compatibility with the [W3C File API Draft](http://dev.w3.org/2006/webapi/FileAPI/). +```javascript +file.hash = null +``` +If hash calculation was set, you can read the hex digest out of this var. + +#### Formidable.File#toJSON() + + This method returns a JSON-representation of the file, allowing you to + `JSON.stringify()` the file which is useful for logging and responding + to requests. + +### Events + + +#### 'progress' + +Emitted after each incoming chunk of data that has been parsed. Can be used to roll your own progress bar. + +```javascript +form.on('progress', function(bytesReceived, bytesExpected) { +}); +``` + + + +#### 'field' + +Emitted whenever a field / value pair has been received. + +```javascript +form.on('field', function(name, value) { +}); +``` + +#### 'fileBegin' + +Emitted whenever a new file is detected in the upload stream. Use this event if +you want to stream the file to somewhere else while buffering the upload on +the file system. + +```javascript +form.on('fileBegin', function(name, file) { +}); +``` + +#### 'file' + +Emitted whenever a field / file pair has been received. `file` is an instance of `File`. + +```javascript +form.on('file', function(name, file) { +}); +``` + +#### 'error' + +Emitted when there is an error processing the incoming form. A request that experiences an error is automatically paused, you will have to manually call `request.resume()` if you want the request to continue firing `'data'` events. + +```javascript +form.on('error', function(err) { +}); +``` + +#### 'aborted' + + +Emitted when the request was aborted by the user. Right now this can be due to a 'timeout' or 'close' event on the socket. After this event is emitted, an `error` event will follow. In the future there will be a separate 'timeout' event (needs a change in the node core). +```javascript +form.on('aborted', function() { +}); +``` + +##### 'end' +```javascript +form.on('end', function() { +}); +``` +Emitted when the entire request has been received, and all contained files have finished flushing to disk. This is a great place for you to send your response. + + + +## Changelog + +[./CHANGELOG.md](./CHANGELOG.md) + +## Credits + +- [multipart-parser](http://github.com/FooBarWidget/multipart-parser): a C++ + parser based on formidable +- [Ryan Dahl](http://twitter.com/ryah) for his work on + [http-parser](http://github.com/ry/http-parser) which heavily inspired the + initial `multipart_parser.js`. + +From [Felix blog post](https://felixge.de/2013/03/11/the-pull-request-hack/): + +- [Sven Lito](https://github.com/svnlto) for fixing bugs and merging patches +- [egirshov](https://github.com/egirshov) for contributing many improvements to the node-formidable multipart parser +- [Andrew Kelley](https://github.com/superjoe30) for also helping with fixing bugs and making improvements +- [Mike Frey](https://github.com/mikefrey) for contributing JSON support + + +## Contributing + +If the documentation is unclear or has a typo, please click on the page's `Edit` +button (pencil icon) and suggest a correction. If you would like to help us fix +a bug or add a new feature, please check our [Contributing +Guide][contributing-url]. Pull requests are welcome! + + +## License + +Formidable is licensed under the [MIT License][license-url]. + + + + +[codestyle-url]: https://github.com/airbnb/javascript +[codestyle-img]: https://badgen.net/badge/code%20style/airbnb%20%2B%20prettier/ff5a5f?icon=airbnb&cache=300 +[codecov-url]: https://codecov.io/gh/node-formidable/formidable +[codecov-img]: https://badgen.net/codecov/c/github/node-formidable/formidable/master?icon=codecov +[npmv-canary-img]: https://badgen.net/npm/v/formidable/canary?icon=npm +[npmv-dev-img]: https://badgen.net/npm/v/formidable/dev?icon=npm +[npmv-img]: https://badgen.net/npm/v/formidable?icon=npm +[npmv-url]: https://npmjs.com/package/formidable +[license-img]: https://badgen.net/npm/license/formidable +[license-url]: https://github.com/node-formidable/formidable/blob/master/LICENSE +[chat-img]: https://badgen.net/badge/chat/on%20gitter/46BC99?icon=gitter +[chat-url]: https://gitter.im/node-formidable/Lobby +[libera-manifesto-url]: https://liberamanifesto.com +[libera-manifesto-img]: https://badgen.net/badge/libera/manifesto/grey +[renovateapp-url]: https://renovatebot.com +[renovateapp-img]: https://badgen.net/badge/renovate/enabled/green?cache=300 +[prs-welcome-img]: https://badgen.net/badge/PRs/welcome/green?cache=300 +[prs-welcome-url]: http://makeapullrequest.com +[twitter-url]: https://twitter.com/tunnckoCore +[twitter-img]: https://badgen.net/twitter/follow/tunnckoCore?icon=twitter&color=1da1f2&cache=300 + +[npm-weekly-img]: https://badgen.net/npm/dw/formidable?icon=npm&cache=300 +[npm-monthly-img]: https://badgen.net/npm/dm/formidable?icon=npm&cache=300 +[npm-yearly-img]: https://badgen.net/npm/dy/formidable?icon=npm&cache=300 +[npm-alltime-img]: https://badgen.net/npm/dt/formidable?icon=npm&cache=300&label=total%20downloads + +[nodejs-img]: https://badgen.net/badge/node/>=%2010.13/green?cache=300 + +[ccommits-url]: https://conventionalcommits.org/ +[ccommits-img]: https://badgen.net/badge/conventional%20commits/v1.0.0/green?cache=300 + +[contributing-url]: https://github.com/node-formidable/.github/blob/master/CONTRIBUTING.md +[code_of_conduct-url]: https://github.com/node-formidable/.github/blob/master/CODE_OF_CONDUCT.md + +[open-issue-url]: https://github.com/node-formidable/formidable/issues/new + +[tidelift-url]: https://tidelift.com/subscription/pkg/npm-formidable?utm_source=npm-formidable&utm_medium=referral&utm_campaign=enterprise +[tidelift-img]: https://badgen.net/badge/tidelift/subscription/4B5168?labelColor=F6914D + +[kofi-url]: https://ko-fi.com/tunnckoCore/commissions +[kofi-img]: https://badgen.net/badge/ko-fi/support/29abe0c2?cache=300&icon=https://rawcdn.githack.com/tunnckoCore/badgen-icons/f8264c6414e0bec449dd86f2241d50a9b89a1203/icons/kofi.svg + +[linux-build-img]: https://badgen.net/github/checks/node-formidable/formidable/master/ubuntu?cache=300&label=linux%20build&icon=github +[macos-build-img]: https://badgen.net/github/checks/node-formidable/formidable/master/macos?cache=300&label=macos%20build&icon=github +[windows-build-img]: https://badgen.net//github/checks/node-formidable/formidable/master/windows?cache=300&label=windows%20build&icon=github +[build-url]: https://github.com/node-formidable/formidable/actions?query=workflow%3Anodejs + + diff --git a/node_modules/formidable/lib/file.js b/node_modules/formidable/lib/file.js new file mode 100644 index 000000000..50d34c099 --- /dev/null +++ b/node_modules/formidable/lib/file.js @@ -0,0 +1,81 @@ +if (global.GENTLY) require = GENTLY.hijack(require); + +var util = require('util'), + fs = require('fs'), + EventEmitter = require('events').EventEmitter, + crypto = require('crypto'); + +function File(properties) { + EventEmitter.call(this); + + this.size = 0; + this.path = null; + this.name = null; + this.type = null; + this.hash = null; + this.lastModifiedDate = null; + + this._writeStream = null; + + for (var key in properties) { + this[key] = properties[key]; + } + + if(typeof this.hash === 'string') { + this.hash = crypto.createHash(properties.hash); + } else { + this.hash = null; + } +} +module.exports = File; +util.inherits(File, EventEmitter); + +File.prototype.open = function() { + this._writeStream = new fs.WriteStream(this.path); +}; + +File.prototype.toJSON = function() { + var json = { + size: this.size, + path: this.path, + name: this.name, + type: this.type, + mtime: this.lastModifiedDate, + length: this.length, + filename: this.filename, + mime: this.mime + }; + if (this.hash && this.hash != "") { + json.hash = this.hash; + } + return json; +}; + +File.prototype.write = function(buffer, cb) { + var self = this; + if (self.hash) { + self.hash.update(buffer); + } + + if (this._writeStream.closed) { + return cb(); + } + + this._writeStream.write(buffer, function() { + self.lastModifiedDate = new Date(); + self.size += buffer.length; + self.emit('progress', self.size); + cb(); + }); +}; + +File.prototype.end = function(cb) { + var self = this; + if (self.hash) { + self.hash = self.hash.digest('hex'); + } + this._writeStream.end(function() { + self.emit('end'); + cb(); + }); +}; diff --git a/node_modules/formidable/lib/incoming_form.js b/node_modules/formidable/lib/incoming_form.js new file mode 100644 index 000000000..606dbaa76 --- /dev/null +++ b/node_modules/formidable/lib/incoming_form.js @@ -0,0 +1,564 @@ +if (global.GENTLY) require = GENTLY.hijack(require); + +var crypto = require('crypto'); +var fs = require('fs'); +var util = require('util'), + path = require('path'), + File = require('./file'), + MultipartParser = require('./multipart_parser').MultipartParser, + QuerystringParser = require('./querystring_parser').QuerystringParser, + OctetParser = require('./octet_parser').OctetParser, + JSONParser = require('./json_parser').JSONParser, + StringDecoder = require('string_decoder').StringDecoder, + EventEmitter = require('events').EventEmitter, + Stream = require('stream').Stream, + os = require('os'); + +function IncomingForm(opts) { + if (!(this instanceof IncomingForm)) return new IncomingForm(opts); + EventEmitter.call(this); + + opts=opts||{}; + + this.error = null; + this.ended = false; + + this.maxFields = opts.maxFields || 1000; + this.maxFieldsSize = opts.maxFieldsSize || 20 * 1024 * 1024; + this.maxFileSize = opts.maxFileSize || 200 * 1024 * 1024; + this.keepExtensions = opts.keepExtensions || false; + this.uploadDir = opts.uploadDir || (os.tmpdir && os.tmpdir()) || os.tmpDir(); + this.encoding = opts.encoding || 'utf-8'; + this.headers = null; + this.type = null; + this.hash = opts.hash || false; + this.multiples = opts.multiples || false; + + this.bytesReceived = null; + this.bytesExpected = null; + + this._parser = null; + this._flushing = 0; + this._fieldsSize = 0; + this._fileSize = 0; + this.openedFiles = []; + + return this; +} +util.inherits(IncomingForm, EventEmitter); +exports.IncomingForm = IncomingForm; + +IncomingForm.prototype.parse = function(req, cb) { + this.pause = function() { + try { + req.pause(); + } catch (err) { + // the stream was destroyed + if (!this.ended) { + // before it was completed, crash & burn + this._error(err); + } + return false; + } + return true; + }; + + this.resume = function() { + try { + req.resume(); + } catch (err) { + // the stream was destroyed + if (!this.ended) { + // before it was completed, crash & burn + this._error(err); + } + return false; + } + + return true; + }; + + // Setup callback first, so we don't miss anything from data events emitted + // immediately. + if (cb) { + var fields = {}, files = {}; + this + .on('field', function(name, value) { + fields[name] = value; + }) + .on('file', function(name, file) { + if (this.multiples) { + if (files[name]) { + if (!Array.isArray(files[name])) { + files[name] = [files[name]]; + } + files[name].push(file); + } else { + files[name] = file; + } + } else { + files[name] = file; + } + }) + .on('error', function(err) { + cb(err, fields, files); + }) + .on('end', function() { + cb(null, fields, files); + }); + } + + // Parse headers and setup the parser, ready to start listening for data. + this.writeHeaders(req.headers); + + // Start listening for data. + var self = this; + req + .on('error', function(err) { + self._error(err); + }) + .on('aborted', function() { + self.emit('aborted'); + self._error(new Error('Request aborted')); + }) + .on('data', function(buffer) { + self.write(buffer); + }) + .on('end', function() { + if (self.error) { + return; + } + + var err = self._parser.end(); + if (err) { + self._error(err); + } + }); + + return this; +}; + +IncomingForm.prototype.writeHeaders = function(headers) { + this.headers = headers; + this._parseContentLength(); + this._parseContentType(); +}; + +IncomingForm.prototype.write = function(buffer) { + if (this.error) { + return; + } + if (!this._parser) { + this._error(new Error('uninitialized parser')); + return; + } + if (typeof this._parser.write !== 'function') { + this._error(new Error('did not expect data')); + return; + } + + this.bytesReceived += buffer.length; + this.emit('progress', this.bytesReceived, this.bytesExpected); + + var bytesParsed = this._parser.write(buffer); + if (bytesParsed !== buffer.length) { + this._error(new Error('parser error, '+bytesParsed+' of '+buffer.length+' bytes parsed')); + } + + return bytesParsed; +}; + +IncomingForm.prototype.pause = function() { + // this does nothing, unless overwritten in IncomingForm.parse + return false; +}; + +IncomingForm.prototype.resume = function() { + // this does nothing, unless overwritten in IncomingForm.parse + return false; +}; + +IncomingForm.prototype.onPart = function(part) { + // this method can be overwritten by the user + this.handlePart(part); +}; + +IncomingForm.prototype.handlePart = function(part) { + var self = this; + + // This MUST check exactly for undefined. You can not change it to !part.filename. + if (part.filename === undefined) { + var value = '' + , decoder = new StringDecoder(this.encoding); + + part.on('data', function(buffer) { + self._fieldsSize += buffer.length; + if (self._fieldsSize > self.maxFieldsSize) { + self._error(new Error('maxFieldsSize exceeded, received '+self._fieldsSize+' bytes of field data')); + return; + } + value += decoder.write(buffer); + }); + + part.on('end', function() { + self.emit('field', part.name, value); + }); + return; + } + + this._flushing++; + + var file = new File({ + path: this._uploadPath(part.filename), + name: part.filename, + type: part.mime, + hash: self.hash + }); + + this.emit('fileBegin', part.name, file); + + file.open(); + this.openedFiles.push(file); + + part.on('data', function(buffer) { + self._fileSize += buffer.length; + if (self._fileSize > self.maxFileSize) { + self._error(new Error('maxFileSize exceeded, received '+self._fileSize+' bytes of file data')); + return; + } + if (buffer.length == 0) { + return; + } + self.pause(); + file.write(buffer, function() { + self.resume(); + }); + }); + + part.on('end', function() { + file.end(function() { + self._flushing--; + self.emit('file', part.name, file); + self._maybeEnd(); + }); + }); +}; + +function dummyParser(self) { + return { + end: function () { + self.ended = true; + self._maybeEnd(); + return null; + } + }; +} + +IncomingForm.prototype._parseContentType = function() { + if (this.bytesExpected === 0) { + this._parser = dummyParser(this); + return; + } + + if (!this.headers['content-type']) { + this._error(new Error('bad content-type header, no content-type')); + return; + } + + if (this.headers['content-type'].match(/octet-stream/i)) { + this._initOctetStream(); + return; + } + + if (this.headers['content-type'].match(/urlencoded/i)) { + this._initUrlencoded(); + return; + } + + if (this.headers['content-type'].match(/multipart/i)) { + var m = this.headers['content-type'].match(/boundary=(?:"([^"]+)"|([^;]+))/i); + if (m) { + this._initMultipart(m[1] || m[2]); + } else { + this._error(new Error('bad content-type header, no multipart boundary')); + } + return; + } + + if (this.headers['content-type'].match(/json/i)) { + this._initJSONencoded(); + return; + } + + this._error(new Error('bad content-type header, unknown content-type: '+this.headers['content-type'])); +}; + +IncomingForm.prototype._error = function(err) { + if (this.error || this.ended) { + return; + } + + this.error = err; + this.emit('error', err); + + if (Array.isArray(this.openedFiles)) { + this.openedFiles.forEach(function(file) { + file._writeStream + .on('error', function() {}) + .destroy(); + setTimeout(fs.unlink, 0, file.path, function(error) { }); + }); + } +}; + +IncomingForm.prototype._parseContentLength = function() { + this.bytesReceived = 0; + if (this.headers['content-length']) { + this.bytesExpected = parseInt(this.headers['content-length'], 10); + } else if (this.headers['transfer-encoding'] === undefined) { + this.bytesExpected = 0; + } + + if (this.bytesExpected !== null) { + this.emit('progress', this.bytesReceived, this.bytesExpected); + } +}; + +IncomingForm.prototype._newParser = function() { + return new MultipartParser(); +}; + +IncomingForm.prototype._initMultipart = function(boundary) { + this.type = 'multipart'; + + var parser = new MultipartParser(), + self = this, + headerField, + headerValue, + part; + + parser.initWithBoundary(boundary); + + parser.onPartBegin = function() { + part = new Stream(); + part.readable = true; + part.headers = {}; + part.name = null; + part.filename = null; + part.mime = null; + + part.transferEncoding = 'binary'; + part.transferBuffer = ''; + + headerField = ''; + headerValue = ''; + }; + + parser.onHeaderField = function(b, start, end) { + headerField += b.toString(self.encoding, start, end); + }; + + parser.onHeaderValue = function(b, start, end) { + headerValue += b.toString(self.encoding, start, end); + }; + + parser.onHeaderEnd = function() { + headerField = headerField.toLowerCase(); + part.headers[headerField] = headerValue; + + // matches either a quoted-string or a token (RFC 2616 section 19.5.1) + var m = headerValue.match(/\bname=("([^"]*)"|([^\(\)<>@,;:\\"\/\[\]\?=\{\}\s\t/]+))/i); + if (headerField == 'content-disposition') { + if (m) { + part.name = m[2] || m[3] || ''; + } + + part.filename = self._fileName(headerValue); + } else if (headerField == 'content-type') { + part.mime = headerValue; + } else if (headerField == 'content-transfer-encoding') { + part.transferEncoding = headerValue.toLowerCase(); + } + + headerField = ''; + headerValue = ''; + }; + + parser.onHeadersEnd = function() { + switch(part.transferEncoding){ + case 'binary': + case '7bit': + case '8bit': + parser.onPartData = function(b, start, end) { + part.emit('data', b.slice(start, end)); + }; + + parser.onPartEnd = function() { + part.emit('end'); + }; + break; + + case 'base64': + parser.onPartData = function(b, start, end) { + part.transferBuffer += b.slice(start, end).toString('ascii'); + + /* + four bytes (chars) in base64 converts to three bytes in binary + encoding. So we should always work with a number of bytes that + can be divided by 4, it will result in a number of buytes that + can be divided vy 3. + */ + var offset = parseInt(part.transferBuffer.length / 4, 10) * 4; + part.emit('data', new Buffer(part.transferBuffer.substring(0, offset), 'base64')); + part.transferBuffer = part.transferBuffer.substring(offset); + }; + + parser.onPartEnd = function() { + part.emit('data', new Buffer(part.transferBuffer, 'base64')); + part.emit('end'); + }; + break; + + default: + return self._error(new Error('unknown transfer-encoding')); + } + + self.onPart(part); + }; + + + parser.onEnd = function() { + self.ended = true; + self._maybeEnd(); + }; + + this._parser = parser; +}; + +IncomingForm.prototype._fileName = function(headerValue) { + // matches either a quoted-string or a token (RFC 2616 section 19.5.1) + var m = headerValue.match(/\bfilename=("(.*?)"|([^\(\)<>@,;:\\"\/\[\]\?=\{\}\s\t/]+))($|;\s)/i); + if (!m) return; + + var match = m[2] || m[3] || ''; + var filename = match.substr(match.lastIndexOf('\\') + 1); + filename = filename.replace(/%22/g, '"'); + filename = filename.replace(/&#([\d]{4});/g, function(m, code) { + return String.fromCharCode(code); + }); + return filename; +}; + +IncomingForm.prototype._initUrlencoded = function() { + this.type = 'urlencoded'; + + var parser = new QuerystringParser(this.maxFields) + , self = this; + + parser.onField = function(key, val) { + self.emit('field', key, val); + }; + + parser.onEnd = function() { + self.ended = true; + self._maybeEnd(); + }; + + this._parser = parser; +}; + +IncomingForm.prototype._initOctetStream = function() { + this.type = 'octet-stream'; + var filename = this.headers['x-file-name']; + var mime = this.headers['content-type']; + + var file = new File({ + path: this._uploadPath(filename), + name: filename, + type: mime + }); + + this.emit('fileBegin', filename, file); + file.open(); + this.openedFiles.push(file); + this._flushing++; + + var self = this; + + self._parser = new OctetParser(); + + //Keep track of writes that haven't finished so we don't emit the file before it's done being written + var outstandingWrites = 0; + + self._parser.on('data', function(buffer){ + self.pause(); + outstandingWrites++; + + file.write(buffer, function() { + outstandingWrites--; + self.resume(); + + if(self.ended){ + self._parser.emit('doneWritingFile'); + } + }); + }); + + self._parser.on('end', function(){ + self._flushing--; + self.ended = true; + + var done = function(){ + file.end(function() { + self.emit('file', 'file', file); + self._maybeEnd(); + }); + }; + + if(outstandingWrites === 0){ + done(); + } else { + self._parser.once('doneWritingFile', done); + } + }); +}; + +IncomingForm.prototype._initJSONencoded = function() { + this.type = 'json'; + + var parser = new JSONParser(this) + , self = this; + + parser.onField = function(key, val) { + self.emit('field', key, val); + }; + + parser.onEnd = function() { + self.ended = true; + self._maybeEnd(); + }; + + this._parser = parser; +}; + +IncomingForm.prototype._uploadPath = function(filename) { + var buf = crypto.randomBytes(16); + var name = 'upload_' + buf.toString('hex'); + + if (this.keepExtensions) { + var ext = path.extname(filename); + ext = ext.replace(/(\.[a-z0-9]+).*/i, '$1'); + + name += ext; + } + + return path.join(this.uploadDir, name); +}; + +IncomingForm.prototype._maybeEnd = function() { + if (!this.ended || this._flushing || this.error) { + return; + } + + this.emit('end'); +}; diff --git a/node_modules/formidable/lib/index.js b/node_modules/formidable/lib/index.js new file mode 100644 index 000000000..7a6e3e109 --- /dev/null +++ b/node_modules/formidable/lib/index.js @@ -0,0 +1,3 @@ +var IncomingForm = require('./incoming_form').IncomingForm; +IncomingForm.IncomingForm = IncomingForm; +module.exports = IncomingForm; diff --git a/node_modules/formidable/lib/json_parser.js b/node_modules/formidable/lib/json_parser.js new file mode 100644 index 000000000..28a23badd --- /dev/null +++ b/node_modules/formidable/lib/json_parser.js @@ -0,0 +1,30 @@ +if (global.GENTLY) require = GENTLY.hijack(require); + +var Buffer = require('buffer').Buffer; + +function JSONParser(parent) { + this.parent = parent; + this.chunks = []; + this.bytesWritten = 0; +} +exports.JSONParser = JSONParser; + +JSONParser.prototype.write = function(buffer) { + this.bytesWritten += buffer.length; + this.chunks.push(buffer); + return buffer.length; +}; + +JSONParser.prototype.end = function() { + try { + var fields = JSON.parse(Buffer.concat(this.chunks)); + for (var field in fields) { + this.onField(field, fields[field]); + } + } catch (e) { + this.parent.emit('error', e); + } + this.data = null; + + this.onEnd(); +}; diff --git a/node_modules/formidable/lib/multipart_parser.js b/node_modules/formidable/lib/multipart_parser.js new file mode 100644 index 000000000..36de2b0d3 --- /dev/null +++ b/node_modules/formidable/lib/multipart_parser.js @@ -0,0 +1,332 @@ +var Buffer = require('buffer').Buffer, + s = 0, + S = + { PARSER_UNINITIALIZED: s++, + START: s++, + START_BOUNDARY: s++, + HEADER_FIELD_START: s++, + HEADER_FIELD: s++, + HEADER_VALUE_START: s++, + HEADER_VALUE: s++, + HEADER_VALUE_ALMOST_DONE: s++, + HEADERS_ALMOST_DONE: s++, + PART_DATA_START: s++, + PART_DATA: s++, + PART_END: s++, + END: s++ + }, + + f = 1, + F = + { PART_BOUNDARY: f, + LAST_BOUNDARY: f *= 2 + }, + + LF = 10, + CR = 13, + SPACE = 32, + HYPHEN = 45, + COLON = 58, + A = 97, + Z = 122, + + lower = function(c) { + return c | 0x20; + }; + +for (s in S) { + exports[s] = S[s]; +} + +function MultipartParser() { + this.boundary = null; + this.boundaryChars = null; + this.lookbehind = null; + this.state = S.PARSER_UNINITIALIZED; + + this.index = null; + this.flags = 0; +} +exports.MultipartParser = MultipartParser; + +MultipartParser.stateToString = function(stateNumber) { + for (var state in S) { + var number = S[state]; + if (number === stateNumber) return state; + } +}; + +MultipartParser.prototype.initWithBoundary = function(str) { + this.boundary = new Buffer(str.length+4); + this.boundary.write('\r\n--', 0); + this.boundary.write(str, 4); + this.lookbehind = new Buffer(this.boundary.length+8); + this.state = S.START; + + this.boundaryChars = {}; + for (var i = 0; i < this.boundary.length; i++) { + this.boundaryChars[this.boundary[i]] = true; + } +}; + +MultipartParser.prototype.write = function(buffer) { + var self = this, + i = 0, + len = buffer.length, + prevIndex = this.index, + index = this.index, + state = this.state, + flags = this.flags, + lookbehind = this.lookbehind, + boundary = this.boundary, + boundaryChars = this.boundaryChars, + boundaryLength = this.boundary.length, + boundaryEnd = boundaryLength - 1, + bufferLength = buffer.length, + c, + cl, + + mark = function(name) { + self[name+'Mark'] = i; + }, + clear = function(name) { + delete self[name+'Mark']; + }, + callback = function(name, buffer, start, end) { + if (start !== undefined && start === end) { + return; + } + + var callbackSymbol = 'on'+name.substr(0, 1).toUpperCase()+name.substr(1); + if (callbackSymbol in self) { + self[callbackSymbol](buffer, start, end); + } + }, + dataCallback = function(name, clear) { + var markSymbol = name+'Mark'; + if (!(markSymbol in self)) { + return; + } + + if (!clear) { + callback(name, buffer, self[markSymbol], buffer.length); + self[markSymbol] = 0; + } else { + callback(name, buffer, self[markSymbol], i); + delete self[markSymbol]; + } + }; + + for (i = 0; i < len; i++) { + c = buffer[i]; + switch (state) { + case S.PARSER_UNINITIALIZED: + return i; + case S.START: + index = 0; + state = S.START_BOUNDARY; + case S.START_BOUNDARY: + if (index == boundary.length - 2) { + if (c == HYPHEN) { + flags |= F.LAST_BOUNDARY; + } else if (c != CR) { + return i; + } + index++; + break; + } else if (index - 1 == boundary.length - 2) { + if (flags & F.LAST_BOUNDARY && c == HYPHEN){ + callback('end'); + state = S.END; + flags = 0; + } else if (!(flags & F.LAST_BOUNDARY) && c == LF) { + index = 0; + callback('partBegin'); + state = S.HEADER_FIELD_START; + } else { + return i; + } + break; + } + + if (c != boundary[index+2]) { + index = -2; + } + if (c == boundary[index+2]) { + index++; + } + break; + case S.HEADER_FIELD_START: + state = S.HEADER_FIELD; + mark('headerField'); + index = 0; + case S.HEADER_FIELD: + if (c == CR) { + clear('headerField'); + state = S.HEADERS_ALMOST_DONE; + break; + } + + index++; + if (c == HYPHEN) { + break; + } + + if (c == COLON) { + if (index == 1) { + // empty header field + return i; + } + dataCallback('headerField', true); + state = S.HEADER_VALUE_START; + break; + } + + cl = lower(c); + if (cl < A || cl > Z) { + return i; + } + break; + case S.HEADER_VALUE_START: + if (c == SPACE) { + break; + } + + mark('headerValue'); + state = S.HEADER_VALUE; + case S.HEADER_VALUE: + if (c == CR) { + dataCallback('headerValue', true); + callback('headerEnd'); + state = S.HEADER_VALUE_ALMOST_DONE; + } + break; + case S.HEADER_VALUE_ALMOST_DONE: + if (c != LF) { + return i; + } + state = S.HEADER_FIELD_START; + break; + case S.HEADERS_ALMOST_DONE: + if (c != LF) { + return i; + } + + callback('headersEnd'); + state = S.PART_DATA_START; + break; + case S.PART_DATA_START: + state = S.PART_DATA; + mark('partData'); + case S.PART_DATA: + prevIndex = index; + + if (index === 0) { + // boyer-moore derrived algorithm to safely skip non-boundary data + i += boundaryEnd; + while (i < bufferLength && !(buffer[i] in boundaryChars)) { + i += boundaryLength; + } + i -= boundaryEnd; + c = buffer[i]; + } + + if (index < boundary.length) { + if (boundary[index] == c) { + if (index === 0) { + dataCallback('partData', true); + } + index++; + } else { + index = 0; + } + } else if (index == boundary.length) { + index++; + if (c == CR) { + // CR = part boundary + flags |= F.PART_BOUNDARY; + } else if (c == HYPHEN) { + // HYPHEN = end boundary + flags |= F.LAST_BOUNDARY; + } else { + index = 0; + } + } else if (index - 1 == boundary.length) { + if (flags & F.PART_BOUNDARY) { + index = 0; + if (c == LF) { + // unset the PART_BOUNDARY flag + flags &= ~F.PART_BOUNDARY; + callback('partEnd'); + callback('partBegin'); + state = S.HEADER_FIELD_START; + break; + } + } else if (flags & F.LAST_BOUNDARY) { + if (c == HYPHEN) { + callback('partEnd'); + callback('end'); + state = S.END; + flags = 0; + } else { + index = 0; + } + } else { + index = 0; + } + } + + if (index > 0) { + // when matching a possible boundary, keep a lookbehind reference + // in case it turns out to be a false lead + lookbehind[index-1] = c; + } else if (prevIndex > 0) { + // if our boundary turned out to be rubbish, the captured lookbehind + // belongs to partData + callback('partData', lookbehind, 0, prevIndex); + prevIndex = 0; + mark('partData'); + + // reconsider the current character even so it interrupted the sequence + // it could be the beginning of a new sequence + i--; + } + + break; + case S.END: + break; + default: + return i; + } + } + + dataCallback('headerField'); + dataCallback('headerValue'); + dataCallback('partData'); + + this.index = index; + this.state = state; + this.flags = flags; + + return len; +}; + +MultipartParser.prototype.end = function() { + var callback = function(self, name) { + var callbackSymbol = 'on'+name.substr(0, 1).toUpperCase()+name.substr(1); + if (callbackSymbol in self) { + self[callbackSymbol](); + } + }; + if ((this.state == S.HEADER_FIELD_START && this.index === 0) || + (this.state == S.PART_DATA && this.index == this.boundary.length)) { + callback(this, 'partEnd'); + callback(this, 'end'); + } else if (this.state != S.END) { + return new Error('MultipartParser.end(): stream ended unexpectedly: ' + this.explain()); + } +}; + +MultipartParser.prototype.explain = function() { + return 'state = ' + MultipartParser.stateToString(this.state); +}; diff --git a/node_modules/formidable/lib/octet_parser.js b/node_modules/formidable/lib/octet_parser.js new file mode 100644 index 000000000..6e8b55155 --- /dev/null +++ b/node_modules/formidable/lib/octet_parser.js @@ -0,0 +1,20 @@ +var EventEmitter = require('events').EventEmitter + , util = require('util'); + +function OctetParser(options){ + if(!(this instanceof OctetParser)) return new OctetParser(options); + EventEmitter.call(this); +} + +util.inherits(OctetParser, EventEmitter); + +exports.OctetParser = OctetParser; + +OctetParser.prototype.write = function(buffer) { + this.emit('data', buffer); + return buffer.length; +}; + +OctetParser.prototype.end = function() { + this.emit('end'); +}; diff --git a/node_modules/formidable/lib/querystring_parser.js b/node_modules/formidable/lib/querystring_parser.js new file mode 100644 index 000000000..fcaffe0ad --- /dev/null +++ b/node_modules/formidable/lib/querystring_parser.js @@ -0,0 +1,27 @@ +if (global.GENTLY) require = GENTLY.hijack(require); + +// This is a buffering parser, not quite as nice as the multipart one. +// If I find time I'll rewrite this to be fully streaming as well +var querystring = require('querystring'); + +function QuerystringParser(maxKeys) { + this.maxKeys = maxKeys; + this.buffer = ''; +} +exports.QuerystringParser = QuerystringParser; + +QuerystringParser.prototype.write = function(buffer) { + this.buffer += buffer.toString('ascii'); + return buffer.length; +}; + +QuerystringParser.prototype.end = function() { + var fields = querystring.parse(this.buffer, '&', '=', { maxKeys: this.maxKeys }); + for (var field in fields) { + this.onField(field, fields[field]); + } + this.buffer = ''; + + this.onEnd(); +}; + diff --git a/node_modules/formidable/package.json b/node_modules/formidable/package.json new file mode 100644 index 000000000..7d746d35a --- /dev/null +++ b/node_modules/formidable/package.json @@ -0,0 +1,29 @@ +{ + "name": "formidable", + "version": "1.2.6", + "license": "MIT", + "description": "(DEPRECATED! Install formidable@v2) A node.js module for parsing form data, especially file uploads.", + "homepage": "https://github.com/node-formidable/formidable", + "funding": "https://ko-fi.com/tunnckoCore/commissions", + "repository": "node-formidable/formidable", + "main": "./lib/index.js", + "files": [ + "lib" + ], + "publishConfig": { + "access": "public", + "tag": "v1" + }, + "devDependencies": { + "gently": "^0.8.0", + "findit": "^0.1.2", + "hashish": "^0.0.4", + "urun": "^0.0.6", + "utest": "^0.0.8", + "request": "^2.11.4" + }, + "scripts": { + "test": "node test/run.js", + "clean": "rm test/tmp/*" + } +} diff --git a/node_modules/fs-readdir-recursive/LICENSE b/node_modules/fs-readdir-recursive/LICENSE new file mode 100644 index 000000000..a7ae8ee9b --- /dev/null +++ b/node_modules/fs-readdir-recursive/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/fs-readdir-recursive/README.md b/node_modules/fs-readdir-recursive/README.md new file mode 100644 index 000000000..4c4f8d5de --- /dev/null +++ b/node_modules/fs-readdir-recursive/README.md @@ -0,0 +1,61 @@ +# fs.readdirSyncRecursive + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![Dependency Status][david-image]][david-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Read a directory recursively. + +## Install + +```bash +npm install fs-readdir-recursive +``` + +## Example + +```js +var read = require('fs-readdir-recursive') +read(__dirname) === [ + 'test/test.js', + 'index.js', + 'LICENSE', + 'package.json', + 'README.md' +] +``` + +## API + +### read(root [, filter]) + +`root` is the directory you wish to scan. `filter` is an optional filter for the files with three params(name, index, dir). By default, filter is: + +```js +function (name) { + return name[0] !== '.' +} +``` + +Which basically just ignores `.` files. + +[npm-image]: https://img.shields.io/npm/v/fs-readdir-recursive.svg?style=flat-square +[npm-url]: https://npmjs.org/package/fs-readdir-recursive +[github-tag]: http://img.shields.io/github/tag/fs-utils/fs-readdir-recursive.svg?style=flat-square +[github-url]: https://github.com/fs-utils/fs-readdir-recursive/tags +[travis-image]: https://img.shields.io/travis/fs-utils/fs-readdir-recursive.svg?style=flat-square +[travis-url]: https://travis-ci.org/fs-utils/fs-readdir-recursive +[coveralls-image]: https://img.shields.io/coveralls/fs-utils/fs-readdir-recursive.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/fs-utils/fs-readdir-recursive +[david-image]: http://img.shields.io/david/fs-utils/fs-readdir-recursive.svg?style=flat-square +[david-url]: https://david-dm.org/fs-utils/fs-readdir-recursive +[license-image]: http://img.shields.io/npm/l/fs-readdir-recursive.svg?style=flat-square +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/fs-readdir-recursive.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/fs-readdir-recursive +[gittip-image]: https://img.shields.io/gratipay/jonathanong.svg?style=flat-square +[gittip-url]: https://gratipay.com/jonathanong/ diff --git a/node_modules/fs-readdir-recursive/index.js b/node_modules/fs-readdir-recursive/index.js new file mode 100644 index 000000000..59d0af258 --- /dev/null +++ b/node_modules/fs-readdir-recursive/index.js @@ -0,0 +1,29 @@ +var fs = require('fs') +var path = require('path') + +module.exports = read + +function read(root, filter, files, prefix) { + prefix = prefix || '' + files = files || [] + filter = filter || noDotFiles + + var dir = path.join(root, prefix) + if (!fs.existsSync(dir)) return files + if (fs.statSync(dir).isDirectory()) + fs.readdirSync(dir) + .filter(function (name, index) { + return filter(name, index, dir) + }) + .forEach(function (name) { + read(root, filter, files, path.join(prefix, name)) + }) + else + files.push(prefix) + + return files +} + +function noDotFiles(x) { + return x[0] !== '.' +} diff --git a/node_modules/fs-readdir-recursive/package.json b/node_modules/fs-readdir-recursive/package.json new file mode 100644 index 000000000..5fc1947ef --- /dev/null +++ b/node_modules/fs-readdir-recursive/package.json @@ -0,0 +1,26 @@ +{ + "name": "fs-readdir-recursive", + "description": "Recursively read a directory", + "version": "1.1.0", + "scripts": { + "test": "mocha --reporter spec", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot" + }, + "devDependencies": { + "istanbul": "0", + "mocha": "3", + "should": "*" + }, + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com", + "twitter": "https://twitter.com/jongleberry" + }, + "repository": "fs-utils/fs-readdir-recursive", + "files": [ + "index.js" + ], + "license": "MIT" +} diff --git a/node_modules/function-bind/.eslintrc b/node_modules/function-bind/.eslintrc index 9b33d8edf..71a054fd3 100644 --- a/node_modules/function-bind/.eslintrc +++ b/node_modules/function-bind/.eslintrc @@ -6,10 +6,16 @@ "rules": { "func-name-matching": 0, "indent": [2, 4], - "max-nested-callbacks": [2, 3], - "max-params": [2, 3], - "max-statements": [2, 20], "no-new-func": [1], - "strict": [0] - } + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "max-lines-per-function": 0, + "strict": [0] + }, + }, + ], } diff --git a/node_modules/function-bind/.github/FUNDING.yml b/node_modules/function-bind/.github/FUNDING.yml new file mode 100644 index 000000000..744821959 --- /dev/null +++ b/node_modules/function-bind/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/function-bind +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/function-bind/.github/SECURITY.md b/node_modules/function-bind/.github/SECURITY.md new file mode 100644 index 000000000..82e4285ad --- /dev/null +++ b/node_modules/function-bind/.github/SECURITY.md @@ -0,0 +1,3 @@ +# Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. diff --git a/node_modules/function-bind/.jscs.json b/node_modules/function-bind/.jscs.json deleted file mode 100644 index 8c4479480..000000000 --- a/node_modules/function-bind/.jscs.json +++ /dev/null @@ -1,176 +0,0 @@ -{ - "es3": true, - - "additionalRules": [], - - "requireSemicolons": true, - - "disallowMultipleSpaces": true, - - "disallowIdentifierNames": [], - - "requireCurlyBraces": { - "allExcept": [], - "keywords": ["if", "else", "for", "while", "do", "try", "catch"] - }, - - "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], - - "disallowSpaceAfterKeywords": [], - - "disallowSpaceBeforeComma": true, - "disallowSpaceAfterComma": false, - "disallowSpaceBeforeSemicolon": true, - - "disallowNodeTypes": [ - "DebuggerStatement", - "ForInStatement", - "LabeledStatement", - "SwitchCase", - "SwitchStatement", - "WithStatement" - ], - - "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, - - "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, - "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, - "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - - "requireSpaceBetweenArguments": true, - - "disallowSpacesInsideParentheses": true, - - "disallowSpacesInsideArrayBrackets": true, - - "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, - - "disallowSpaceAfterObjectKeys": true, - - "requireCommaBeforeLineBreak": true, - - "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], - "requireSpaceAfterPrefixUnaryOperators": [], - - "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], - "requireSpaceBeforePostfixUnaryOperators": [], - - "disallowSpaceBeforeBinaryOperators": [], - "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - - "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - "disallowSpaceAfterBinaryOperators": [], - - "disallowImplicitTypeConversion": ["binary", "string"], - - "disallowKeywords": ["with", "eval"], - - "requireKeywordsOnNewLine": [], - "disallowKeywordsOnNewLine": ["else"], - - "requireLineFeedAtFileEnd": true, - - "disallowTrailingWhitespace": true, - - "disallowTrailingComma": true, - - "excludeFiles": ["node_modules/**", "vendor/**"], - - "disallowMultipleLineStrings": true, - - "requireDotNotation": { "allExcept": ["keywords"] }, - - "requireParenthesesAroundIIFE": true, - - "validateLineBreaks": "LF", - - "validateQuoteMarks": { - "escape": true, - "mark": "'" - }, - - "disallowOperatorBeforeLineBreak": [], - - "requireSpaceBeforeKeywords": [ - "do", - "for", - "if", - "else", - "switch", - "case", - "try", - "catch", - "finally", - "while", - "with", - "return" - ], - - "validateAlignedFunctionParameters": { - "lineBreakAfterOpeningBraces": true, - "lineBreakBeforeClosingBraces": true - }, - - "requirePaddingNewLinesBeforeExport": true, - - "validateNewlineAfterArrayElements": { - "maximum": 8 - }, - - "requirePaddingNewLinesAfterUseStrict": true, - - "disallowArrowFunctions": true, - - "disallowMultiLineTernary": true, - - "validateOrderInObjectKeys": "asc-insensitive", - - "disallowIdenticalDestructuringNames": true, - - "disallowNestedTernaries": { "maxLevel": 1 }, - - "requireSpaceAfterComma": { "allExcept": ["trailing"] }, - "requireAlignedMultilineParams": false, - - "requireSpacesInGenerator": { - "afterStar": true - }, - - "disallowSpacesInGenerator": { - "beforeStar": true - }, - - "disallowVar": false, - - "requireArrayDestructuring": false, - - "requireEnhancedObjectLiterals": false, - - "requireObjectDestructuring": false, - - "requireEarlyReturn": false, - - "requireCapitalizedConstructorsNew": { - "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] - }, - - "requireImportAlphabetized": false, - - "requireSpaceBeforeObjectValues": true, - "requireSpaceBeforeDestructuredValues": true, - - "disallowSpacesInsideTemplateStringPlaceholders": true, - - "disallowArrayDestructuringReturn": false, - - "requireNewlineBeforeSingleStatementsInIf": false, - - "disallowUnusedVariables": true, - - "requireSpacesInsideImportedObjectBraces": true, - - "requireUseStrict": true -} - diff --git a/node_modules/function-bind/.npmignore b/node_modules/function-bind/.npmignore deleted file mode 100644 index dbb555fd1..000000000 --- a/node_modules/function-bind/.npmignore +++ /dev/null @@ -1,22 +0,0 @@ -# gitignore -.DS_Store -.monitor -.*.swp -.nodemonignore -releases -*.log -*.err -fleet.json -public/browserify -bin/*.json -.bin -build -compile -.lock-wscript -coverage -node_modules - -# Only apps should have lockfiles -npm-shrinkwrap.json -package-lock.json -yarn.lock diff --git a/node_modules/function-bind/.nycrc b/node_modules/function-bind/.nycrc new file mode 100644 index 000000000..1826526e0 --- /dev/null +++ b/node_modules/function-bind/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/function-bind/.travis.yml b/node_modules/function-bind/.travis.yml deleted file mode 100644 index 85f70d246..000000000 --- a/node_modules/function-bind/.travis.yml +++ /dev/null @@ -1,168 +0,0 @@ -language: node_js -os: - - linux -node_js: - - "8.4" - - "7.10" - - "6.11" - - "5.12" - - "4.8" - - "iojs-v3.3" - - "iojs-v2.5" - - "iojs-v1.8" - - "0.12" - - "0.10" - - "0.8" -before_install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ]; then npm install -g npm@1.3 ; elif [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then case "$(npm --version)" in 1.*) npm install -g npm@1.4.28 ;; 2.*) npm install -g npm@2 ;; esac ; fi' - - 'if [ "${TRAVIS_NODE_VERSION}" != "0.6" ] && [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then if [ "${TRAVIS_NODE_VERSION%${TRAVIS_NODE_VERSION#[0-9]}}" = "0" ] || [ "${TRAVIS_NODE_VERSION:0:4}" = "iojs" ]; then npm install -g npm@4.5 ; else npm install -g npm; fi; fi' -install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ]; then nvm install 0.8 && npm install -g npm@1.3 && npm install -g npm@1.4.28 && npm install -g npm@2 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' -script: - - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' - - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' - - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' -sudo: false -env: - - TEST=true -matrix: - fast_finish: true - include: - - node_js: "node" - env: PRETEST=true - - node_js: "4" - env: COVERAGE=true - - node_js: "8.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.4" - env: TEST=true ALLOW_FAILURE=true - allow_failures: - - os: osx - - env: TEST=true ALLOW_FAILURE=true diff --git a/node_modules/function-bind/CHANGELOG.md b/node_modules/function-bind/CHANGELOG.md new file mode 100644 index 000000000..f9e6cc078 --- /dev/null +++ b/node_modules/function-bind/CHANGELOG.md @@ -0,0 +1,136 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.2](https://github.com/ljharb/function-bind/compare/v1.1.1...v1.1.2) - 2023-10-12 + +### Merged + +- Point to the correct file [`#16`](https://github.com/ljharb/function-bind/pull/16) + +### Commits + +- [Tests] migrate tests to Github Actions [`4f8b57c`](https://github.com/ljharb/function-bind/commit/4f8b57c02f2011fe9ae353d5e74e8745f0988af8) +- [Tests] remove `jscs` [`90eb2ed`](https://github.com/ljharb/function-bind/commit/90eb2edbeefd5b76cd6c3a482ea3454db169b31f) +- [meta] update `.gitignore` [`53fcdc3`](https://github.com/ljharb/function-bind/commit/53fcdc371cd66634d6e9b71c836a50f437e89fed) +- [Tests] up to `node` `v11.10`, `v10.15`, `v9.11`, `v8.15`, `v6.16`, `v4.9`; use `nvm install-latest-npm`; run audit script in tests [`1fe8f6e`](https://github.com/ljharb/function-bind/commit/1fe8f6e9aed0dfa8d8b3cdbd00c7f5ea0cd2b36e) +- [meta] add `auto-changelog` [`1921fcb`](https://github.com/ljharb/function-bind/commit/1921fcb5b416b63ffc4acad051b6aad5722f777d) +- [Robustness] remove runtime dependency on all builtins except `.apply` [`f743e61`](https://github.com/ljharb/function-bind/commit/f743e61aa6bb2360358c04d4884c9db853d118b7) +- Docs: enable badges; update wording [`503cb12`](https://github.com/ljharb/function-bind/commit/503cb12d998b5f91822776c73332c7adcd6355dd) +- [readme] update badges [`290c5db`](https://github.com/ljharb/function-bind/commit/290c5dbbbda7264efaeb886552a374b869a4bb48) +- [Tests] switch to nyc for coverage [`ea360ba`](https://github.com/ljharb/function-bind/commit/ea360ba907fc2601ed18d01a3827fa2d3533cdf8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`cae5e9e`](https://github.com/ljharb/function-bind/commit/cae5e9e07a5578dc6df26c03ee22851ce05b943c) +- [meta] add `funding` field; create FUNDING.yml [`c9f4274`](https://github.com/ljharb/function-bind/commit/c9f4274aa80ea3aae9657a3938fdba41a3b04ca6) +- [Tests] fix eslint errors from #15 [`f69aaa2`](https://github.com/ljharb/function-bind/commit/f69aaa2beb2fdab4415bfb885760a699d0b9c964) +- [actions] fix permissions [`99a0cd9`](https://github.com/ljharb/function-bind/commit/99a0cd9f3b5bac223a0d572f081834cd73314be7) +- [meta] use `npmignore` to autogenerate an npmignore file [`f03b524`](https://github.com/ljharb/function-bind/commit/f03b524ca91f75a109a5d062f029122c86ecd1ae) +- [Dev Deps] update `@ljharb/eslint‑config`, `eslint`, `tape` [`7af9300`](https://github.com/ljharb/function-bind/commit/7af930023ae2ce7645489532821e4fbbcd7a2280) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape` [`64a9127`](https://github.com/ljharb/function-bind/commit/64a9127ab0bd331b93d6572eaf6e9971967fc08c) +- [Tests] use `aud` instead of `npm audit` [`e75069c`](https://github.com/ljharb/function-bind/commit/e75069c50010a8fcce2a9ce2324934c35fdb4386) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`d03555c`](https://github.com/ljharb/function-bind/commit/d03555ca59dea3b71ce710045e4303b9e2619e28) +- [meta] add `safe-publish-latest` [`9c8f809`](https://github.com/ljharb/function-bind/commit/9c8f8092aed027d7e80c94f517aa892385b64f09) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`baf6893`](https://github.com/ljharb/function-bind/commit/baf6893e27f5b59abe88bc1995e6f6ed1e527397) +- [meta] create SECURITY.md [`4db1779`](https://github.com/ljharb/function-bind/commit/4db17799f1f28ae294cb95e0081ca2b591c3911b) +- [Tests] add `npm run audit` [`c8b38ec`](https://github.com/ljharb/function-bind/commit/c8b38ec40ed3f85dabdee40ed4148f1748375bc2) +- Revert "Point to the correct file" [`05cdf0f`](https://github.com/ljharb/function-bind/commit/05cdf0fa205c6a3c5ba40bbedd1dfa9874f915c9) + +## [v1.1.1](https://github.com/ljharb/function-bind/compare/v1.1.0...v1.1.1) - 2017-08-28 + +### Commits + +- [Tests] up to `node` `v8`; newer npm breaks on older node; fix scripts [`817f7d2`](https://github.com/ljharb/function-bind/commit/817f7d28470fdbff8ef608d4d565dd4d1430bc5e) +- [Dev Deps] update `eslint`, `jscs`, `tape`, `@ljharb/eslint-config` [`854288b`](https://github.com/ljharb/function-bind/commit/854288b1b6f5c555f89aceb9eff1152510262084) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`83e639f`](https://github.com/ljharb/function-bind/commit/83e639ff74e6cd6921285bccec22c1bcf72311bd) +- Only apps should have lockfiles [`5ed97f5`](https://github.com/ljharb/function-bind/commit/5ed97f51235c17774e0832e122abda0f3229c908) +- Use a SPDX-compliant “license” field. [`5feefea`](https://github.com/ljharb/function-bind/commit/5feefea0dc0193993e83e5df01ded424403a5381) + +## [v1.1.0](https://github.com/ljharb/function-bind/compare/v1.0.2...v1.1.0) - 2016-02-14 + +### Commits + +- Update `eslint`, `tape`; use my personal shared `eslint` config [`9c9062a`](https://github.com/ljharb/function-bind/commit/9c9062abbe9dd70b59ea2c3a3c3a81f29b457097) +- Add `npm run eslint` [`dd96c56`](https://github.com/ljharb/function-bind/commit/dd96c56720034a3c1ffee10b8a59a6f7c53e24ad) +- [New] return the native `bind` when available. [`82186e0`](https://github.com/ljharb/function-bind/commit/82186e03d73e580f95ff167e03f3582bed90ed72) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`a3dd767`](https://github.com/ljharb/function-bind/commit/a3dd76720c795cb7f4586b0544efabf8aa107b8b) +- Update `eslint` [`3dae2f7`](https://github.com/ljharb/function-bind/commit/3dae2f7423de30a2d20313ddb1edc19660142fe9) +- Update `tape`, `covert`, `jscs` [`a181eee`](https://github.com/ljharb/function-bind/commit/a181eee0cfa24eb229c6e843a971f36e060a2f6a) +- [Tests] up to `node` `v5.6`, `v4.3` [`964929a`](https://github.com/ljharb/function-bind/commit/964929a6a4ddb36fb128de2bcc20af5e4f22e1ed) +- Test up to `io.js` `v2.1` [`2be7310`](https://github.com/ljharb/function-bind/commit/2be7310f2f74886a7124ca925be411117d41d5ea) +- Update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`45f3d68`](https://github.com/ljharb/function-bind/commit/45f3d6865c6ca93726abcef54febe009087af101) +- [Dev Deps] update `tape`, `jscs` [`6e1340d`](https://github.com/ljharb/function-bind/commit/6e1340d94642deaecad3e717825db641af4f8b1f) +- [Tests] up to `io.js` `v3.3`, `node` `v4.1` [`d9bad2b`](https://github.com/ljharb/function-bind/commit/d9bad2b778b1b3a6dd2876087b88b3acf319f8cc) +- Update `eslint` [`935590c`](https://github.com/ljharb/function-bind/commit/935590caa024ab356102e4858e8fc315b2ccc446) +- [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` [`8c9a1ef`](https://github.com/ljharb/function-bind/commit/8c9a1efd848e5167887aa8501857a0940a480c57) +- Test on `io.js` `v2.2` [`9a3a38c`](https://github.com/ljharb/function-bind/commit/9a3a38c92013aed6e108666e7bd40969b84ac86e) +- Run `travis-ci` tests on `iojs` and `node` v0.12; speed up builds; allow 0.8 failures. [`69afc26`](https://github.com/ljharb/function-bind/commit/69afc2617405b147dd2a8d8ae73ca9e9283f18b4) +- [Dev Deps] Update `tape`, `eslint` [`36c1be0`](https://github.com/ljharb/function-bind/commit/36c1be0ab12b45fe5df6b0fdb01a5d5137fd0115) +- Update `tape`, `jscs` [`98d8303`](https://github.com/ljharb/function-bind/commit/98d8303cd5ca1c6b8f985469f86b0d44d7d45f6e) +- Update `jscs` [`9633a4e`](https://github.com/ljharb/function-bind/commit/9633a4e9fbf82051c240855166e468ba8ba0846f) +- Update `tape`, `jscs` [`c80ef0f`](https://github.com/ljharb/function-bind/commit/c80ef0f46efc9791e76fa50de4414092ac147831) +- Test up to `io.js` `v3.0` [`7e2c853`](https://github.com/ljharb/function-bind/commit/7e2c8537d52ab9cf5a655755561d8917684c0df4) +- Test on `io.js` `v2.4` [`5a199a2`](https://github.com/ljharb/function-bind/commit/5a199a27ba46795ba5eaf0845d07d4b8232895c9) +- Test on `io.js` `v2.3` [`a511b88`](https://github.com/ljharb/function-bind/commit/a511b8896de0bddf3b56862daa416c701f4d0453) +- Fixing a typo from 822b4e1938db02dc9584aa434fd3a45cb20caf43 [`732d6b6`](https://github.com/ljharb/function-bind/commit/732d6b63a9b33b45230e630dbcac7a10855d3266) +- Update `jscs` [`da52a48`](https://github.com/ljharb/function-bind/commit/da52a4886c06d6490f46ae30b15e4163ba08905d) +- Lock covert to v1.0.0. [`d6150fd`](https://github.com/ljharb/function-bind/commit/d6150fda1e6f486718ebdeff823333d9e48e7430) + +## [v1.0.2](https://github.com/ljharb/function-bind/compare/v1.0.1...v1.0.2) - 2014-10-04 + +## [v1.0.1](https://github.com/ljharb/function-bind/compare/v1.0.0...v1.0.1) - 2014-10-03 + +### Merged + +- make CI build faster [`#3`](https://github.com/ljharb/function-bind/pull/3) + +### Commits + +- Using my standard jscs.json [`d8ee94c`](https://github.com/ljharb/function-bind/commit/d8ee94c993eff0a84cf5744fe6a29627f5cffa1a) +- Adding `npm run lint` [`7571ab7`](https://github.com/ljharb/function-bind/commit/7571ab7dfdbd99b25a1dbb2d232622bd6f4f9c10) +- Using consistent indentation [`e91a1b1`](https://github.com/ljharb/function-bind/commit/e91a1b13a61e99ec1e530e299b55508f74218a95) +- Updating jscs [`7e17892`](https://github.com/ljharb/function-bind/commit/7e1789284bc629bc9c1547a61c9b227bbd8c7a65) +- Using consistent quotes [`c50b57f`](https://github.com/ljharb/function-bind/commit/c50b57fcd1c5ec38320979c837006069ebe02b77) +- Adding keywords [`cb94631`](https://github.com/ljharb/function-bind/commit/cb946314eed35f21186a25fb42fc118772f9ee00) +- Directly export a function expression instead of using a declaration, and relying on hoisting. [`5a33c5f`](https://github.com/ljharb/function-bind/commit/5a33c5f45642de180e0d207110bf7d1843ceb87c) +- Naming npm URL and badge in README; use SVG [`2aef8fc`](https://github.com/ljharb/function-bind/commit/2aef8fcb79d54e63a58ae557c4e60949e05d5e16) +- Naming deps URLs in README [`04228d7`](https://github.com/ljharb/function-bind/commit/04228d766670ee45ca24e98345c1f6a7621065b5) +- Naming travis-ci URLs in README; using SVG [`62c810c`](https://github.com/ljharb/function-bind/commit/62c810c2f54ced956cd4d4ab7b793055addfe36e) +- Make sure functions are invoked correctly (also passing coverage tests) [`2b289b4`](https://github.com/ljharb/function-bind/commit/2b289b4dfbf037ffcfa4dc95eb540f6165e9e43a) +- Removing the strict mode pragmas; they make tests fail. [`1aa701d`](https://github.com/ljharb/function-bind/commit/1aa701d199ddc3782476e8f7eef82679be97b845) +- Adding myself as a contributor [`85fd57b`](https://github.com/ljharb/function-bind/commit/85fd57b0860e5a7af42de9a287f3f265fc6d72fc) +- Adding strict mode pragmas [`915b08e`](https://github.com/ljharb/function-bind/commit/915b08e084c86a722eafe7245e21db74aa21ca4c) +- Adding devDeps URLs to README [`4ccc731`](https://github.com/ljharb/function-bind/commit/4ccc73112c1769859e4ca3076caf4086b3cba2cd) +- Fixing the description. [`a7a472c`](https://github.com/ljharb/function-bind/commit/a7a472cf649af515c635cf560fc478fbe48999c8) +- Using a function expression instead of a function declaration. [`b5d3e4e`](https://github.com/ljharb/function-bind/commit/b5d3e4ea6aaffc63888953eeb1fbc7ff45f1fa14) +- Updating tape [`f086be6`](https://github.com/ljharb/function-bind/commit/f086be6029fb56dde61a258c1340600fa174d1e0) +- Updating jscs [`5f9bdb3`](https://github.com/ljharb/function-bind/commit/5f9bdb375ab13ba48f30852aab94029520c54d71) +- Updating jscs [`9b409ba`](https://github.com/ljharb/function-bind/commit/9b409ba6118e23395a4e5d83ef39152aab9d3bfc) +- Run coverage as part of tests. [`8e1b6d4`](https://github.com/ljharb/function-bind/commit/8e1b6d459f047d1bd4fee814e01247c984c80bd0) +- Run linter as part of tests [`c1ca83f`](https://github.com/ljharb/function-bind/commit/c1ca83f832df94587d09e621beba682fabfaa987) +- Updating covert [`701e837`](https://github.com/ljharb/function-bind/commit/701e83774b57b4d3ef631e1948143f43a72f4bb9) + +## [v1.0.0](https://github.com/ljharb/function-bind/compare/v0.2.0...v1.0.0) - 2014-08-09 + +### Commits + +- Make sure old and unstable nodes don't fail Travis [`27adca3`](https://github.com/ljharb/function-bind/commit/27adca34a4ab6ad67b6dfde43942a1b103ce4d75) +- Fixing an issue when the bound function is called as a constructor in ES3. [`e20122d`](https://github.com/ljharb/function-bind/commit/e20122d267d92ce553859b280cbbea5d27c07731) +- Adding `npm run coverage` [`a2e29c4`](https://github.com/ljharb/function-bind/commit/a2e29c4ecaef9e2f6cd1603e868c139073375502) +- Updating tape [`b741168`](https://github.com/ljharb/function-bind/commit/b741168b12b235b1717ff696087645526b69213c) +- Upgrading tape [`63631a0`](https://github.com/ljharb/function-bind/commit/63631a04c7fbe97cc2fa61829cc27246d6986f74) +- Updating tape [`363cb46`](https://github.com/ljharb/function-bind/commit/363cb46dafb23cb3e347729a22f9448051d78464) + +## v0.2.0 - 2014-03-23 + +### Commits + +- Updating test coverage to match es5-shim. [`aa94d44`](https://github.com/ljharb/function-bind/commit/aa94d44b8f9d7f69f10e060db7709aa7a694e5d4) +- initial [`942ee07`](https://github.com/ljharb/function-bind/commit/942ee07e94e542d91798137bc4b80b926137e066) +- Setting the bound function's length properly. [`079f46a`](https://github.com/ljharb/function-bind/commit/079f46a2d3515b7c0b308c2c13fceb641f97ca25) +- Ensuring that some older browsers will throw when given a regex. [`36ac55b`](https://github.com/ljharb/function-bind/commit/36ac55b87f460d4330253c92870aa26fbfe8227f) +- Removing npm scripts that don't have dependencies [`9d2be60`](https://github.com/ljharb/function-bind/commit/9d2be600002cb8bc8606f8f3585ad3e05868c750) +- Updating tape [`297a4ac`](https://github.com/ljharb/function-bind/commit/297a4acc5464db381940aafb194d1c88f4e678f3) +- Skipping length tests for now. [`d9891ea`](https://github.com/ljharb/function-bind/commit/d9891ea4d2aaffa69f408339cdd61ff740f70565) +- don't take my tea [`dccd930`](https://github.com/ljharb/function-bind/commit/dccd930bfd60ea10cb178d28c97550c3bc8c1e07) diff --git a/node_modules/function-bind/README.md b/node_modules/function-bind/README.md index 81862a02c..814c20b5a 100644 --- a/node_modules/function-bind/README.md +++ b/node_modules/function-bind/README.md @@ -1,22 +1,19 @@ -# function-bind +# function-bind [![Version Badge][npm-version-svg]][package-url] - +[![github actions][actions-image]][actions-url] + +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] - +[![npm badge][npm-badge-png]][package-url] Implementation of function.prototype.bind -## Example +Old versions of phantomjs, Internet Explorer < 9, and node < 0.6 don't support `Function.prototype.bind`. -I mainly do this for unit tests I run on phantomjs. -PhantomJS does not have Function.prototype.bind :( +## Example ```js Function.prototype.bind = require("function-bind") @@ -32,17 +29,18 @@ Function.prototype.bind = require("function-bind") ## MIT Licenced - [travis-svg]: https://travis-ci.org/Raynos/function-bind.svg - [travis-url]: https://travis-ci.org/Raynos/function-bind - [npm-badge-svg]: https://badge.fury.io/js/function-bind.svg - [npm-url]: https://npmjs.org/package/function-bind - [5]: https://coveralls.io/repos/Raynos/function-bind/badge.png - [6]: https://coveralls.io/r/Raynos/function-bind - [7]: https://gemnasium.com/Raynos/function-bind.png - [8]: https://gemnasium.com/Raynos/function-bind - [deps-svg]: https://david-dm.org/Raynos/function-bind.svg - [deps-url]: https://david-dm.org/Raynos/function-bind - [dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg - [dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies - [11]: https://ci.testling.com/Raynos/function-bind.png - [12]: https://ci.testling.com/Raynos/function-bind +[package-url]: https://npmjs.org/package/function-bind +[npm-version-svg]: https://versionbadg.es/Raynos/function-bind.svg +[deps-svg]: https://david-dm.org/Raynos/function-bind.svg +[deps-url]: https://david-dm.org/Raynos/function-bind +[dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg +[dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/function-bind.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/function-bind.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/function-bind.svg +[downloads-url]: https://npm-stat.com/charts.html?package=function-bind +[codecov-image]: https://codecov.io/gh/Raynos/function-bind/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/Raynos/function-bind/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/Raynos/function-bind +[actions-url]: https://github.com/Raynos/function-bind/actions diff --git a/node_modules/function-bind/implementation.js b/node_modules/function-bind/implementation.js index cc4daec1b..fd4384cc0 100644 --- a/node_modules/function-bind/implementation.js +++ b/node_modules/function-bind/implementation.js @@ -3,43 +3,75 @@ /* eslint no-invalid-this: 1 */ var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var slice = Array.prototype.slice; var toStr = Object.prototype.toString; +var max = Math.max; var funcType = '[object Function]'; +var concatty = function concatty(a, b) { + var arr = []; + + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + + return arr; +}; + +var slicy = function slicy(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; +}; + +var joiny = function (arr, joiner) { + var str = ''; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; +}; + module.exports = function bind(that) { var target = this; - if (typeof target !== 'function' || toStr.call(target) !== funcType) { + if (typeof target !== 'function' || toStr.apply(target) !== funcType) { throw new TypeError(ERROR_MESSAGE + target); } - var args = slice.call(arguments, 1); + var args = slicy(arguments, 1); var bound; var binder = function () { if (this instanceof bound) { var result = target.apply( this, - args.concat(slice.call(arguments)) + concatty(args, arguments) ); if (Object(result) === result) { return result; } return this; - } else { - return target.apply( - that, - args.concat(slice.call(arguments)) - ); } + return target.apply( + that, + concatty(args, arguments) + ); + }; - var boundLength = Math.max(0, target.length - args.length); + var boundLength = max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) { - boundArgs.push('$' + i); + boundArgs[i] = '$' + i; } - bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); if (target.prototype) { var Empty = function Empty() {}; diff --git a/node_modules/function-bind/package.json b/node_modules/function-bind/package.json index 6d5603fd3..618596389 100644 --- a/node_modules/function-bind/package.json +++ b/node_modules/function-bind/package.json @@ -1,36 +1,23 @@ { - "_from": "function-bind@^1.1.1", - "_id": "function-bind@1.1.1", - "_inBundle": false, - "_integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", - "_location": "/function-bind", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "function-bind@^1.1.1", - "name": "function-bind", - "escapedName": "function-bind", - "rawSpec": "^1.1.1", - "saveSpec": null, - "fetchSpec": "^1.1.1" - }, - "_requiredBy": [ - "/has" + "name": "function-bind", + "version": "1.1.2", + "description": "Implementation of Function.prototype.bind", + "keywords": [ + "function", + "bind", + "shim", + "es5" ], - "_resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "_shasum": "a56899d3ea3c9bab874bb9773b7c5ede92f4895d", - "_spec": "function-bind@^1.1.1", - "_where": "/Users/christopher/Projects/github-actions-asana/node_modules/has", - "author": { - "name": "Raynos", - "email": "raynos2@gmail.com" + "author": "Raynos ", + "repository": { + "type": "git", + "url": "https://github.com/Raynos/function-bind.git" }, - "bugs": { - "url": "https://github.com/Raynos/function-bind/issues", - "email": "raynos2@gmail.com" + "funding": { + "url": "https://github.com/sponsors/ljharb" }, - "bundleDependencies": false, + "main": "index", + "homepage": "https://github.com/Raynos/function-bind", "contributors": [ { "name": "Raynos" @@ -40,39 +27,33 @@ "url": "https://github.com/ljharb" } ], - "dependencies": {}, - "deprecated": false, - "description": "Implementation of Function.prototype.bind", + "bugs": { + "url": "https://github.com/Raynos/function-bind/issues", + "email": "raynos2@gmail.com" + }, "devDependencies": { - "@ljharb/eslint-config": "^12.2.1", - "covert": "^1.1.0", - "eslint": "^4.5.0", - "jscs": "^3.0.7", - "tape": "^4.8.0" + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.3", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.1" }, - "homepage": "https://github.com/Raynos/function-bind", - "keywords": [ - "function", - "bind", - "shim", - "es5" - ], "license": "MIT", - "main": "index", - "name": "function-bind", - "repository": { - "type": "git", - "url": "git://github.com/Raynos/function-bind.git" - }, "scripts": { - "coverage": "covert test/*.js", - "eslint": "eslint *.js */*.js", - "jscs": "jscs *.js */*.js", - "lint": "npm run jscs && npm run eslint", - "posttest": "npm run coverage -- --quiet", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepack": "npmignore --auto --commentLines=autogenerated", "pretest": "npm run lint", "test": "npm run tests-only", - "tests-only": "node test" + "posttest": "aud --production", + "tests-only": "nyc tape 'test/**/*.js'", + "lint": "eslint --ext=js,mjs .", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" }, "testling": { "files": "test/index.js", @@ -90,5 +71,17 @@ "android-browser/4.2..latest" ] }, - "version": "1.1.1" + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } } diff --git a/node_modules/get-intrinsic/.eslintrc b/node_modules/get-intrinsic/.eslintrc new file mode 100644 index 000000000..837663623 --- /dev/null +++ b/node_modules/get-intrinsic/.eslintrc @@ -0,0 +1,38 @@ +{ + "root": true, + + "extends": "@ljharb", + + "env": { + "es6": true, + "es2017": true, + "es2020": true, + "es2021": true, + "es2022": true, + }, + + "rules": { + "array-bracket-newline": 0, + "complexity": 0, + "eqeqeq": [2, "allow-null"], + "func-name-matching": 0, + "id-length": 0, + "max-lines": 0, + "max-lines-per-function": [2, 90], + "max-params": [2, 4], + "max-statements": 0, + "max-statements-per-line": [2, { "max": 2 }], + "multiline-comment-style": 0, + "no-magic-numbers": 0, + "sort-keys": 0, + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "new-cap": 0, + }, + }, + ], +} diff --git a/node_modules/get-intrinsic/.github/FUNDING.yml b/node_modules/get-intrinsic/.github/FUNDING.yml new file mode 100644 index 000000000..8e8da0dda --- /dev/null +++ b/node_modules/get-intrinsic/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/get-intrinsic +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/get-intrinsic/.nycrc b/node_modules/get-intrinsic/.nycrc new file mode 100644 index 000000000..bdd626ce9 --- /dev/null +++ b/node_modules/get-intrinsic/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/get-intrinsic/CHANGELOG.md b/node_modules/get-intrinsic/CHANGELOG.md new file mode 100644 index 000000000..96d5397fc --- /dev/null +++ b/node_modules/get-intrinsic/CHANGELOG.md @@ -0,0 +1,143 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.2.4](https://github.com/ljharb/get-intrinsic/compare/v1.2.3...v1.2.4) - 2024-02-05 + +### Commits + +- [Refactor] use all 7 <+ ES6 Errors from `es-errors` [`bcac811`](https://github.com/ljharb/get-intrinsic/commit/bcac811abdc1c982e12abf848a410d6aae148d14) + +## [v1.2.3](https://github.com/ljharb/get-intrinsic/compare/v1.2.2...v1.2.3) - 2024-02-03 + +### Commits + +- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`f11db9c`](https://github.com/ljharb/get-intrinsic/commit/f11db9c4fb97d87bbd53d3c73ac6b3db3613ad3b) +- [Dev Deps] update `aud`, `es-abstract`, `mock-property`, `npmignore` [`b7ac7d1`](https://github.com/ljharb/get-intrinsic/commit/b7ac7d1616fefb03877b1aed0c8f8d61aad32b6c) +- [meta] simplify `exports` [`faa0cc6`](https://github.com/ljharb/get-intrinsic/commit/faa0cc618e2830ffb51a8202490b0c215d965cbc) +- [meta] add missing `engines.node` [`774dd0b`](https://github.com/ljharb/get-intrinsic/commit/774dd0b3e8f741c3f05a6322d124d6087f146af1) +- [Dev Deps] update `tape` [`5828e8e`](https://github.com/ljharb/get-intrinsic/commit/5828e8e4a04e69312e87a36c0ea39428a7a4c3d8) +- [Robustness] use null objects for lookups [`eb9a11f`](https://github.com/ljharb/get-intrinsic/commit/eb9a11fa9eb3e13b193fcc05a7fb814341b1a7b7) +- [meta] add `sideEffects` flag [`89bcc7a`](https://github.com/ljharb/get-intrinsic/commit/89bcc7a42e19bf07b7c21e3094d5ab177109e6d2) + +## [v1.2.2](https://github.com/ljharb/get-intrinsic/compare/v1.2.1...v1.2.2) - 2023-10-20 + +### Commits + +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `call-bind`, `es-abstract`, `mock-property`, `object-inspect`, `tape` [`f51bcf2`](https://github.com/ljharb/get-intrinsic/commit/f51bcf26412d58d17ce17c91c9afd0ad271f0762) +- [Refactor] use `hasown` instead of `has` [`18d14b7`](https://github.com/ljharb/get-intrinsic/commit/18d14b799bea6b5765e1cec91890830cbcdb0587) +- [Deps] update `function-bind` [`6e109c8`](https://github.com/ljharb/get-intrinsic/commit/6e109c81e03804cc5e7824fb64353cdc3d8ee2c7) + +## [v1.2.1](https://github.com/ljharb/get-intrinsic/compare/v1.2.0...v1.2.1) - 2023-05-13 + +### Commits + +- [Fix] avoid a crash in envs without `__proto__` [`7bad8d0`](https://github.com/ljharb/get-intrinsic/commit/7bad8d061bf8721733b58b73a2565af2b6756b64) +- [Dev Deps] update `es-abstract` [`c60e6b7`](https://github.com/ljharb/get-intrinsic/commit/c60e6b7b4cf9660c7f27ed970970fd55fac48dc5) + +## [v1.2.0](https://github.com/ljharb/get-intrinsic/compare/v1.1.3...v1.2.0) - 2023-01-19 + +### Commits + +- [actions] update checkout action [`ca6b12f`](https://github.com/ljharb/get-intrinsic/commit/ca6b12f31eaacea4ea3b055e744cd61623385ffb) +- [Dev Deps] update `@ljharb/eslint-config`, `es-abstract`, `object-inspect`, `tape` [`41a3727`](https://github.com/ljharb/get-intrinsic/commit/41a3727d0026fa04273ae216a5f8e12eefd72da8) +- [Fix] ensure `Error.prototype` is undeniable [`c511e97`](https://github.com/ljharb/get-intrinsic/commit/c511e97ae99c764c4524b540dee7a70757af8da3) +- [Dev Deps] update `aud`, `es-abstract`, `tape` [`1bef8a8`](https://github.com/ljharb/get-intrinsic/commit/1bef8a8fd439ebb80863199b6189199e0851ac67) +- [Dev Deps] update `aud`, `es-abstract` [`0d41f16`](https://github.com/ljharb/get-intrinsic/commit/0d41f16bcd500bc28b7bfc98043ebf61ea081c26) +- [New] add `BigInt64Array` and `BigUint64Array` [`a6cca25`](https://github.com/ljharb/get-intrinsic/commit/a6cca25f29635889b7e9bd669baf9e04be90e48c) +- [Tests] use `gopd` [`ecf7722`](https://github.com/ljharb/get-intrinsic/commit/ecf7722240d15cfd16edda06acf63359c10fb9bd) + +## [v1.1.3](https://github.com/ljharb/get-intrinsic/compare/v1.1.2...v1.1.3) - 2022-09-12 + +### Commits + +- [Dev Deps] update `es-abstract`, `es-value-fixtures`, `tape` [`07ff291`](https://github.com/ljharb/get-intrinsic/commit/07ff291816406ebe5a12d7f16965bde0942dd688) +- [Fix] properly check for % signs [`50ac176`](https://github.com/ljharb/get-intrinsic/commit/50ac1760fe99c227e64eabde76e9c0e44cd881b5) + +## [v1.1.2](https://github.com/ljharb/get-intrinsic/compare/v1.1.1...v1.1.2) - 2022-06-08 + +### Fixed + +- [Fix] properly validate against extra % signs [`#16`](https://github.com/ljharb/get-intrinsic/issues/16) + +### Commits + +- [actions] reuse common workflows [`0972547`](https://github.com/ljharb/get-intrinsic/commit/0972547efd0abc863fe4c445a6ca7eb4f8c6901d) +- [meta] use `npmignore` to autogenerate an npmignore file [`5ba0b51`](https://github.com/ljharb/get-intrinsic/commit/5ba0b51d8d8d4f1c31d426d74abc0770fd106bad) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`c364492`](https://github.com/ljharb/get-intrinsic/commit/c364492af4af51333e6f81c0bf21fd3d602c3661) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `es-abstract`, `object-inspect`, `tape` [`dc04dad`](https://github.com/ljharb/get-intrinsic/commit/dc04dad86f6e5608775a2640cb0db5927ae29ed9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `es-abstract`, `object-inspect`, `safe-publish-latest`, `tape` [`1c14059`](https://github.com/ljharb/get-intrinsic/commit/1c1405984e86dd2dc9366c15d8a0294a96a146a5) +- [Tests] use `mock-property` [`b396ef0`](https://github.com/ljharb/get-intrinsic/commit/b396ef05bb73b1d699811abd64b0d9b97997fdda) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `object-inspect`, `tape` [`c2c758d`](https://github.com/ljharb/get-intrinsic/commit/c2c758d3b90af4fef0a76910d8d3c292ec8d1d3e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `es-abstract`, `es-value-fixtures`, `object-inspect`, `tape` [`29e3c09`](https://github.com/ljharb/get-intrinsic/commit/29e3c091c2bf3e17099969847e8729d0e46896de) +- [actions] update codecov uploader [`8cbc141`](https://github.com/ljharb/get-intrinsic/commit/8cbc1418940d7a8941f3a7985cbc4ac095c5e13d) +- [Dev Deps] update `@ljharb/eslint-config`, `es-abstract`, `es-value-fixtures`, `object-inspect`, `tape` [`10b6f5c`](https://github.com/ljharb/get-intrinsic/commit/10b6f5c02593fb3680c581d696ac124e30652932) +- [readme] add github actions/codecov badges [`4e25400`](https://github.com/ljharb/get-intrinsic/commit/4e25400d9f51ae9eb059cbe22d9144e70ea214e8) +- [Tests] use `for-each` instead of `foreach` [`c05b957`](https://github.com/ljharb/get-intrinsic/commit/c05b957ad9a7bc7721af7cc9e9be1edbfe057496) +- [Dev Deps] update `es-abstract` [`29b05ae`](https://github.com/ljharb/get-intrinsic/commit/29b05aec3e7330e9ad0b8e0f685a9112c20cdd97) +- [meta] use `prepublishOnly` script for npm 7+ [`95c285d`](https://github.com/ljharb/get-intrinsic/commit/95c285da810516057d3bbfa871176031af38f05d) +- [Deps] update `has-symbols` [`593cb4f`](https://github.com/ljharb/get-intrinsic/commit/593cb4fb38e7922e40e42c183f45274b636424cd) +- [readme] fix repo URLs [`1c8305b`](https://github.com/ljharb/get-intrinsic/commit/1c8305b5365827c9b6fc785434aac0e1328ff2f5) +- [Deps] update `has-symbols` [`c7138b6`](https://github.com/ljharb/get-intrinsic/commit/c7138b6c6d73132d859471fb8c13304e1e7c8b20) +- [Dev Deps] remove unused `has-bigints` [`bd63aff`](https://github.com/ljharb/get-intrinsic/commit/bd63aff6ad8f3a986c557fcda2914187bdaab359) + +## [v1.1.1](https://github.com/ljharb/get-intrinsic/compare/v1.1.0...v1.1.1) - 2021-02-03 + +### Fixed + +- [meta] export `./package.json` [`#9`](https://github.com/ljharb/get-intrinsic/issues/9) + +### Commits + +- [readme] flesh out the readme; use `evalmd` [`d12f12c`](https://github.com/ljharb/get-intrinsic/commit/d12f12c15345a0a0772cc65a7c64369529abd614) +- [eslint] set up proper globals config [`5a8c098`](https://github.com/ljharb/get-intrinsic/commit/5a8c0984e3319d1ac0e64b102f8ec18b64e79f36) +- [Dev Deps] update `eslint` [`7b9a5c0`](https://github.com/ljharb/get-intrinsic/commit/7b9a5c0d31a90ca1a1234181c74988fb046701cd) + +## [v1.1.0](https://github.com/ljharb/get-intrinsic/compare/v1.0.2...v1.1.0) - 2021-01-25 + +### Fixed + +- [Refactor] delay `Function` eval until syntax-derived values are requested [`#3`](https://github.com/ljharb/get-intrinsic/issues/3) + +### Commits + +- [Tests] migrate tests to Github Actions [`2ab762b`](https://github.com/ljharb/get-intrinsic/commit/2ab762b48164aea8af37a40ba105bbc8246ab8c4) +- [meta] do not publish github action workflow files [`5e7108e`](https://github.com/ljharb/get-intrinsic/commit/5e7108e4768b244d48d9567ba4f8a6cab9c65b8e) +- [Tests] add some coverage [`01ac7a8`](https://github.com/ljharb/get-intrinsic/commit/01ac7a87ac29738567e8524cd8c9e026b1fa8cb3) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `call-bind`, `es-abstract`, `tape`; add `call-bind` [`911b672`](https://github.com/ljharb/get-intrinsic/commit/911b672fbffae433a96924c6ce013585e425f4b7) +- [Refactor] rearrange evalled constructors a bit [`7e7e4bf`](https://github.com/ljharb/get-intrinsic/commit/7e7e4bf583f3799c8ac1c6c5e10d2cb553957347) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`0199968`](https://github.com/ljharb/get-intrinsic/commit/01999687a263ffce0a3cb011dfbcb761754aedbc) + +## [v1.0.2](https://github.com/ljharb/get-intrinsic/compare/v1.0.1...v1.0.2) - 2020-12-17 + +### Commits + +- [Fix] Throw for non‑existent intrinsics [`68f873b`](https://github.com/ljharb/get-intrinsic/commit/68f873b013c732a05ad6f5fc54f697e55515461b) +- [Fix] Throw for non‑existent segments in the intrinsic path [`8325dee`](https://github.com/ljharb/get-intrinsic/commit/8325deee43128f3654d3399aa9591741ebe17b21) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-bigints`, `object-inspect` [`0c227a7`](https://github.com/ljharb/get-intrinsic/commit/0c227a7d8b629166f25715fd242553892e458525) +- [meta] do not lint coverage output [`70d2419`](https://github.com/ljharb/get-intrinsic/commit/70d24199b620043cd9110fc5f426d214ebe21dc9) + +## [v1.0.1](https://github.com/ljharb/get-intrinsic/compare/v1.0.0...v1.0.1) - 2020-10-30 + +### Commits + +- [Tests] gather coverage data on every job [`d1d280d`](https://github.com/ljharb/get-intrinsic/commit/d1d280dec714e3f0519cc877dbcb193057d9cac6) +- [Fix] add missing dependencies [`5031771`](https://github.com/ljharb/get-intrinsic/commit/5031771bb1095b38be88ce7c41d5de88718e432e) +- [Tests] use `es-value-fixtures` [`af48765`](https://github.com/ljharb/get-intrinsic/commit/af48765a23c5323fb0b6b38dbf00eb5099c7bebc) + +## v1.0.0 - 2020-10-29 + +### Commits + +- Implementation [`bbce57c`](https://github.com/ljharb/get-intrinsic/commit/bbce57c6f33d05b2d8d3efa273ceeb3ee01127bb) +- Tests [`17b4f0d`](https://github.com/ljharb/get-intrinsic/commit/17b4f0d56dea6b4059b56fc30ef3ee4d9500ebc2) +- Initial commit [`3153294`](https://github.com/ljharb/get-intrinsic/commit/31532948de363b0a27dd9fd4649e7b7028ec4b44) +- npm init [`fb326c4`](https://github.com/ljharb/get-intrinsic/commit/fb326c4d2817c8419ec31de1295f06bb268a7902) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`48862fb`](https://github.com/ljharb/get-intrinsic/commit/48862fb2508c8f6a57968e6d08b7c883afc9d550) +- [meta] add `auto-changelog` [`5f28ad0`](https://github.com/ljharb/get-intrinsic/commit/5f28ad019e060a353d8028f9f2591a9cc93074a1) +- [meta] add "funding"; create `FUNDING.yml` [`c2bbdde`](https://github.com/ljharb/get-intrinsic/commit/c2bbddeba73a875be61484ee4680b129a6d4e0a1) +- [Tests] add `npm run lint` [`0a84b98`](https://github.com/ljharb/get-intrinsic/commit/0a84b98b22b7cf7a748666f705b0003a493c35fd) +- Only apps should have lockfiles [`9586c75`](https://github.com/ljharb/get-intrinsic/commit/9586c75866c1ee678e4d5d4dbbdef6997e511b05) diff --git a/node_modules/get-intrinsic/LICENSE b/node_modules/get-intrinsic/LICENSE new file mode 100644 index 000000000..48f05d01d --- /dev/null +++ b/node_modules/get-intrinsic/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/get-intrinsic/README.md b/node_modules/get-intrinsic/README.md new file mode 100644 index 000000000..3aa0bba40 --- /dev/null +++ b/node_modules/get-intrinsic/README.md @@ -0,0 +1,71 @@ +# get-intrinsic [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Get and robustly cache all JS language-level intrinsics at first require time. + +See the syntax described [in the JS spec](https://tc39.es/ecma262/#sec-well-known-intrinsic-objects) for reference. + +## Example + +```js +var GetIntrinsic = require('get-intrinsic'); +var assert = require('assert'); + +// static methods +assert.equal(GetIntrinsic('%Math.pow%'), Math.pow); +assert.equal(Math.pow(2, 3), 8); +assert.equal(GetIntrinsic('%Math.pow%')(2, 3), 8); +delete Math.pow; +assert.equal(GetIntrinsic('%Math.pow%')(2, 3), 8); + +// instance methods +var arr = [1]; +assert.equal(GetIntrinsic('%Array.prototype.push%'), Array.prototype.push); +assert.deepEqual(arr, [1]); + +arr.push(2); +assert.deepEqual(arr, [1, 2]); + +GetIntrinsic('%Array.prototype.push%').call(arr, 3); +assert.deepEqual(arr, [1, 2, 3]); + +delete Array.prototype.push; +GetIntrinsic('%Array.prototype.push%').call(arr, 4); +assert.deepEqual(arr, [1, 2, 3, 4]); + +// missing features +delete JSON.parse; // to simulate a real intrinsic that is missing in the environment +assert.throws(() => GetIntrinsic('%JSON.parse%')); +assert.equal(undefined, GetIntrinsic('%JSON.parse%', true)); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/get-intrinsic +[npm-version-svg]: https://versionbadg.es/ljharb/get-intrinsic.svg +[deps-svg]: https://david-dm.org/ljharb/get-intrinsic.svg +[deps-url]: https://david-dm.org/ljharb/get-intrinsic +[dev-deps-svg]: https://david-dm.org/ljharb/get-intrinsic/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/get-intrinsic#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/get-intrinsic.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/get-intrinsic.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/get-intrinsic.svg +[downloads-url]: https://npm-stat.com/charts.html?package=get-intrinsic +[codecov-image]: https://codecov.io/gh/ljharb/get-intrinsic/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/get-intrinsic/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/get-intrinsic +[actions-url]: https://github.com/ljharb/get-intrinsic/actions diff --git a/node_modules/get-intrinsic/index.js b/node_modules/get-intrinsic/index.js new file mode 100644 index 000000000..c25e2c42e --- /dev/null +++ b/node_modules/get-intrinsic/index.js @@ -0,0 +1,359 @@ +'use strict'; + +var undefined; + +var $Error = require('es-errors'); +var $EvalError = require('es-errors/eval'); +var $RangeError = require('es-errors/range'); +var $ReferenceError = require('es-errors/ref'); +var $SyntaxError = require('es-errors/syntax'); +var $TypeError = require('es-errors/type'); +var $URIError = require('es-errors/uri'); + +var $Function = Function; + +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; + +var $gOPD = Object.getOwnPropertyDescriptor; +if ($gOPD) { + try { + $gOPD({}, ''); + } catch (e) { + $gOPD = null; // this is IE 8, which has a broken gOPD + } +} + +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = require('has-symbols')(); +var hasProto = require('has-proto')(); + +var getProto = Object.getPrototypeOf || ( + hasProto + ? function (x) { return x.__proto__; } // eslint-disable-line no-proto + : null +); + +var needsEval = {}; + +var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + __proto__: null, + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, + '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': $Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': $EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': Object, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': $RangeError, + '%ReferenceError%': $ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': $URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet +}; + +if (getProto) { + try { + null.error; // eslint-disable-line no-unused-expressions + } catch (e) { + // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 + var errorProto = getProto(getProto(e)); + INTRINSICS['%Error.prototype%'] = errorProto; + } +} + +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; +}; + +var LEGACY_ALIASES = { + __proto__: null, + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; + +var bind = require('function-bind'); +var hasOwn = require('hasown'); +var $concat = bind.call(Function.call, Array.prototype.concat); +var $spliceApply = bind.call(Function.apply, Array.prototype.splice); +var $replace = bind.call(Function.call, String.prototype.replace); +var $strSlice = bind.call(Function.call, String.prototype.slice); +var $exec = bind.call(Function.call, RegExp.prototype.exec); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; + +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; diff --git a/node_modules/get-intrinsic/package.json b/node_modules/get-intrinsic/package.json new file mode 100644 index 000000000..568dff997 --- /dev/null +++ b/node_modules/get-intrinsic/package.json @@ -0,0 +1,93 @@ +{ + "name": "get-intrinsic", + "version": "1.2.4", + "description": "Get and robustly cache all JS language-level intrinsics at first require time", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=.js,.mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/get-intrinsic.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "es", + "js", + "intrinsic", + "getintrinsic", + "es-abstract" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/get-intrinsic/issues" + }, + "homepage": "https://github.com/ljharb/get-intrinsic#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "call-bind": "^1.0.5", + "es-abstract": "^1.22.3", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "make-async-function": "^1.0.0", + "make-async-generator-function": "^1.0.0", + "make-generator-function": "^2.0.0", + "mock-property": "^1.0.3", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + }, + "testling": { + "files": "test/GetIntrinsic.js" + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/get-intrinsic/test/GetIntrinsic.js b/node_modules/get-intrinsic/test/GetIntrinsic.js new file mode 100644 index 000000000..1cc08e00c --- /dev/null +++ b/node_modules/get-intrinsic/test/GetIntrinsic.js @@ -0,0 +1,274 @@ +'use strict'; + +var GetIntrinsic = require('../'); + +var test = require('tape'); +var forEach = require('for-each'); +var debug = require('object-inspect'); +var generatorFns = require('make-generator-function')(); +var asyncFns = require('make-async-function').list(); +var asyncGenFns = require('make-async-generator-function')(); +var mockProperty = require('mock-property'); + +var callBound = require('call-bind/callBound'); +var v = require('es-value-fixtures'); +var $gOPD = require('gopd'); +var DefinePropertyOrThrow = require('es-abstract/2021/DefinePropertyOrThrow'); + +var $isProto = callBound('%Object.prototype.isPrototypeOf%'); + +test('export', function (t) { + t.equal(typeof GetIntrinsic, 'function', 'it is a function'); + t.equal(GetIntrinsic.length, 2, 'function has length of 2'); + + t.end(); +}); + +test('throws', function (t) { + t['throws']( + function () { GetIntrinsic('not an intrinsic'); }, + SyntaxError, + 'nonexistent intrinsic throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic(''); }, + TypeError, + 'empty string intrinsic throws a type error' + ); + + t['throws']( + function () { GetIntrinsic('.'); }, + SyntaxError, + '"just a dot" intrinsic throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic('%String'); }, + SyntaxError, + 'Leading % without trailing % throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic('String%'); }, + SyntaxError, + 'Trailing % without leading % throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic("String['prototype]"); }, + SyntaxError, + 'Dynamic property access is disallowed for intrinsics (unterminated string)' + ); + + t['throws']( + function () { GetIntrinsic('%Proxy.prototype.undefined%'); }, + TypeError, + "Throws when middle part doesn't exist (%Proxy.prototype.undefined%)" + ); + + t['throws']( + function () { GetIntrinsic('%Array.prototype%garbage%'); }, + SyntaxError, + 'Throws with extra percent signs' + ); + + t['throws']( + function () { GetIntrinsic('%Array.prototype%push%'); }, + SyntaxError, + 'Throws with extra percent signs, even on an existing intrinsic' + ); + + forEach(v.nonStrings, function (nonString) { + t['throws']( + function () { GetIntrinsic(nonString); }, + TypeError, + debug(nonString) + ' is not a String' + ); + }); + + forEach(v.nonBooleans, function (nonBoolean) { + t['throws']( + function () { GetIntrinsic('%', nonBoolean); }, + TypeError, + debug(nonBoolean) + ' is not a Boolean' + ); + }); + + forEach([ + 'toString', + 'propertyIsEnumerable', + 'hasOwnProperty' + ], function (objectProtoMember) { + t['throws']( + function () { GetIntrinsic(objectProtoMember); }, + SyntaxError, + debug(objectProtoMember) + ' is not an intrinsic' + ); + }); + + t.end(); +}); + +test('base intrinsics', function (t) { + t.equal(GetIntrinsic('%Object%'), Object, '%Object% yields Object'); + t.equal(GetIntrinsic('Object'), Object, 'Object yields Object'); + t.equal(GetIntrinsic('%Array%'), Array, '%Array% yields Array'); + t.equal(GetIntrinsic('Array'), Array, 'Array yields Array'); + + t.end(); +}); + +test('dotted paths', function (t) { + t.equal(GetIntrinsic('%Object.prototype.toString%'), Object.prototype.toString, '%Object.prototype.toString% yields Object.prototype.toString'); + t.equal(GetIntrinsic('Object.prototype.toString'), Object.prototype.toString, 'Object.prototype.toString yields Object.prototype.toString'); + t.equal(GetIntrinsic('%Array.prototype.push%'), Array.prototype.push, '%Array.prototype.push% yields Array.prototype.push'); + t.equal(GetIntrinsic('Array.prototype.push'), Array.prototype.push, 'Array.prototype.push yields Array.prototype.push'); + + test('underscore paths are aliases for dotted paths', { skip: !Object.isFrozen || Object.isFrozen(Object.prototype) }, function (st) { + var original = GetIntrinsic('%ObjProto_toString%'); + + forEach([ + '%Object.prototype.toString%', + 'Object.prototype.toString', + '%ObjectPrototype.toString%', + 'ObjectPrototype.toString', + '%ObjProto_toString%', + 'ObjProto_toString' + ], function (name) { + DefinePropertyOrThrow(Object.prototype, 'toString', { + '[[Value]]': function toString() { + return original.apply(this, arguments); + } + }); + st.equal(GetIntrinsic(name), original, name + ' yields original Object.prototype.toString'); + }); + + DefinePropertyOrThrow(Object.prototype, 'toString', { '[[Value]]': original }); + st.end(); + }); + + test('dotted paths cache', { skip: !Object.isFrozen || Object.isFrozen(Object.prototype) }, function (st) { + var original = GetIntrinsic('%Object.prototype.propertyIsEnumerable%'); + + forEach([ + '%Object.prototype.propertyIsEnumerable%', + 'Object.prototype.propertyIsEnumerable', + '%ObjectPrototype.propertyIsEnumerable%', + 'ObjectPrototype.propertyIsEnumerable' + ], function (name) { + var restore = mockProperty(Object.prototype, 'propertyIsEnumerable', { + value: function propertyIsEnumerable() { + return original.apply(this, arguments); + } + }); + st.equal(GetIntrinsic(name), original, name + ' yields cached Object.prototype.propertyIsEnumerable'); + + restore(); + }); + + st.end(); + }); + + test('dotted path reports correct error', function (st) { + st['throws'](function () { + GetIntrinsic('%NonExistentIntrinsic.prototype.property%'); + }, /%NonExistentIntrinsic%/, 'The base intrinsic of %NonExistentIntrinsic.prototype.property% is %NonExistentIntrinsic%'); + + st['throws'](function () { + GetIntrinsic('%NonExistentIntrinsicPrototype.property%'); + }, /%NonExistentIntrinsicPrototype%/, 'The base intrinsic of %NonExistentIntrinsicPrototype.property% is %NonExistentIntrinsicPrototype%'); + + st.end(); + }); + + t.end(); +}); + +test('accessors', { skip: !$gOPD || typeof Map !== 'function' }, function (t) { + var actual = $gOPD(Map.prototype, 'size'); + t.ok(actual, 'Map.prototype.size has a descriptor'); + t.equal(typeof actual.get, 'function', 'Map.prototype.size has a getter function'); + t.equal(GetIntrinsic('%Map.prototype.size%'), actual.get, '%Map.prototype.size% yields the getter for it'); + t.equal(GetIntrinsic('Map.prototype.size'), actual.get, 'Map.prototype.size yields the getter for it'); + + t.end(); +}); + +test('generator functions', { skip: !generatorFns.length }, function (t) { + var $GeneratorFunction = GetIntrinsic('%GeneratorFunction%'); + var $GeneratorFunctionPrototype = GetIntrinsic('%Generator%'); + var $GeneratorPrototype = GetIntrinsic('%GeneratorPrototype%'); + + forEach(generatorFns, function (genFn) { + var fnName = genFn.name; + fnName = fnName ? "'" + fnName + "'" : 'genFn'; + + t.ok(genFn instanceof $GeneratorFunction, fnName + ' instanceof %GeneratorFunction%'); + t.ok($isProto($GeneratorFunctionPrototype, genFn), '%Generator% is prototype of ' + fnName); + t.ok($isProto($GeneratorPrototype, genFn.prototype), '%GeneratorPrototype% is prototype of ' + fnName + '.prototype'); + }); + + t.end(); +}); + +test('async functions', { skip: !asyncFns.length }, function (t) { + var $AsyncFunction = GetIntrinsic('%AsyncFunction%'); + var $AsyncFunctionPrototype = GetIntrinsic('%AsyncFunctionPrototype%'); + + forEach(asyncFns, function (asyncFn) { + var fnName = asyncFn.name; + fnName = fnName ? "'" + fnName + "'" : 'asyncFn'; + + t.ok(asyncFn instanceof $AsyncFunction, fnName + ' instanceof %AsyncFunction%'); + t.ok($isProto($AsyncFunctionPrototype, asyncFn), '%AsyncFunctionPrototype% is prototype of ' + fnName); + }); + + t.end(); +}); + +test('async generator functions', { skip: asyncGenFns.length === 0 }, function (t) { + var $AsyncGeneratorFunction = GetIntrinsic('%AsyncGeneratorFunction%'); + var $AsyncGeneratorFunctionPrototype = GetIntrinsic('%AsyncGenerator%'); + var $AsyncGeneratorPrototype = GetIntrinsic('%AsyncGeneratorPrototype%'); + + forEach(asyncGenFns, function (asyncGenFn) { + var fnName = asyncGenFn.name; + fnName = fnName ? "'" + fnName + "'" : 'asyncGenFn'; + + t.ok(asyncGenFn instanceof $AsyncGeneratorFunction, fnName + ' instanceof %AsyncGeneratorFunction%'); + t.ok($isProto($AsyncGeneratorFunctionPrototype, asyncGenFn), '%AsyncGenerator% is prototype of ' + fnName); + t.ok($isProto($AsyncGeneratorPrototype, asyncGenFn.prototype), '%AsyncGeneratorPrototype% is prototype of ' + fnName + '.prototype'); + }); + + t.end(); +}); + +test('%ThrowTypeError%', function (t) { + var $ThrowTypeError = GetIntrinsic('%ThrowTypeError%'); + + t.equal(typeof $ThrowTypeError, 'function', 'is a function'); + t['throws']( + $ThrowTypeError, + TypeError, + '%ThrowTypeError% throws a TypeError' + ); + + t.end(); +}); + +test('allowMissing', { skip: asyncGenFns.length > 0 }, function (t) { + t['throws']( + function () { GetIntrinsic('%AsyncGeneratorPrototype%'); }, + TypeError, + 'throws when missing' + ); + + t.equal( + GetIntrinsic('%AsyncGeneratorPrototype%', true), + undefined, + 'does not throw when allowMissing' + ); + + t.end(); +}); diff --git a/node_modules/glob/README.md b/node_modules/glob/README.md index 0916a4825..83f0c83a0 100644 --- a/node_modules/glob/README.md +++ b/node_modules/glob/README.md @@ -7,7 +7,7 @@ Match files using the patterns the shell uses, like stars and stuff. This is a glob implementation in JavaScript. It uses the `minimatch` library to do its matching. -![](logo/glob.png) +![a fun cartoon logo made of glob characters](logo/glob.png) ## Usage @@ -276,6 +276,9 @@ the filesystem. * `absolute` Set to true to always receive absolute paths for matched files. Unlike `realpath`, this also affects the values returned in the `match` event. +* `fs` File-system object with Node's `fs` API. By default, the built-in + `fs` module will be used. Set to a volume provided by a library like + `memfs` to avoid using the "real" file-system. ## Comparisons to other fnmatch/glob implementations diff --git a/node_modules/glob/changelog.md b/node_modules/glob/changelog.md deleted file mode 100644 index 41636771e..000000000 --- a/node_modules/glob/changelog.md +++ /dev/null @@ -1,67 +0,0 @@ -## 7.0 - -- Raise error if `options.cwd` is specified, and not a directory - -## 6.0 - -- Remove comment and negation pattern support -- Ignore patterns are always in `dot:true` mode - -## 5.0 - -- Deprecate comment and negation patterns -- Fix regression in `mark` and `nodir` options from making all cache - keys absolute path. -- Abort if `fs.readdir` returns an error that's unexpected -- Don't emit `match` events for ignored items -- Treat ENOTSUP like ENOTDIR in readdir - -## 4.5 - -- Add `options.follow` to always follow directory symlinks in globstar -- Add `options.realpath` to call `fs.realpath` on all results -- Always cache based on absolute path - -## 4.4 - -- Add `options.ignore` -- Fix handling of broken symlinks - -## 4.3 - -- Bump minimatch to 2.x -- Pass all tests on Windows - -## 4.2 - -- Add `glob.hasMagic` function -- Add `options.nodir` flag - -## 4.1 - -- Refactor sync and async implementations for performance -- Throw if callback provided to sync glob function -- Treat symbolic links in globstar results the same as Bash 4.3 - -## 4.0 - -- Use `^` for dependency versions (bumped major because this breaks - older npm versions) -- Ensure callbacks are only ever called once -- switch to ISC license - -## 3.x - -- Rewrite in JavaScript -- Add support for setting root, cwd, and windows support -- Cache many fs calls -- Add globstar support -- emit match events - -## 2.x - -- Use `glob.h` and `fnmatch.h` from NetBSD - -## 1.x - -- `glob.h` static binding. diff --git a/node_modules/glob/common.js b/node_modules/glob/common.js index 66651bb3a..424c46e1d 100644 --- a/node_modules/glob/common.js +++ b/node_modules/glob/common.js @@ -1,5 +1,3 @@ -exports.alphasort = alphasort -exports.alphasorti = alphasorti exports.setopts = setopts exports.ownProp = ownProp exports.makeAbs = makeAbs @@ -12,17 +10,14 @@ function ownProp (obj, field) { return Object.prototype.hasOwnProperty.call(obj, field) } +var fs = require("fs") var path = require("path") var minimatch = require("minimatch") var isAbsolute = require("path-is-absolute") var Minimatch = minimatch.Minimatch -function alphasorti (a, b) { - return a.toLowerCase().localeCompare(b.toLowerCase()) -} - function alphasort (a, b) { - return a.localeCompare(b) + return a.localeCompare(b, 'en') } function setupIgnores (self, options) { @@ -81,6 +76,7 @@ function setopts (self, pattern, options) { self.stat = !!options.stat self.noprocess = !!options.noprocess self.absolute = !!options.absolute + self.fs = options.fs || fs self.maxLength = options.maxLength || Infinity self.cache = options.cache || Object.create(null) @@ -114,6 +110,8 @@ function setopts (self, pattern, options) { // Note that they are not supported in Glob itself anyway. options.nonegate = true options.nocomment = true + // always treat \ in patterns as escapes, not path separators + options.allowWindowsEscape = false self.minimatch = new Minimatch(pattern, options) self.options = self.minimatch.options @@ -150,7 +148,7 @@ function finish (self) { all = Object.keys(all) if (!self.nosort) - all = all.sort(self.nocase ? alphasorti : alphasort) + all = all.sort(alphasort) // at *some* point we statted all of these if (self.mark) { diff --git a/node_modules/glob/glob.js b/node_modules/glob/glob.js index 58dec0f6c..37a4d7e60 100644 --- a/node_modules/glob/glob.js +++ b/node_modules/glob/glob.js @@ -40,7 +40,6 @@ module.exports = glob -var fs = require('fs') var rp = require('fs.realpath') var minimatch = require('minimatch') var Minimatch = minimatch.Minimatch @@ -51,8 +50,6 @@ var assert = require('assert') var isAbsolute = require('path-is-absolute') var globSync = require('./sync.js') var common = require('./common.js') -var alphasort = common.alphasort -var alphasorti = common.alphasorti var setopts = common.setopts var ownProp = common.ownProp var inflight = require('inflight') @@ -345,7 +342,10 @@ Glob.prototype._process = function (pattern, index, inGlobStar, cb) { var read if (prefix === null) read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix @@ -503,7 +503,7 @@ Glob.prototype._readdirInGlobStar = function (abs, cb) { var lstatcb = inflight(lstatkey, lstatcb_) if (lstatcb) - fs.lstat(abs, lstatcb) + self.fs.lstat(abs, lstatcb) function lstatcb_ (er, lstat) { if (er && er.code === 'ENOENT') @@ -544,7 +544,7 @@ Glob.prototype._readdir = function (abs, inGlobStar, cb) { } var self = this - fs.readdir(abs, readdirCb(this, abs, cb)) + self.fs.readdir(abs, readdirCb(this, abs, cb)) } function readdirCb (self, abs, cb) { @@ -748,13 +748,13 @@ Glob.prototype._stat = function (f, cb) { var self = this var statcb = inflight('stat\0' + abs, lstatcb_) if (statcb) - fs.lstat(abs, statcb) + self.fs.lstat(abs, statcb) function lstatcb_ (er, lstat) { if (lstat && lstat.isSymbolicLink()) { // If it's a symlink, then treat it as the target, unless // the target does not exist, then treat it as a file. - return fs.stat(abs, function (er, stat) { + return self.fs.stat(abs, function (er, stat) { if (er) self._stat2(f, abs, null, lstat, cb) else diff --git a/node_modules/glob/package.json b/node_modules/glob/package.json index a3230d07d..5940b649b 100644 --- a/node_modules/glob/package.json +++ b/node_modules/glob/package.json @@ -1,83 +1,55 @@ { - "_from": "glob@^7.1.2", - "_id": "glob@7.1.6", - "_inBundle": false, - "_integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", - "_location": "/glob", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "glob@^7.1.2", - "name": "glob", - "escapedName": "glob", - "rawSpec": "^7.1.2", - "saveSpec": null, - "fetchSpec": "^7.1.2" + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "name": "glob", + "description": "a little globber", + "version": "7.2.3", + "publishConfig": { + "tag": "v7-legacy" }, - "_requiredBy": [ - "/@jest/reporters", - "/jest-config", - "/jest-runtime", - "/rimraf", - "/test-exclude" - ], - "_resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", - "_shasum": "141f33b81a7c2492e125594307480c46679278a6", - "_spec": "glob@^7.1.2", - "_where": "/Users/hcliff/src/github-asana-action/node_modules/@jest/reporters", - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-glob.git" }, - "bugs": { - "url": "https://github.com/isaacs/node-glob/issues" + "main": "glob.js", + "files": [ + "glob.js", + "sync.js", + "common.js" + ], + "engines": { + "node": "*" }, - "bundleDependencies": false, "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", - "minimatch": "^3.0.4", + "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" }, - "deprecated": false, - "description": "a little globber", "devDependencies": { + "memfs": "^3.2.0", "mkdirp": "0", "rimraf": "^2.2.8", - "tap": "^12.0.1", + "tap": "^15.0.6", "tick": "0.0.6" }, - "engines": { - "node": "*" - }, - "files": [ - "glob.js", - "sync.js", - "common.js" - ], - "funding": { - "url": "https://github.com/sponsors/isaacs" - }, - "homepage": "https://github.com/isaacs/node-glob#readme", - "license": "ISC", - "main": "glob.js", - "name": "glob", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/node-glob.git" + "tap": { + "before": "test/00-setup.js", + "after": "test/zz-cleanup.js", + "jobs": 1 }, "scripts": { - "bench": "bash benchmark.sh", - "benchclean": "node benchclean.js", "prepublish": "npm run benchclean", - "prof": "bash prof.sh && cat profile.txt", "profclean": "rm -f v8.log profile.txt", - "test": "tap test/*.js --cov", - "test-regen": "npm run profclean && TEST_REGEN=1 node test/00-setup.js" + "test": "tap", + "test-regen": "npm run profclean && TEST_REGEN=1 node test/00-setup.js", + "bench": "bash benchmark.sh", + "prof": "bash prof.sh && cat profile.txt", + "benchclean": "node benchclean.js" }, - "version": "7.1.6" + "license": "ISC", + "funding": { + "url": "https://github.com/sponsors/isaacs" + } } diff --git a/node_modules/glob/sync.js b/node_modules/glob/sync.js index c952134ba..2c4f48019 100644 --- a/node_modules/glob/sync.js +++ b/node_modules/glob/sync.js @@ -1,7 +1,6 @@ module.exports = globSync globSync.GlobSync = GlobSync -var fs = require('fs') var rp = require('fs.realpath') var minimatch = require('minimatch') var Minimatch = minimatch.Minimatch @@ -11,8 +10,6 @@ var path = require('path') var assert = require('assert') var isAbsolute = require('path-is-absolute') var common = require('./common.js') -var alphasort = common.alphasort -var alphasorti = common.alphasorti var setopts = common.setopts var ownProp = common.ownProp var childrenIgnored = common.childrenIgnored @@ -51,7 +48,7 @@ function GlobSync (pattern, options) { } GlobSync.prototype._finish = function () { - assert(this instanceof GlobSync) + assert.ok(this instanceof GlobSync) if (this.realpath) { var self = this this.matches.forEach(function (matchset, index) { @@ -75,7 +72,7 @@ GlobSync.prototype._finish = function () { GlobSync.prototype._process = function (pattern, index, inGlobStar) { - assert(this instanceof GlobSync) + assert.ok(this instanceof GlobSync) // Get the first [n] parts of pattern that are all strings. var n = 0 @@ -112,7 +109,10 @@ GlobSync.prototype._process = function (pattern, index, inGlobStar) { var read if (prefix === null) read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix @@ -248,7 +248,7 @@ GlobSync.prototype._readdirInGlobStar = function (abs) { var lstat var stat try { - lstat = fs.lstatSync(abs) + lstat = this.fs.lstatSync(abs) } catch (er) { if (er.code === 'ENOENT') { // lstat failed, doesn't exist @@ -285,7 +285,7 @@ GlobSync.prototype._readdir = function (abs, inGlobStar) { } try { - return this._readdirEntries(abs, fs.readdirSync(abs)) + return this._readdirEntries(abs, this.fs.readdirSync(abs)) } catch (er) { this._readdirError(abs, er) return null @@ -444,7 +444,7 @@ GlobSync.prototype._stat = function (f) { if (!stat) { var lstat try { - lstat = fs.lstatSync(abs) + lstat = this.fs.lstatSync(abs) } catch (er) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false @@ -454,7 +454,7 @@ GlobSync.prototype._stat = function (f) { if (lstat && lstat.isSymbolicLink()) { try { - stat = fs.statSync(abs) + stat = this.fs.statSync(abs) } catch (er) { stat = lstat } diff --git a/node_modules/gopd/.eslintrc b/node_modules/gopd/.eslintrc new file mode 100644 index 000000000..e2550c0fb --- /dev/null +++ b/node_modules/gopd/.eslintrc @@ -0,0 +1,16 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-style": [2, "declaration"], + "id-length": 0, + "multiline-comment-style": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, +} diff --git a/node_modules/gopd/.github/FUNDING.yml b/node_modules/gopd/.github/FUNDING.yml new file mode 100644 index 000000000..94a44a8e8 --- /dev/null +++ b/node_modules/gopd/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/gopd +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/gopd/CHANGELOG.md b/node_modules/gopd/CHANGELOG.md new file mode 100644 index 000000000..f111eb178 --- /dev/null +++ b/node_modules/gopd/CHANGELOG.md @@ -0,0 +1,25 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.1](https://github.com/ljharb/gopd/compare/v1.0.0...v1.0.1) - 2022-11-01 + +### Commits + +- [Fix] actually export gOPD instead of dP [`4b624bf`](https://github.com/ljharb/gopd/commit/4b624bfbeff788c5e3ff16d9443a83627847234f) + +## v1.0.0 - 2022-11-01 + +### Commits + +- Initial implementation, tests, readme [`0911e01`](https://github.com/ljharb/gopd/commit/0911e012cd642092bd88b732c161c58bf4f20bea) +- Initial commit [`b84e33f`](https://github.com/ljharb/gopd/commit/b84e33f5808a805ac57ff88d4247ad935569acbe) +- [actions] add reusable workflows [`12ae28a`](https://github.com/ljharb/gopd/commit/12ae28ae5f50f86e750215b6e2188901646d0119) +- npm init [`280118b`](https://github.com/ljharb/gopd/commit/280118badb45c80b4483836b5cb5315bddf6e582) +- [meta] add `auto-changelog` [`bb78de5`](https://github.com/ljharb/gopd/commit/bb78de5639a180747fb290c28912beaaf1615709) +- [meta] create FUNDING.yml; add `funding` in package.json [`11c22e6`](https://github.com/ljharb/gopd/commit/11c22e6355bb01f24e7fac4c9bb3055eb5b25002) +- [meta] use `npmignore` to autogenerate an npmignore file [`4f4537a`](https://github.com/ljharb/gopd/commit/4f4537a843b39f698c52f072845092e6fca345bb) +- Only apps should have lockfiles [`c567022`](https://github.com/ljharb/gopd/commit/c567022a18573aa7951cf5399445d9840e23e98b) diff --git a/node_modules/gopd/LICENSE b/node_modules/gopd/LICENSE new file mode 100644 index 000000000..6abfe1434 --- /dev/null +++ b/node_modules/gopd/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/gopd/README.md b/node_modules/gopd/README.md new file mode 100644 index 000000000..784e56a09 --- /dev/null +++ b/node_modules/gopd/README.md @@ -0,0 +1,40 @@ +# gopd [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +`Object.getOwnPropertyDescriptor`, but accounts for IE's broken implementation. + +## Usage + +```javascript +var gOPD = require('gopd'); +var assert = require('assert'); + +if (gOPD) { + assert.equal(typeof gOPD, 'function', 'descriptors supported'); + // use gOPD like Object.getOwnPropertyDescriptor here +} else { + assert.ok(!gOPD, 'descriptors not supported'); +} +``` + +[package-url]: https://npmjs.org/package/gopd +[npm-version-svg]: https://versionbadg.es/ljharb/gopd.svg +[deps-svg]: https://david-dm.org/ljharb/gopd.svg +[deps-url]: https://david-dm.org/ljharb/gopd +[dev-deps-svg]: https://david-dm.org/ljharb/gopd/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/gopd#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/gopd.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/gopd.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/gopd.svg +[downloads-url]: https://npm-stat.com/charts.html?package=gopd +[codecov-image]: https://codecov.io/gh/ljharb/gopd/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/gopd/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/gopd +[actions-url]: https://github.com/ljharb/gopd/actions diff --git a/node_modules/gopd/index.js b/node_modules/gopd/index.js new file mode 100644 index 000000000..fb6d3bbef --- /dev/null +++ b/node_modules/gopd/index.js @@ -0,0 +1,16 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); + +if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; + } +} + +module.exports = $gOPD; diff --git a/node_modules/gopd/package.json b/node_modules/gopd/package.json new file mode 100644 index 000000000..d5e1fa4a2 --- /dev/null +++ b/node_modules/gopd/package.json @@ -0,0 +1,71 @@ +{ + "name": "gopd", + "version": "1.0.1", + "description": "`Object.getOwnPropertyDescriptor`, but accounts for IE's broken implementation.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint --ext=js,mjs .", + "postlint": "evalmd README.md", + "pretest": "npm run lint", + "tests-only": "tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/gopd.git" + }, + "keywords": [ + "ecmascript", + "javascript", + "getownpropertydescriptor", + "property", + "descriptor" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/gopd/issues" + }, + "homepage": "https://github.com/ljharb/gopd#readme", + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.0.0", + "aud": "^2.0.1", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "safe-publish-latest": "^2.0.0", + "tape": "^5.6.1" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/gopd/test/index.js b/node_modules/gopd/test/index.js new file mode 100644 index 000000000..0376bfbad --- /dev/null +++ b/node_modules/gopd/test/index.js @@ -0,0 +1,35 @@ +'use strict'; + +var test = require('tape'); +var gOPD = require('../'); + +test('gOPD', function (t) { + t.test('supported', { skip: !gOPD }, function (st) { + st.equal(typeof gOPD, 'function', 'is a function'); + + var obj = { x: 1 }; + st.ok('x' in obj, 'property exists'); + + var desc = gOPD(obj, 'x'); + st.deepEqual( + desc, + { + configurable: true, + enumerable: true, + value: 1, + writable: true + }, + 'descriptor is as expected' + ); + + st.end(); + }); + + t.test('not supported', { skip: gOPD }, function (st) { + st.notOk(gOPD, 'is falsy'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/has-property-descriptors/.eslintrc b/node_modules/has-property-descriptors/.eslintrc new file mode 100644 index 000000000..2fcc002b0 --- /dev/null +++ b/node_modules/has-property-descriptors/.eslintrc @@ -0,0 +1,13 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "id-length": 0, + "new-cap": [2, { + "capIsNewExceptions": ["GetIntrinsic"], + }], + }, +} diff --git a/node_modules/has-property-descriptors/.github/FUNDING.yml b/node_modules/has-property-descriptors/.github/FUNDING.yml new file mode 100644 index 000000000..817aacf1f --- /dev/null +++ b/node_modules/has-property-descriptors/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/has-property-descriptors +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/has-property-descriptors/.nycrc b/node_modules/has-property-descriptors/.nycrc new file mode 100644 index 000000000..bdd626ce9 --- /dev/null +++ b/node_modules/has-property-descriptors/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/has-property-descriptors/CHANGELOG.md b/node_modules/has-property-descriptors/CHANGELOG.md new file mode 100644 index 000000000..19c8a959c --- /dev/null +++ b/node_modules/has-property-descriptors/CHANGELOG.md @@ -0,0 +1,35 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.2](https://github.com/inspect-js/has-property-descriptors/compare/v1.0.1...v1.0.2) - 2024-02-12 + +### Commits + +- [Refactor] use `es-define-property` [`f93a8c8`](https://github.com/inspect-js/has-property-descriptors/commit/f93a8c85eba70cbceab500f2619fb5cce73a1805) +- [Dev Deps] update `aud`, `npmignore`, `tape` [`42b0c9d`](https://github.com/inspect-js/has-property-descriptors/commit/42b0c9d1c23e747755f0f2924923c418ea34a9ee) +- [Deps] update `get-intrinsic` [`35e9b46`](https://github.com/inspect-js/has-property-descriptors/commit/35e9b46a7f14331bf0de98b644dd803676746037) + +## [v1.0.1](https://github.com/inspect-js/has-property-descriptors/compare/v1.0.0...v1.0.1) - 2023-10-20 + +### Commits + +- [meta] use `npmignore` to autogenerate an npmignore file [`5bbf4da`](https://github.com/inspect-js/has-property-descriptors/commit/5bbf4dae1b58950d87bb3af508bee7513e640868) +- [actions] update rebase action to use reusable workflow [`3a5585b`](https://github.com/inspect-js/has-property-descriptors/commit/3a5585bf74988f71a8f59e67a07d594e62c51fd8) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`e5c1212`](https://github.com/inspect-js/has-property-descriptors/commit/e5c1212048a8fda549794c47863724ca60b89cae) +- [Dev Deps] update `aud`, `tape` [`e942917`](https://github.com/inspect-js/has-property-descriptors/commit/e942917b6c2f7c090d5623048989cf20d0834ebf) +- [Deps] update `get-intrinsic` [`f4a44ec`](https://github.com/inspect-js/has-property-descriptors/commit/f4a44ec6d94146fa6c550d3c15c31a2062c83ef4) +- [Deps] update `get-intrinsic` [`eeb275b`](https://github.com/inspect-js/has-property-descriptors/commit/eeb275b473e5d72ca843b61ca25cfcb06a5d4300) + +## v1.0.0 - 2022-04-14 + +### Commits + +- Initial implementation, tests [`303559f`](https://github.com/inspect-js/has-property-descriptors/commit/303559f2a72dfe7111573a1aec475ed4a184c35a) +- Initial commit [`3a7ca2d`](https://github.com/inspect-js/has-property-descriptors/commit/3a7ca2dc49f1fff0279a28bb16265e7615e14749) +- read me [`dd73dce`](https://github.com/inspect-js/has-property-descriptors/commit/dd73dce09d89d0f7a4a6e3b1e562a506f979a767) +- npm init [`c1e6557`](https://github.com/inspect-js/has-property-descriptors/commit/c1e655779de632d68cb944c50da6b71bcb7b8c85) +- Only apps should have lockfiles [`e72f7c6`](https://github.com/inspect-js/has-property-descriptors/commit/e72f7c68de534b2d273ee665f8b18d4ecc7f70b0) diff --git a/node_modules/has-property-descriptors/LICENSE b/node_modules/has-property-descriptors/LICENSE new file mode 100644 index 000000000..2e7b9a3ea --- /dev/null +++ b/node_modules/has-property-descriptors/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Inspect JS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/has-property-descriptors/README.md b/node_modules/has-property-descriptors/README.md new file mode 100644 index 000000000..d81fbd99e --- /dev/null +++ b/node_modules/has-property-descriptors/README.md @@ -0,0 +1,43 @@ +# has-property-descriptors [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Does the environment have full property descriptor support? Handles IE 8's broken defineProperty/gOPD. + +## Example + +```js +var hasPropertyDescriptors = require('has-property-descriptors'); +var assert = require('assert'); + +assert.equal(hasPropertyDescriptors(), true); // will be `false` in IE 6-8, and ES5 engines + +// Arrays can not have their length `[[Defined]]` in some engines +assert.equal(hasPropertyDescriptors.hasArrayLengthDefineBug(), false); // will be `true` in Firefox 4-22, and node v0.6 +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/has-property-descriptors +[npm-version-svg]: https://versionbadg.es/inspect-js/has-property-descriptors.svg +[deps-svg]: https://david-dm.org/inspect-js/has-property-descriptors.svg +[deps-url]: https://david-dm.org/inspect-js/has-property-descriptors +[dev-deps-svg]: https://david-dm.org/inspect-js/has-property-descriptors/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/has-property-descriptors#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/has-property-descriptors.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/has-property-descriptors.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/has-property-descriptors.svg +[downloads-url]: https://npm-stat.com/charts.html?package=has-property-descriptors +[codecov-image]: https://codecov.io/gh/inspect-js/has-property-descriptors/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/has-property-descriptors/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-property-descriptors +[actions-url]: https://github.com/inspect-js/has-property-descriptors/actions diff --git a/node_modules/has-property-descriptors/index.js b/node_modules/has-property-descriptors/index.js new file mode 100644 index 000000000..04804379c --- /dev/null +++ b/node_modules/has-property-descriptors/index.js @@ -0,0 +1,22 @@ +'use strict'; + +var $defineProperty = require('es-define-property'); + +var hasPropertyDescriptors = function hasPropertyDescriptors() { + return !!$defineProperty; +}; + +hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { + // node v0.6 has a bug where array lengths can be Set but not Defined + if (!$defineProperty) { + return null; + } + try { + return $defineProperty([], 'length', { value: 1 }).length !== 1; + } catch (e) { + // In Firefox 4-22, defining length on an array throws an exception. + return true; + } +}; + +module.exports = hasPropertyDescriptors; diff --git a/node_modules/has-property-descriptors/package.json b/node_modules/has-property-descriptors/package.json new file mode 100644 index 000000000..7e70218b4 --- /dev/null +++ b/node_modules/has-property-descriptors/package.json @@ -0,0 +1,77 @@ +{ + "name": "has-property-descriptors", + "version": "1.0.2", + "description": "Does the environment have full property descriptor support? Handles IE 8's broken defineProperty/gOPD.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/has-property-descriptors.git" + }, + "keywords": [ + "property", + "descriptors", + "has", + "environment", + "env", + "defineProperty", + "getOwnPropertyDescriptor" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/has-property-descriptors/issues" + }, + "homepage": "https://github.com/inspect-js/has-property-descriptors#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.4" + }, + "dependencies": { + "es-define-property": "^1.0.0" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/has-property-descriptors/test/index.js b/node_modules/has-property-descriptors/test/index.js new file mode 100644 index 000000000..7f02bd3e6 --- /dev/null +++ b/node_modules/has-property-descriptors/test/index.js @@ -0,0 +1,57 @@ +'use strict'; + +var test = require('tape'); + +var hasPropertyDescriptors = require('../'); + +var sentinel = {}; + +test('hasPropertyDescriptors', function (t) { + t.equal(typeof hasPropertyDescriptors, 'function', 'is a function'); + t.equal(typeof hasPropertyDescriptors.hasArrayLengthDefineBug, 'function', '`hasArrayLengthDefineBug` property is a function'); + + var yes = hasPropertyDescriptors(); + t.test('property descriptors', { skip: !yes }, function (st) { + var o = { a: sentinel }; + + st.deepEqual( + Object.getOwnPropertyDescriptor(o, 'a'), + { + configurable: true, + enumerable: true, + value: sentinel, + writable: true + }, + 'has expected property descriptor' + ); + + Object.defineProperty(o, 'a', { enumerable: false, writable: false }); + + st.deepEqual( + Object.getOwnPropertyDescriptor(o, 'a'), + { + configurable: true, + enumerable: false, + value: sentinel, + writable: false + }, + 'has expected property descriptor after [[Define]]' + ); + + st.end(); + }); + + var arrayBug = hasPropertyDescriptors.hasArrayLengthDefineBug(); + t.test('defining array lengths', { skip: !yes || arrayBug }, function (st) { + var arr = [1, , 3]; // eslint-disable-line no-sparse-arrays + st.equal(arr.length, 3, 'array starts with length 3'); + + Object.defineProperty(arr, 'length', { value: 5 }); + + st.equal(arr.length, 5, 'array ends with length 5'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/has-proto/.eslintrc b/node_modules/has-proto/.eslintrc new file mode 100644 index 000000000..3b5d9e90e --- /dev/null +++ b/node_modules/has-proto/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/node_modules/has-proto/.github/FUNDING.yml b/node_modules/has-proto/.github/FUNDING.yml new file mode 100644 index 000000000..613705c7e --- /dev/null +++ b/node_modules/has-proto/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/has-proto +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/has-proto/CHANGELOG.md b/node_modules/has-proto/CHANGELOG.md new file mode 100644 index 000000000..6690f28e6 --- /dev/null +++ b/node_modules/has-proto/CHANGELOG.md @@ -0,0 +1,38 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.3](https://github.com/inspect-js/has-proto/compare/v1.0.2...v1.0.3) - 2024-02-19 + +### Commits + +- [types] add missing declaration file [`26ecade`](https://github.com/inspect-js/has-proto/commit/26ecade05d253bb5dc376945ee3186d1fbe334f8) + +## [v1.0.2](https://github.com/inspect-js/has-proto/compare/v1.0.1...v1.0.2) - 2024-02-19 + +### Commits + +- add types [`6435262`](https://github.com/inspect-js/has-proto/commit/64352626cf511c0276d5f4bb6be770a0bf0f8524) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `npmignore`, `tape` [`f16a5e4`](https://github.com/inspect-js/has-proto/commit/f16a5e4121651e551271419f9d60fdd3561fd82c) +- [Refactor] tiny cleanup [`d1f1a4b`](https://github.com/inspect-js/has-proto/commit/d1f1a4bdc135f115a10f148ce302676224534702) +- [meta] add `sideEffects` flag [`e7ab1a6`](https://github.com/inspect-js/has-proto/commit/e7ab1a6f153b3e80dee68d1748b71e46767a0531) + +## [v1.0.1](https://github.com/inspect-js/has-proto/compare/v1.0.0...v1.0.1) - 2022-12-21 + +### Commits + +- [meta] correct URLs and description [`ef34483`](https://github.com/inspect-js/has-proto/commit/ef34483ca0d35680f271b6b96e35526151b25dfc) +- [patch] add an additional criteria [`e81959e`](https://github.com/inspect-js/has-proto/commit/e81959ed7c7a77fbf459f00cb4ef824f1099497f) +- [Dev Deps] update `aud` [`2bec2c4`](https://github.com/inspect-js/has-proto/commit/2bec2c47b072b122ff5443fba0263f6dc649531f) + +## v1.0.0 - 2022-12-12 + +### Commits + +- Initial implementation, tests, readme [`6886fea`](https://github.com/inspect-js/has-proto/commit/6886fea578f67daf69a7920b2eb7637ea6ebb0bc) +- Initial commit [`99129c8`](https://github.com/inspect-js/has-proto/commit/99129c8f42471ac89cb681ba9cb9d52a583eb94f) +- npm init [`2844ad8`](https://github.com/inspect-js/has-proto/commit/2844ad8e75b84d66a46765b3bab9d2e8ea692e10) +- Only apps should have lockfiles [`c65bc5e`](https://github.com/inspect-js/has-proto/commit/c65bc5e40b9004463f7336d47c67245fb139a36a) diff --git a/node_modules/has-proto/LICENSE b/node_modules/has-proto/LICENSE new file mode 100644 index 000000000..2e7b9a3ea --- /dev/null +++ b/node_modules/has-proto/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Inspect JS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/has-proto/README.md b/node_modules/has-proto/README.md new file mode 100644 index 000000000..145676547 --- /dev/null +++ b/node_modules/has-proto/README.md @@ -0,0 +1,38 @@ +# has-proto [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Does this environment have the ability to set the [[Prototype]] of an object on creation with `__proto__`? + +## Example + +```js +var hasProto = require('has-proto'); +var assert = require('assert'); + +assert.equal(typeof hasProto(), 'boolean'); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/has-proto +[npm-version-svg]: https://versionbadg.es/inspect-js/has-proto.svg +[deps-svg]: https://david-dm.org/inspect-js/has-proto.svg +[deps-url]: https://david-dm.org/inspect-js/has-proto +[dev-deps-svg]: https://david-dm.org/inspect-js/has-proto/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/has-proto#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/has-proto.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/has-proto.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/has-proto.svg +[downloads-url]: https://npm-stat.com/charts.html?package=has-proto +[codecov-image]: https://codecov.io/gh/inspect-js/has-proto/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/has-proto/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-proto +[actions-url]: https://github.com/inspect-js/has-proto/actions diff --git a/node_modules/has-proto/index.d.ts b/node_modules/has-proto/index.d.ts new file mode 100644 index 000000000..cfed6951b --- /dev/null +++ b/node_modules/has-proto/index.d.ts @@ -0,0 +1,3 @@ +declare function hasProto(): boolean; + +export = hasProto; \ No newline at end of file diff --git a/node_modules/has-proto/index.js b/node_modules/has-proto/index.js new file mode 100644 index 000000000..d3c8a0afd --- /dev/null +++ b/node_modules/has-proto/index.js @@ -0,0 +1,15 @@ +'use strict'; + +var test = { + __proto__: null, + foo: {} +}; + +var $Object = Object; + +/** @type {import('.')} */ +module.exports = function hasProto() { + // @ts-expect-error: TS errors on an inherited property for some reason + return { __proto__: test }.foo === test.foo + && !(test instanceof $Object); +}; diff --git a/node_modules/has-proto/package.json b/node_modules/has-proto/package.json new file mode 100644 index 000000000..9d37e4ed1 --- /dev/null +++ b/node_modules/has-proto/package.json @@ -0,0 +1,78 @@ +{ + "name": "has-proto", + "version": "1.0.3", + "description": "Does this environment have the ability to get the [[Prototype]] of an object on creation with `__proto__`?", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p .", + "pretest": "npm run lint", + "tests-only": "tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/has-proto.git" + }, + "keywords": [ + "prototype", + "proto", + "set", + "get", + "__proto__", + "getPrototypeOf", + "setPrototypeOf", + "has" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/has-proto/issues" + }, + "homepage": "https://github.com/inspect-js/has-proto#readme", + "testling": { + "files": "test/index.js" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.5", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/has-proto/test/index.js b/node_modules/has-proto/test/index.js new file mode 100644 index 000000000..5da1a3aa6 --- /dev/null +++ b/node_modules/has-proto/test/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var test = require('tape'); +var hasProto = require('../'); + +test('hasProto', function (t) { + var result = hasProto(); + t.equal(typeof result, 'boolean', 'returns a boolean (' + result + ')'); + + var obj = { __proto__: null }; + if (result) { + t.notOk('toString' in obj, 'null object lacks toString'); + } else { + t.ok('toString' in obj, 'without proto, null object has toString'); + t.equal(obj.__proto__, null); // eslint-disable-line no-proto + } + + t.end(); +}); diff --git a/node_modules/has-proto/tsconfig.json b/node_modules/has-proto/tsconfig.json new file mode 100644 index 000000000..2002ce5a5 --- /dev/null +++ b/node_modules/has-proto/tsconfig.json @@ -0,0 +1,49 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + + /* Language and Environment */ + "target": "ESNext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + "typeRoots": ["types"], /* Specify multiple folders that act like './node_modules/@types'. */ + "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + "maxNodeModuleJsDepth": 0, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declarationMap": true, /* Create sourcemaps for d.ts files. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + + /* Interop Constraints */ + "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + + /* Completeness */ + //"skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "exclude": [ + "coverage" + ] +} diff --git a/node_modules/has-symbols/.eslintrc b/node_modules/has-symbols/.eslintrc new file mode 100644 index 000000000..2d9a66a8a --- /dev/null +++ b/node_modules/has-symbols/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-statements-per-line": [2, { "max": 2 }], + "no-magic-numbers": 0, + "multiline-comment-style": 0, + } +} diff --git a/node_modules/has-symbols/.github/FUNDING.yml b/node_modules/has-symbols/.github/FUNDING.yml new file mode 100644 index 000000000..04cf87e66 --- /dev/null +++ b/node_modules/has-symbols/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/has-symbols +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/has-symbols/.nycrc b/node_modules/has-symbols/.nycrc new file mode 100644 index 000000000..bdd626ce9 --- /dev/null +++ b/node_modules/has-symbols/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/has-symbols/CHANGELOG.md b/node_modules/has-symbols/CHANGELOG.md new file mode 100644 index 000000000..cd532a2b4 --- /dev/null +++ b/node_modules/has-symbols/CHANGELOG.md @@ -0,0 +1,75 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.3](https://github.com/inspect-js/has-symbols/compare/v1.0.2...v1.0.3) - 2022-03-01 + +### Commits + +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`518b28f`](https://github.com/inspect-js/has-symbols/commit/518b28f6c5a516cbccae30794e40aa9f738b1693) +- [meta] add `bugs` and `homepage` fields; reorder package.json [`c480b13`](https://github.com/inspect-js/has-symbols/commit/c480b13fd6802b557e1cef9749872cb5fdeef744) +- [actions] reuse common workflows [`01d0ee0`](https://github.com/inspect-js/has-symbols/commit/01d0ee0a8d97c0947f5edb73eb722027a77b2b07) +- [actions] update codecov uploader [`6424ebe`](https://github.com/inspect-js/has-symbols/commit/6424ebe86b2c9c7c3d2e9bd4413a4e4f168cb275) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`dfa7e7f`](https://github.com/inspect-js/has-symbols/commit/dfa7e7ff38b594645d8c8222aab895157fa7e282) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`0c8d436`](https://github.com/inspect-js/has-symbols/commit/0c8d43685c45189cea9018191d4fd7eca91c9d02) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`9026554`](https://github.com/inspect-js/has-symbols/commit/902655442a1bf88e72b42345494ef0c60f5d36ab) +- [readme] add actions and codecov badges [`eaa9682`](https://github.com/inspect-js/has-symbols/commit/eaa9682f990f481d3acf7a1c7600bec36f7b3adc) +- [Dev Deps] update `eslint`, `tape` [`bc7a3ba`](https://github.com/inspect-js/has-symbols/commit/bc7a3ba46f27b7743f8a2579732d59d1b9ac791e) +- [Dev Deps] update `eslint`, `auto-changelog` [`0ace00a`](https://github.com/inspect-js/has-symbols/commit/0ace00af08a88cdd1e6ce0d60357d941c60c2d9f) +- [meta] use `prepublishOnly` script for npm 7+ [`093f72b`](https://github.com/inspect-js/has-symbols/commit/093f72bc2b0ed00c781f444922a5034257bf561d) +- [Tests] test on all 16 minors [`9b80d3d`](https://github.com/inspect-js/has-symbols/commit/9b80d3d9102529f04c20ec5b1fcc6e38426c6b03) + +## [v1.0.2](https://github.com/inspect-js/has-symbols/compare/v1.0.1...v1.0.2) - 2021-02-27 + +### Fixed + +- [Fix] use a universal way to get the original Symbol [`#11`](https://github.com/inspect-js/has-symbols/issues/11) + +### Commits + +- [Tests] migrate tests to Github Actions [`90ae798`](https://github.com/inspect-js/has-symbols/commit/90ae79820bdfe7bc703d67f5f3c5e205f98556d3) +- [meta] do not publish github action workflow files [`29e60a1`](https://github.com/inspect-js/has-symbols/commit/29e60a1b7c25c7f1acf7acff4a9320d0d10c49b4) +- [Tests] run `nyc` on all tests [`8476b91`](https://github.com/inspect-js/has-symbols/commit/8476b915650d360915abe2522505abf4b0e8f0ae) +- [readme] fix repo URLs, remove defunct badges [`126288e`](https://github.com/inspect-js/has-symbols/commit/126288ecc1797c0a40247a6b78bcb2e0bc5d7036) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `core-js`, `get-own-property-symbols` [`d84bdfa`](https://github.com/inspect-js/has-symbols/commit/d84bdfa48ac5188abbb4904b42614cd6c030940a) +- [Tests] fix linting errors [`0df3070`](https://github.com/inspect-js/has-symbols/commit/0df3070b981b6c9f2ee530c09189a7f5c6def839) +- [actions] add "Allow Edits" workflow [`1e6bc29`](https://github.com/inspect-js/has-symbols/commit/1e6bc29b188f32b9648657b07eda08504be5aa9c) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`36cea2a`](https://github.com/inspect-js/has-symbols/commit/36cea2addd4e6ec435f35a2656b4e9ef82498e9b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`1278338`](https://github.com/inspect-js/has-symbols/commit/127833801865fbc2cc8979beb9ca869c7bfe8222) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`1493254`](https://github.com/inspect-js/has-symbols/commit/1493254eda13db5fb8fc5e4a3e8324b3d196029d) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js` [`b090bf2`](https://github.com/inspect-js/has-symbols/commit/b090bf214d3679a30edc1e2d729d466ab5183e1d) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`4addb7a`](https://github.com/inspect-js/has-symbols/commit/4addb7ab4dc73f927ae99928d68817554fc21dc0) +- [Dev Deps] update `auto-changelog`, `tape` [`81d0baf`](https://github.com/inspect-js/has-symbols/commit/81d0baf3816096a89a8558e8043895f7a7d10d8b) +- [Dev Deps] update `auto-changelog`; add `aud` [`1a4e561`](https://github.com/inspect-js/has-symbols/commit/1a4e5612c25d91c3a03d509721d02630bc4fe3da) +- [readme] remove unused testling URLs [`3000941`](https://github.com/inspect-js/has-symbols/commit/3000941f958046e923ed8152edb1ef4a599e6fcc) +- [Tests] only audit prod deps [`692e974`](https://github.com/inspect-js/has-symbols/commit/692e9743c912410e9440207631a643a34b4741a1) +- [Dev Deps] update `@ljharb/eslint-config` [`51c946c`](https://github.com/inspect-js/has-symbols/commit/51c946c7f6baa793ec5390bb5a45cdce16b4ba76) + +## [v1.0.1](https://github.com/inspect-js/has-symbols/compare/v1.0.0...v1.0.1) - 2019-11-16 + +### Commits + +- [Tests] use shared travis-ci configs [`ce396c9`](https://github.com/inspect-js/has-symbols/commit/ce396c9419ff11c43d0da5d05cdbb79f7fb42229) +- [Tests] up to `node` `v12.4`, `v11.15`, `v10.15`, `v9.11`, `v8.15`, `v7.10`, `v6.17`, `v4.9`; use `nvm install-latest-npm` [`0690732`](https://github.com/inspect-js/has-symbols/commit/0690732801f47ab429f39ba1962f522d5c462d6b) +- [meta] add `auto-changelog` [`2163d0b`](https://github.com/inspect-js/has-symbols/commit/2163d0b7f36343076b8f947cd1667dd1750f26fc) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `safe-publish-latest`, `tape` [`8e0951f`](https://github.com/inspect-js/has-symbols/commit/8e0951f1a7a2e52068222b7bb73511761e6e4d9c) +- [actions] add automatic rebasing / merge commit blocking [`b09cdb7`](https://github.com/inspect-js/has-symbols/commit/b09cdb7cd7ee39e7a769878f56e2d6066f5ccd1d) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `core-js`, `get-own-property-symbols`, `tape` [`1dd42cd`](https://github.com/inspect-js/has-symbols/commit/1dd42cd86183ed0c50f99b1062345c458babca91) +- [meta] create FUNDING.yml [`aa57a17`](https://github.com/inspect-js/has-symbols/commit/aa57a17b19708906d1927f821ea8e73394d84ca4) +- Only apps should have lockfiles [`a2d8bea`](https://github.com/inspect-js/has-symbols/commit/a2d8bea23a97d15c09eaf60f5b107fcf9a4d57aa) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`9e96cb7`](https://github.com/inspect-js/has-symbols/commit/9e96cb783746cbed0c10ef78e599a8eaa7ebe193) +- [meta] add `funding` field [`a0b32cf`](https://github.com/inspect-js/has-symbols/commit/a0b32cf68e803f963c1639b6d47b0a9d6440bab0) +- [Dev Deps] update `safe-publish-latest` [`cb9f0a5`](https://github.com/inspect-js/has-symbols/commit/cb9f0a521a3a1790f1064d437edd33bb6c3d6af0) + +## v1.0.0 - 2016-09-19 + +### Commits + +- Tests. [`ecb6eb9`](https://github.com/inspect-js/has-symbols/commit/ecb6eb934e4883137f3f93b965ba5e0a98df430d) +- package.json [`88a337c`](https://github.com/inspect-js/has-symbols/commit/88a337cee0864a0da35f5d19e69ff0ef0150e46a) +- Initial commit [`42e1e55`](https://github.com/inspect-js/has-symbols/commit/42e1e5502536a2b8ac529c9443984acd14836b1c) +- Initial implementation. [`33f5cc6`](https://github.com/inspect-js/has-symbols/commit/33f5cc6cdff86e2194b081ee842bfdc63caf43fb) +- read me [`01f1170`](https://github.com/inspect-js/has-symbols/commit/01f1170188ff7cb1558aa297f6ba5b516c6d7b0c) diff --git a/node_modules/has-symbols/LICENSE b/node_modules/has-symbols/LICENSE new file mode 100644 index 000000000..df31cbf3c --- /dev/null +++ b/node_modules/has-symbols/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/has-symbols/README.md b/node_modules/has-symbols/README.md new file mode 100644 index 000000000..33905f0fc --- /dev/null +++ b/node_modules/has-symbols/README.md @@ -0,0 +1,46 @@ +# has-symbols [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Determine if the JS environment has Symbol support. Supports spec, or shams. + +## Example + +```js +var hasSymbols = require('has-symbols'); + +hasSymbols() === true; // if the environment has native Symbol support. Not polyfillable, not forgeable. + +var hasSymbolsKinda = require('has-symbols/shams'); +hasSymbolsKinda() === true; // if the environment has a Symbol sham that mostly follows the spec. +``` + +## Supported Symbol shams + - get-own-property-symbols [npm](https://www.npmjs.com/package/get-own-property-symbols) | [github](https://github.com/WebReflection/get-own-property-symbols) + - core-js [npm](https://www.npmjs.com/package/core-js) | [github](https://github.com/zloirock/core-js) + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/has-symbols +[2]: https://versionbadg.es/inspect-js/has-symbols.svg +[5]: https://david-dm.org/inspect-js/has-symbols.svg +[6]: https://david-dm.org/inspect-js/has-symbols +[7]: https://david-dm.org/inspect-js/has-symbols/dev-status.svg +[8]: https://david-dm.org/inspect-js/has-symbols#info=devDependencies +[11]: https://nodei.co/npm/has-symbols.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/has-symbols.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/has-symbols.svg +[downloads-url]: https://npm-stat.com/charts.html?package=has-symbols +[codecov-image]: https://codecov.io/gh/inspect-js/has-symbols/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/has-symbols/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-symbols +[actions-url]: https://github.com/inspect-js/has-symbols/actions diff --git a/node_modules/has-symbols/index.js b/node_modules/has-symbols/index.js new file mode 100644 index 000000000..17044fa21 --- /dev/null +++ b/node_modules/has-symbols/index.js @@ -0,0 +1,13 @@ +'use strict'; + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = require('./shams'); + +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; diff --git a/node_modules/has-symbols/package.json b/node_modules/has-symbols/package.json new file mode 100644 index 000000000..fe7004a10 --- /dev/null +++ b/node_modules/has-symbols/package.json @@ -0,0 +1,101 @@ +{ + "name": "has-symbols", + "version": "1.0.3", + "description": "Determine if the JS environment has Symbol support. Supports spec, or shams.", + "main": "index.js", + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent lint", + "test": "npm run tests-only", + "posttest": "aud --production", + "tests-only": "npm run test:stock && npm run test:staging && npm run test:shams", + "test:stock": "nyc node test", + "test:staging": "nyc node --harmony --es-staging test", + "test:shams": "npm run --silent test:shams:getownpropertysymbols && npm run --silent test:shams:corejs", + "test:shams:corejs": "nyc node test/shams/core-js.js", + "test:shams:getownpropertysymbols": "nyc node test/shams/get-own-property-symbols.js", + "lint": "eslint --ext=js,mjs .", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/has-symbols.git" + }, + "keywords": [ + "Symbol", + "symbols", + "typeof", + "sham", + "polyfill", + "native", + "core-js", + "ES6" + ], + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/has-symbols/issues" + }, + "homepage": "https://github.com/ljharb/has-symbols#readme", + "devDependencies": { + "@ljharb/eslint-config": "^20.2.3", + "aud": "^2.0.0", + "auto-changelog": "^2.4.0", + "core-js": "^2.6.12", + "eslint": "=8.8.0", + "get-own-property-symbols": "^0.9.5", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.5.2" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "greenkeeper": { + "ignore": [ + "core-js" + ] + } +} diff --git a/node_modules/has-symbols/shams.js b/node_modules/has-symbols/shams.js new file mode 100644 index 000000000..1285210ef --- /dev/null +++ b/node_modules/has-symbols/shams.js @@ -0,0 +1,42 @@ +'use strict'; + +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; diff --git a/node_modules/has-symbols/test/index.js b/node_modules/has-symbols/test/index.js new file mode 100644 index 000000000..352129ca3 --- /dev/null +++ b/node_modules/has-symbols/test/index.js @@ -0,0 +1,22 @@ +'use strict'; + +var test = require('tape'); +var hasSymbols = require('../'); +var runSymbolTests = require('./tests'); + +test('interface', function (t) { + t.equal(typeof hasSymbols, 'function', 'is a function'); + t.equal(typeof hasSymbols(), 'boolean', 'returns a boolean'); + t.end(); +}); + +test('Symbols are supported', { skip: !hasSymbols() }, function (t) { + runSymbolTests(t); + t.end(); +}); + +test('Symbols are not supported', { skip: hasSymbols() }, function (t) { + t.equal(typeof Symbol, 'undefined', 'global Symbol is undefined'); + t.equal(typeof Object.getOwnPropertySymbols, 'undefined', 'Object.getOwnPropertySymbols does not exist'); + t.end(); +}); diff --git a/node_modules/has-symbols/test/shams/core-js.js b/node_modules/has-symbols/test/shams/core-js.js new file mode 100644 index 000000000..df5365c23 --- /dev/null +++ b/node_modules/has-symbols/test/shams/core-js.js @@ -0,0 +1,28 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { + test('has native Symbol support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol(), 'symbol'); + t.end(); + }); + return; +} + +var hasSymbols = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling'); + require('core-js/fn/symbol'); + require('core-js/fn/symbol/to-string-tag'); + + require('../tests')(t); + + var hasSymbolsAfter = hasSymbols(); + t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/node_modules/has-symbols/test/shams/get-own-property-symbols.js b/node_modules/has-symbols/test/shams/get-own-property-symbols.js new file mode 100644 index 000000000..9191b248b --- /dev/null +++ b/node_modules/has-symbols/test/shams/get-own-property-symbols.js @@ -0,0 +1,28 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { + test('has native Symbol support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol(), 'symbol'); + t.end(); + }); + return; +} + +var hasSymbols = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling'); + + require('get-own-property-symbols'); + + require('../tests')(t); + + var hasSymbolsAfter = hasSymbols(); + t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/node_modules/has-symbols/test/tests.js b/node_modules/has-symbols/test/tests.js new file mode 100644 index 000000000..89edd1291 --- /dev/null +++ b/node_modules/has-symbols/test/tests.js @@ -0,0 +1,56 @@ +'use strict'; + +// eslint-disable-next-line consistent-return +module.exports = function runSymbolTests(t) { + t.equal(typeof Symbol, 'function', 'global Symbol is a function'); + + if (typeof Symbol !== 'function') { return false; } + + t.notEqual(Symbol(), Symbol(), 'two symbols are not equal'); + + /* + t.equal( + Symbol.prototype.toString.call(Symbol('foo')), + Symbol.prototype.toString.call(Symbol('foo')), + 'two symbols with the same description stringify the same' + ); + */ + + /* + var foo = Symbol('foo'); + + t.notEqual( + String(foo), + String(Symbol('bar')), + 'two symbols with different descriptions do not stringify the same' + ); + */ + + t.equal(typeof Symbol.prototype.toString, 'function', 'Symbol#toString is a function'); + // t.equal(String(foo), Symbol.prototype.toString.call(foo), 'Symbol#toString equals String of the same symbol'); + + t.equal(typeof Object.getOwnPropertySymbols, 'function', 'Object.getOwnPropertySymbols is a function'); + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + t.notEqual(typeof sym, 'string', 'Symbol is not a string'); + t.equal(Object.prototype.toString.call(sym), '[object Symbol]', 'symbol primitive Object#toStrings properly'); + t.equal(Object.prototype.toString.call(symObj), '[object Symbol]', 'symbol primitive Object#toStrings properly'); + + var symVal = 42; + obj[sym] = symVal; + // eslint-disable-next-line no-restricted-syntax + for (sym in obj) { t.fail('symbol property key was found in for..in of object'); } + + t.deepEqual(Object.keys(obj), [], 'no enumerable own keys on symbol-valued object'); + t.deepEqual(Object.getOwnPropertyNames(obj), [], 'no own names on symbol-valued object'); + t.deepEqual(Object.getOwnPropertySymbols(obj), [sym], 'one own symbol on symbol-valued object'); + t.equal(Object.prototype.propertyIsEnumerable.call(obj, sym), true, 'symbol is enumerable'); + t.deepEqual(Object.getOwnPropertyDescriptor(obj, sym), { + configurable: true, + enumerable: true, + value: 42, + writable: true + }, 'property descriptor is correct'); +}; diff --git a/node_modules/hasown/.eslintrc b/node_modules/hasown/.eslintrc new file mode 100644 index 000000000..3b5d9e90e --- /dev/null +++ b/node_modules/hasown/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/node_modules/hasown/.github/FUNDING.yml b/node_modules/hasown/.github/FUNDING.yml new file mode 100644 index 000000000..d68c8b716 --- /dev/null +++ b/node_modules/hasown/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/hasown +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/hasown/.nycrc b/node_modules/hasown/.nycrc new file mode 100644 index 000000000..1826526e0 --- /dev/null +++ b/node_modules/hasown/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/hasown/CHANGELOG.md b/node_modules/hasown/CHANGELOG.md new file mode 100644 index 000000000..2b0a980fb --- /dev/null +++ b/node_modules/hasown/CHANGELOG.md @@ -0,0 +1,40 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v2.0.2](https://github.com/inspect-js/hasOwn/compare/v2.0.1...v2.0.2) - 2024-03-10 + +### Commits + +- [types] use shared config [`68e9d4d`](https://github.com/inspect-js/hasOwn/commit/68e9d4dab6facb4f05f02c6baea94a3f2a4e44b2) +- [actions] remove redundant finisher; use reusable workflow [`241a68e`](https://github.com/inspect-js/hasOwn/commit/241a68e13ea1fe52bec5ba7f74144befc31fae7b) +- [Tests] increase coverage [`4125c0d`](https://github.com/inspect-js/hasOwn/commit/4125c0d6121db56ae30e38346dfb0c000b04f0a7) +- [Tests] skip `npm ls` in old node due to TS [`01b9282`](https://github.com/inspect-js/hasOwn/commit/01b92822f9971dea031eafdd14767df41d61c202) +- [types] improve predicate type [`d340f85`](https://github.com/inspect-js/hasOwn/commit/d340f85ce02e286ef61096cbbb6697081d40a12b) +- [Dev Deps] update `tape` [`70089fc`](https://github.com/inspect-js/hasOwn/commit/70089fcf544e64acc024cbe60f5a9b00acad86de) +- [Tests] use `@arethetypeswrong/cli` [`50b272c`](https://github.com/inspect-js/hasOwn/commit/50b272c829f40d053a3dd91c9796e0ac0b2af084) + +## [v2.0.1](https://github.com/inspect-js/hasOwn/compare/v2.0.0...v2.0.1) - 2024-02-10 + +### Commits + +- [types] use a handwritten d.ts file; fix exported type [`012b989`](https://github.com/inspect-js/hasOwn/commit/012b9898ccf91dc441e2ebf594ff70270a5fda58) +- [Dev Deps] update `@types/function-bind`, `@types/mock-property`, `@types/tape`, `aud`, `mock-property`, `npmignore`, `tape`, `typescript` [`977a56f`](https://github.com/inspect-js/hasOwn/commit/977a56f51a1f8b20566f3c471612137894644025) +- [meta] add `sideEffects` flag [`3a60b7b`](https://github.com/inspect-js/hasOwn/commit/3a60b7bf42fccd8c605e5f145a6fcc83b13cb46f) + +## [v2.0.0](https://github.com/inspect-js/hasOwn/compare/v1.0.1...v2.0.0) - 2023-10-19 + +### Commits + +- revamped implementation, tests, readme [`72bf8b3`](https://github.com/inspect-js/hasOwn/commit/72bf8b338e77a638f0a290c63ffaed18339c36b4) +- [meta] revamp package.json [`079775f`](https://github.com/inspect-js/hasOwn/commit/079775fb1ec72c1c6334069593617a0be3847458) +- Only apps should have lockfiles [`6640e23`](https://github.com/inspect-js/hasOwn/commit/6640e233d1bb8b65260880f90787637db157d215) + +## v1.0.1 - 2023-10-10 + +### Commits + +- Initial commit [`8dbfde6`](https://github.com/inspect-js/hasOwn/commit/8dbfde6e8fb0ebb076fab38d138f2984eb340a62) diff --git a/node_modules/hasown/LICENSE b/node_modules/hasown/LICENSE new file mode 100644 index 000000000..031492907 --- /dev/null +++ b/node_modules/hasown/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Jordan Harband and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/hasown/README.md b/node_modules/hasown/README.md new file mode 100644 index 000000000..f759b8a83 --- /dev/null +++ b/node_modules/hasown/README.md @@ -0,0 +1,40 @@ +# hasown [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +A robust, ES3 compatible, "has own property" predicate. + +## Example + +```js +const assert = require('assert'); +const hasOwn = require('hasown'); + +assert.equal(hasOwn({}, 'toString'), false); +assert.equal(hasOwn([], 'length'), true); +assert.equal(hasOwn({ a: 42 }, 'a'), true); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/hasown +[npm-version-svg]: https://versionbadg.es/inspect-js/hasown.svg +[deps-svg]: https://david-dm.org/inspect-js/hasOwn.svg +[deps-url]: https://david-dm.org/inspect-js/hasOwn +[dev-deps-svg]: https://david-dm.org/inspect-js/hasOwn/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/hasOwn#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/hasown.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/hasown.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/hasown.svg +[downloads-url]: https://npm-stat.com/charts.html?package=hasown +[codecov-image]: https://codecov.io/gh/inspect-js/hasOwn/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/hasOwn/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/hasOwn +[actions-url]: https://github.com/inspect-js/hasOwn/actions diff --git a/node_modules/hasown/index.d.ts b/node_modules/hasown/index.d.ts new file mode 100644 index 000000000..aafdf3b2b --- /dev/null +++ b/node_modules/hasown/index.d.ts @@ -0,0 +1,3 @@ +declare function hasOwn(o: O, p: K): o is O & Record; + +export = hasOwn; diff --git a/node_modules/hasown/index.js b/node_modules/hasown/index.js new file mode 100644 index 000000000..34e605913 --- /dev/null +++ b/node_modules/hasown/index.js @@ -0,0 +1,8 @@ +'use strict'; + +var call = Function.prototype.call; +var $hasOwn = Object.prototype.hasOwnProperty; +var bind = require('function-bind'); + +/** @type {import('.')} */ +module.exports = bind.call(call, $hasOwn); diff --git a/node_modules/hasown/package.json b/node_modules/hasown/package.json new file mode 100644 index 000000000..8502e13dd --- /dev/null +++ b/node_modules/hasown/package.json @@ -0,0 +1,92 @@ +{ + "name": "hasown", + "version": "2.0.2", + "description": "A robust, ES3 compatible, \"has own property\" predicate.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "types": "index.d.ts", + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "npm run tsc", + "pretest": "npm run lint", + "tsc": "tsc -p .", + "posttsc": "attw -P", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/hasOwn.git" + }, + "keywords": [ + "has", + "hasOwnProperty", + "hasOwn", + "has-own", + "own", + "has", + "property", + "in", + "javascript", + "ecmascript" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/hasOwn/issues" + }, + "homepage": "https://github.com/inspect-js/hasOwn#readme", + "dependencies": { + "function-bind": "^1.1.2" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.15.1", + "@ljharb/eslint-config": "^21.1.0", + "@ljharb/tsconfig": "^0.2.0", + "@types/function-bind": "^1.1.10", + "@types/mock-property": "^1.0.2", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "mock-property": "^1.0.3", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.5", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "test" + ] + } +} diff --git a/node_modules/hasown/tsconfig.json b/node_modules/hasown/tsconfig.json new file mode 100644 index 000000000..0930c5658 --- /dev/null +++ b/node_modules/hasown/tsconfig.json @@ -0,0 +1,6 @@ +{ + "extends": "@ljharb/tsconfig", + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/is-binary-path/index.d.ts b/node_modules/is-binary-path/index.d.ts new file mode 100644 index 000000000..19dcd4327 --- /dev/null +++ b/node_modules/is-binary-path/index.d.ts @@ -0,0 +1,17 @@ +/** +Check if a file path is a binary file. + +@example +``` +import isBinaryPath = require('is-binary-path'); + +isBinaryPath('source/unicorn.png'); +//=> true + +isBinaryPath('source/unicorn.txt'); +//=> false +``` +*/ +declare function isBinaryPath(filePath: string): boolean; + +export = isBinaryPath; diff --git a/node_modules/is-binary-path/index.js b/node_modules/is-binary-path/index.js new file mode 100644 index 000000000..ef7548c83 --- /dev/null +++ b/node_modules/is-binary-path/index.js @@ -0,0 +1,7 @@ +'use strict'; +const path = require('path'); +const binaryExtensions = require('binary-extensions'); + +const extensions = new Set(binaryExtensions); + +module.exports = filePath => extensions.has(path.extname(filePath).slice(1).toLowerCase()); diff --git a/node_modules/is-binary-path/license b/node_modules/is-binary-path/license new file mode 100644 index 000000000..401b1c731 --- /dev/null +++ b/node_modules/is-binary-path/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2019 Sindre Sorhus (https://sindresorhus.com), Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/is-binary-path/package.json b/node_modules/is-binary-path/package.json new file mode 100644 index 000000000..a8d005aed --- /dev/null +++ b/node_modules/is-binary-path/package.json @@ -0,0 +1,40 @@ +{ + "name": "is-binary-path", + "version": "2.1.0", + "description": "Check if a file path is a binary file", + "license": "MIT", + "repository": "sindresorhus/is-binary-path", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "binary", + "extensions", + "extension", + "file", + "path", + "check", + "detect", + "is" + ], + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/is-binary-path/readme.md b/node_modules/is-binary-path/readme.md new file mode 100644 index 000000000..b4ab02519 --- /dev/null +++ b/node_modules/is-binary-path/readme.md @@ -0,0 +1,34 @@ +# is-binary-path [![Build Status](https://travis-ci.org/sindresorhus/is-binary-path.svg?branch=master)](https://travis-ci.org/sindresorhus/is-binary-path) + +> Check if a file path is a binary file + + +## Install + +``` +$ npm install is-binary-path +``` + + +## Usage + +```js +const isBinaryPath = require('is-binary-path'); + +isBinaryPath('source/unicorn.png'); +//=> true + +isBinaryPath('source/unicorn.txt'); +//=> false +``` + + +## Related + +- [binary-extensions](https://github.com/sindresorhus/binary-extensions) - List of binary file extensions +- [is-text-path](https://github.com/sindresorhus/is-text-path) - Check if a filepath is a text file + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com), [Paul Miller](https://paulmillr.com) diff --git a/node_modules/methods/HISTORY.md b/node_modules/methods/HISTORY.md new file mode 100644 index 000000000..c0ecf072d --- /dev/null +++ b/node_modules/methods/HISTORY.md @@ -0,0 +1,29 @@ +1.1.2 / 2016-01-17 +================== + + * perf: enable strict mode + +1.1.1 / 2014-12-30 +================== + + * Improve `browserify` support + +1.1.0 / 2014-07-05 +================== + + * Add `CONNECT` method + +1.0.1 / 2014-06-02 +================== + + * Fix module to work with harmony transform + +1.0.0 / 2014-05-08 +================== + + * Add `PURGE` method + +0.1.0 / 2013-10-28 +================== + + * Add `http.METHODS` support diff --git a/node_modules/methods/LICENSE b/node_modules/methods/LICENSE new file mode 100644 index 000000000..220dc1a24 --- /dev/null +++ b/node_modules/methods/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2013-2014 TJ Holowaychuk +Copyright (c) 2015-2016 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/methods/README.md b/node_modules/methods/README.md new file mode 100644 index 000000000..672a32bfe --- /dev/null +++ b/node_modules/methods/README.md @@ -0,0 +1,51 @@ +# Methods + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +HTTP verbs that Node.js core's HTTP parser supports. + +This module provides an export that is just like `http.METHODS` from Node.js core, +with the following differences: + + * All method names are lower-cased. + * Contains a fallback list of methods for Node.js versions that do not have a + `http.METHODS` export (0.10 and lower). + * Provides the fallback list when using tools like `browserify` without pulling + in the `http` shim module. + +## Install + +```bash +$ npm install methods +``` + +## API + +```js +var methods = require('methods') +``` + +### methods + +This is an array of lower-cased method names that Node.js supports. If Node.js +provides the `http.METHODS` export, then this is the same array lower-cased, +otherwise it is a snapshot of the verbs from Node.js 0.10. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/methods.svg?style=flat +[npm-url]: https://npmjs.org/package/methods +[node-version-image]: https://img.shields.io/node/v/methods.svg?style=flat +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/methods.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/methods +[coveralls-image]: https://img.shields.io/coveralls/jshttp/methods.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/methods?branch=master +[downloads-image]: https://img.shields.io/npm/dm/methods.svg?style=flat +[downloads-url]: https://npmjs.org/package/methods diff --git a/node_modules/methods/index.js b/node_modules/methods/index.js new file mode 100644 index 000000000..667a50bde --- /dev/null +++ b/node_modules/methods/index.js @@ -0,0 +1,69 @@ +/*! + * methods + * Copyright(c) 2013-2014 TJ Holowaychuk + * Copyright(c) 2015-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var http = require('http'); + +/** + * Module exports. + * @public + */ + +module.exports = getCurrentNodeMethods() || getBasicNodeMethods(); + +/** + * Get the current Node.js methods. + * @private + */ + +function getCurrentNodeMethods() { + return http.METHODS && http.METHODS.map(function lowerCaseMethod(method) { + return method.toLowerCase(); + }); +} + +/** + * Get the "basic" Node.js methods, a snapshot from Node.js 0.10. + * @private + */ + +function getBasicNodeMethods() { + return [ + 'get', + 'post', + 'put', + 'head', + 'delete', + 'options', + 'trace', + 'copy', + 'lock', + 'mkcol', + 'move', + 'purge', + 'propfind', + 'proppatch', + 'unlock', + 'report', + 'mkactivity', + 'checkout', + 'merge', + 'm-search', + 'notify', + 'subscribe', + 'unsubscribe', + 'patch', + 'search', + 'connect' + ]; +} diff --git a/node_modules/methods/package.json b/node_modules/methods/package.json new file mode 100644 index 000000000..c4ce6f053 --- /dev/null +++ b/node_modules/methods/package.json @@ -0,0 +1,36 @@ +{ + "name": "methods", + "description": "HTTP methods that node supports", + "version": "1.1.2", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)", + "TJ Holowaychuk (http://tjholowaychuk.com)" + ], + "license": "MIT", + "repository": "jshttp/methods", + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "1.21.5" + }, + "files": [ + "index.js", + "HISTORY.md", + "LICENSE" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "browser": { + "http": false + }, + "keywords": [ + "http", + "methods" + ] +} diff --git a/node_modules/mime/CHANGELOG.md b/node_modules/mime/CHANGELOG.md new file mode 100644 index 000000000..dd254310a --- /dev/null +++ b/node_modules/mime/CHANGELOG.md @@ -0,0 +1,296 @@ +# Changelog + +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. + +## [2.6.0](https://github.com/broofa/mime/compare/v2.5.2...v2.6.0) (2021-11-02) + + +### Features + +* mime-db@1.50.0 ([cef0cc4](https://github.com/broofa/mime/commit/cef0cc484ff6d05ff1e12b54ca3e8b856fbc14d8)) + +### [2.5.2](https://github.com/broofa/mime/compare/v2.5.0...v2.5.2) (2021-02-17) + + +### Bug Fixes + +* update to mime-db@1.46.0, fixes [#253](https://github.com/broofa/mime/issues/253) ([f10e6aa](https://github.com/broofa/mime/commit/f10e6aa62e1356de7e2491d7fb4374c8dac65800)) + +## [2.5.0](https://github.com/broofa/mime/compare/v2.4.7...v2.5.0) (2021-01-16) + + +### Features + +* improved CLI ([#244](https://github.com/broofa/mime/issues/244)) ([c8a8356](https://github.com/broofa/mime/commit/c8a8356e3b27f3ef46b64b89b428fdb547b14d5f)) + +### [2.4.7](https://github.com/broofa/mime/compare/v2.4.6...v2.4.7) (2020-12-16) + + +### Bug Fixes + +* update to latest mime-db ([43b09ef](https://github.com/broofa/mime/commit/43b09eff0233eacc449af2b1f99a19ba9e104a44)) + +### [2.4.6](https://github.com/broofa/mime/compare/v2.4.5...v2.4.6) (2020-05-27) + + +### Bug Fixes + +* add cli.js to package.json files ([#237](https://github.com/broofa/mime/issues/237)) ([6c070bc](https://github.com/broofa/mime/commit/6c070bc298fa12a48e2ed126fbb9de641a1e7ebc)) + +### [2.4.5](https://github.com/broofa/mime/compare/v2.4.4...v2.4.5) (2020-05-01) + + +### Bug Fixes + +* fix [#236](https://github.com/broofa/mime/issues/236) ([7f4ecd0](https://github.com/broofa/mime/commit/7f4ecd0d850ed22c9e3bfda2c11fc74e4dde12a7)) +* update to latest mime-db ([c5cb3f2](https://github.com/broofa/mime/commit/c5cb3f2ab8b07642a066efbde1142af1b90c927b)) + +### [2.4.4](https://github.com/broofa/mime/compare/v2.4.3...v2.4.4) (2019-06-07) + + + +### [2.4.3](https://github.com/broofa/mime/compare/v2.4.2...v2.4.3) (2019-05-15) + + + +### [2.4.2](https://github.com/broofa/mime/compare/v2.4.1...v2.4.2) (2019-04-07) + + +### Bug Fixes + +* don't use arrow function introduced in 2.4.1 ([2e00b5c](https://github.com/broofa/mime/commit/2e00b5c)) + + + +### [2.4.1](https://github.com/broofa/mime/compare/v2.4.0...v2.4.1) (2019-04-03) + + +### Bug Fixes + +* update MDN and mime-db types ([3e567a9](https://github.com/broofa/mime/commit/3e567a9)) + + + +# [2.4.0](https://github.com/broofa/mime/compare/v2.3.1...v2.4.0) (2018-11-26) + + +### Features + +* Bind exported methods ([9d2a7b8](https://github.com/broofa/mime/commit/9d2a7b8)) +* update to mime-db@1.37.0 ([49e6e41](https://github.com/broofa/mime/commit/49e6e41)) + + + +### [2.3.1](https://github.com/broofa/mime/compare/v2.3.0...v2.3.1) (2018-04-11) + + +### Bug Fixes + +* fix [#198](https://github.com/broofa/mime/issues/198) ([25ca180](https://github.com/broofa/mime/commit/25ca180)) + + + +# [2.3.0](https://github.com/broofa/mime/compare/v2.2.2...v2.3.0) (2018-04-11) + + +### Bug Fixes + +* fix [#192](https://github.com/broofa/mime/issues/192) ([5c35df6](https://github.com/broofa/mime/commit/5c35df6)) + + +### Features + +* add travis-ci testing ([d64160f](https://github.com/broofa/mime/commit/d64160f)) + + + +### [2.2.2](https://github.com/broofa/mime/compare/v2.2.1...v2.2.2) (2018-03-30) + + +### Bug Fixes + +* update types files to mime-db@1.32.0 ([85aac16](https://github.com/broofa/mime/commit/85aac16)) + + +### [2.2.1](https://github.com/broofa/mime/compare/v2.2.0...v2.2.1) (2018-03-30) + + +### Bug Fixes + +* Retain type->extension mappings for non-default types. Fixes [#180](https://github.com/broofa/mime/issues/180) ([b5c83fb](https://github.com/broofa/mime/commit/b5c83fb)) + + + +# [2.2.0](https://github.com/broofa/mime/compare/v2.1.0...v2.2.0) (2018-01-04) + + +### Features + +* Retain type->extension mappings for non-default types. Fixes [#180](https://github.com/broofa/mime/issues/180) ([10f82ac](https://github.com/broofa/mime/commit/10f82ac)) + + + +# [2.1.0](https://github.com/broofa/mime/compare/v2.0.5...v2.1.0) (2017-12-22) + + +### Features + +* Upgrade to mime-db@1.32.0. Fixes [#185](https://github.com/broofa/mime/issues/185) ([3f775ba](https://github.com/broofa/mime/commit/3f775ba)) + + + +### [2.0.5](https://github.com/broofa/mime/compare/v2.0.1...v2.0.5) (2017-12-22) + + +### Bug Fixes + +* ES5 support (back to node v0.4) ([f14ccb6](https://github.com/broofa/mime/commit/f14ccb6)) + + + +# Changelog + +### v2.0.4 (24/11/2017) +- [**closed**] Switch to mime-score module for resolving extension contention issues. [#182](https://github.com/broofa/mime/issues/182) +- [**closed**] Update mime-db to 1.31.0 in v1.x branch [#181](https://github.com/broofa/mime/issues/181) + +--- + +## v1.5.0 (22/11/2017) +- [**closed**] need ES5 version ready in npm package [#179](https://github.com/broofa/mime/issues/179) +- [**closed**] mime-db no trace of iWork - pages / numbers / etc. [#178](https://github.com/broofa/mime/issues/178) +- [**closed**] How it works in brownser ? [#176](https://github.com/broofa/mime/issues/176) +- [**closed**] Missing `./Mime` [#175](https://github.com/broofa/mime/issues/175) +- [**closed**] Vulnerable Regular Expression [#167](https://github.com/broofa/mime/issues/167) + +--- + +### v2.0.3 (25/09/2017) +*No changelog for this release.* + +--- + +### v1.4.1 (25/09/2017) +- [**closed**] Issue when bundling with webpack [#172](https://github.com/broofa/mime/issues/172) + +--- + +### v2.0.2 (15/09/2017) +- [**V2**] fs.readFileSync is not a function [#165](https://github.com/broofa/mime/issues/165) +- [**closed**] The extension for video/quicktime should map to .mov, not .qt [#164](https://github.com/broofa/mime/issues/164) +- [**V2**] [v2 Feedback request] Mime class API [#163](https://github.com/broofa/mime/issues/163) +- [**V2**] [v2 Feedback request] Resolving conflicts over extensions [#162](https://github.com/broofa/mime/issues/162) +- [**V2**] Allow callers to load module with official, full, or no defined types. [#161](https://github.com/broofa/mime/issues/161) +- [**V2**] Use "facets" to resolve extension conflicts [#160](https://github.com/broofa/mime/issues/160) +- [**V2**] Remove fs and path dependencies [#152](https://github.com/broofa/mime/issues/152) +- [**V2**] Default content-type should not be application/octet-stream [#139](https://github.com/broofa/mime/issues/139) +- [**V2**] reset mime-types [#124](https://github.com/broofa/mime/issues/124) +- [**V2**] Extensionless paths should return null or false [#113](https://github.com/broofa/mime/issues/113) + +--- + +### v2.0.1 (14/09/2017) +- [**closed**] Changelog for v2.0 does not mention breaking changes [#171](https://github.com/broofa/mime/issues/171) +- [**closed**] MIME breaking with 'class' declaration as it is without 'use strict mode' [#170](https://github.com/broofa/mime/issues/170) + +--- + +## v2.0.0 (12/09/2017) +- [**closed**] woff and woff2 [#168](https://github.com/broofa/mime/issues/168) + +--- + +## v1.4.0 (28/08/2017) +- [**closed**] support for ac3 voc files [#159](https://github.com/broofa/mime/issues/159) +- [**closed**] Help understanding change from application/xml to text/xml [#158](https://github.com/broofa/mime/issues/158) +- [**closed**] no longer able to override mimetype [#157](https://github.com/broofa/mime/issues/157) +- [**closed**] application/vnd.adobe.photoshop [#147](https://github.com/broofa/mime/issues/147) +- [**closed**] Directories should appear as something other than application/octet-stream [#135](https://github.com/broofa/mime/issues/135) +- [**closed**] requested features [#131](https://github.com/broofa/mime/issues/131) +- [**closed**] Make types.json loading optional? [#129](https://github.com/broofa/mime/issues/129) +- [**closed**] Cannot find module './types.json' [#120](https://github.com/broofa/mime/issues/120) +- [**V2**] .wav files show up as "audio/x-wav" instead of "audio/x-wave" [#118](https://github.com/broofa/mime/issues/118) +- [**closed**] Don't be a pain in the ass for node community [#108](https://github.com/broofa/mime/issues/108) +- [**closed**] don't make default_type global [#78](https://github.com/broofa/mime/issues/78) +- [**closed**] mime.extension() fails if the content-type is parameterized [#74](https://github.com/broofa/mime/issues/74) + +--- + +### v1.3.6 (11/05/2017) +- [**closed**] .md should be text/markdown as of March 2016 [#154](https://github.com/broofa/mime/issues/154) +- [**closed**] Error while installing mime [#153](https://github.com/broofa/mime/issues/153) +- [**closed**] application/manifest+json [#149](https://github.com/broofa/mime/issues/149) +- [**closed**] Dynamic adaptive streaming over HTTP (DASH) file extension typo [#141](https://github.com/broofa/mime/issues/141) +- [**closed**] charsets image/png undefined [#140](https://github.com/broofa/mime/issues/140) +- [**closed**] Mime-db dependency out of date [#130](https://github.com/broofa/mime/issues/130) +- [**closed**] how to support plist? [#126](https://github.com/broofa/mime/issues/126) +- [**closed**] how does .types file format look like? [#123](https://github.com/broofa/mime/issues/123) +- [**closed**] Feature: support for expanding MIME patterns [#121](https://github.com/broofa/mime/issues/121) +- [**closed**] DEBUG_MIME doesn't work [#117](https://github.com/broofa/mime/issues/117) + +--- + +### v1.3.4 (06/02/2015) +*No changelog for this release.* + +--- + +### v1.3.3 (06/02/2015) +*No changelog for this release.* + +--- + +### v1.3.1 (05/02/2015) +- [**closed**] Consider adding support for Handlebars .hbs file ending [#111](https://github.com/broofa/mime/issues/111) +- [**closed**] Consider adding support for hjson. [#110](https://github.com/broofa/mime/issues/110) +- [**closed**] Add mime type for Opus audio files [#94](https://github.com/broofa/mime/issues/94) +- [**closed**] Consider making the `Requesting New Types` information more visible [#77](https://github.com/broofa/mime/issues/77) + +--- + +## v1.3.0 (05/02/2015) +- [**closed**] Add common name? [#114](https://github.com/broofa/mime/issues/114) +- [**closed**] application/x-yaml [#104](https://github.com/broofa/mime/issues/104) +- [**closed**] Add mime type for WOFF file format 2.0 [#102](https://github.com/broofa/mime/issues/102) +- [**closed**] application/x-msi for .msi [#99](https://github.com/broofa/mime/issues/99) +- [**closed**] Add mimetype for gettext translation files [#98](https://github.com/broofa/mime/issues/98) +- [**closed**] collaborators [#88](https://github.com/broofa/mime/issues/88) +- [**closed**] getting errot in installation of mime module...any1 can help? [#87](https://github.com/broofa/mime/issues/87) +- [**closed**] should application/json's charset be utf8? [#86](https://github.com/broofa/mime/issues/86) +- [**closed**] Add "license" and "licenses" to package.json [#81](https://github.com/broofa/mime/issues/81) +- [**closed**] lookup with extension-less file on Windows returns wrong type [#68](https://github.com/broofa/mime/issues/68) + +--- + +### v1.2.11 (15/08/2013) +- [**closed**] Update mime.types [#65](https://github.com/broofa/mime/issues/65) +- [**closed**] Publish a new version [#63](https://github.com/broofa/mime/issues/63) +- [**closed**] README should state upfront that "application/octet-stream" is default for unknown extension [#55](https://github.com/broofa/mime/issues/55) +- [**closed**] Suggested improvement to the charset API [#52](https://github.com/broofa/mime/issues/52) + +--- + +### v1.2.10 (25/07/2013) +- [**closed**] Mime type for woff files should be application/font-woff and not application/x-font-woff [#62](https://github.com/broofa/mime/issues/62) +- [**closed**] node.types in conflict with mime.types [#51](https://github.com/broofa/mime/issues/51) + +--- + +### v1.2.9 (17/01/2013) +- [**closed**] Please update "mime" NPM [#49](https://github.com/broofa/mime/issues/49) +- [**closed**] Please add semicolon [#46](https://github.com/broofa/mime/issues/46) +- [**closed**] parse full mime types [#43](https://github.com/broofa/mime/issues/43) + +--- + +### v1.2.8 (10/01/2013) +- [**closed**] /js directory mime is application/javascript. Is it correct? [#47](https://github.com/broofa/mime/issues/47) +- [**closed**] Add mime types for lua code. [#45](https://github.com/broofa/mime/issues/45) + +--- + +### v1.2.7 (19/10/2012) +- [**closed**] cannot install 1.2.7 via npm [#41](https://github.com/broofa/mime/issues/41) +- [**closed**] Transfer ownership to @broofa [#36](https://github.com/broofa/mime/issues/36) +- [**closed**] it's wrong to set charset to UTF-8 for text [#30](https://github.com/broofa/mime/issues/30) +- [**closed**] Allow multiple instances of MIME types container [#27](https://github.com/broofa/mime/issues/27) diff --git a/node_modules/mime/LICENSE b/node_modules/mime/LICENSE new file mode 100644 index 000000000..d3f46f7e1 --- /dev/null +++ b/node_modules/mime/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2010 Benjamin Thomas, Robert Kieffer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/mime/Mime.js b/node_modules/mime/Mime.js new file mode 100644 index 000000000..969a66e41 --- /dev/null +++ b/node_modules/mime/Mime.js @@ -0,0 +1,97 @@ +'use strict'; + +/** + * @param typeMap [Object] Map of MIME type -> Array[extensions] + * @param ... + */ +function Mime() { + this._types = Object.create(null); + this._extensions = Object.create(null); + + for (let i = 0; i < arguments.length; i++) { + this.define(arguments[i]); + } + + this.define = this.define.bind(this); + this.getType = this.getType.bind(this); + this.getExtension = this.getExtension.bind(this); +} + +/** + * Define mimetype -> extension mappings. Each key is a mime-type that maps + * to an array of extensions associated with the type. The first extension is + * used as the default extension for the type. + * + * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); + * + * If a type declares an extension that has already been defined, an error will + * be thrown. To suppress this error and force the extension to be associated + * with the new type, pass `force`=true. Alternatively, you may prefix the + * extension with "*" to map the type to extension, without mapping the + * extension to the type. + * + * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']}); + * + * + * @param map (Object) type definitions + * @param force (Boolean) if true, force overriding of existing definitions + */ +Mime.prototype.define = function(typeMap, force) { + for (let type in typeMap) { + let extensions = typeMap[type].map(function(t) { + return t.toLowerCase(); + }); + type = type.toLowerCase(); + + for (let i = 0; i < extensions.length; i++) { + const ext = extensions[i]; + + // '*' prefix = not the preferred type for this extension. So fixup the + // extension, and skip it. + if (ext[0] === '*') { + continue; + } + + if (!force && (ext in this._types)) { + throw new Error( + 'Attempt to change mapping for "' + ext + + '" extension from "' + this._types[ext] + '" to "' + type + + '". Pass `force=true` to allow this, otherwise remove "' + ext + + '" from the list of extensions for "' + type + '".' + ); + } + + this._types[ext] = type; + } + + // Use first extension as default + if (force || !this._extensions[type]) { + const ext = extensions[0]; + this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1); + } + } +}; + +/** + * Lookup a mime type based on extension + */ +Mime.prototype.getType = function(path) { + path = String(path); + let last = path.replace(/^.*[/\\]/, '').toLowerCase(); + let ext = last.replace(/^.*\./, '').toLowerCase(); + + let hasPath = last.length < path.length; + let hasDot = ext.length < last.length - 1; + + return (hasDot || !hasPath) && this._types[ext] || null; +}; + +/** + * Return file extension associated with a mime type + */ +Mime.prototype.getExtension = function(type) { + type = /^\s*([^;\s]*)/.test(type) && RegExp.$1; + return type && this._extensions[type.toLowerCase()] || null; +}; + +module.exports = Mime; diff --git a/node_modules/mime/README.md b/node_modules/mime/README.md new file mode 100644 index 000000000..b08316f24 --- /dev/null +++ b/node_modules/mime/README.md @@ -0,0 +1,187 @@ + +# Mime + +A comprehensive, compact MIME type module. + +[![Build Status](https://travis-ci.org/broofa/mime.svg?branch=master)](https://travis-ci.org/broofa/mime) + +## Version 2 Notes + +Version 2 is a breaking change from 1.x as the semver implies. Specifically: + +* `lookup()` renamed to `getType()` +* `extension()` renamed to `getExtension()` +* `charset()` and `load()` methods have been removed + +If you prefer the legacy version of this module please `npm install mime@^1`. Version 1 docs may be found [here](https://github.com/broofa/mime/tree/v1.4.0). + +## Install + +### NPM +``` +npm install mime +``` + +### Browser + +It is recommended that you use a bundler such as +[webpack](https://webpack.github.io/) or [browserify](http://browserify.org/) to +package your code. However, browser-ready versions are available via wzrd.in. +E.g. For the full version: + + + + +Or, for the `mime/lite` version: + + + + +## Quick Start + +For the full version (800+ MIME types, 1,000+ extensions): + +```javascript +const mime = require('mime'); + +mime.getType('txt'); // ⇨ 'text/plain' +mime.getExtension('text/plain'); // ⇨ 'txt' +``` + +See [Mime API](#mime-api) below for API details. + +## Lite Version + +There is also a "lite" version of this module that omits vendor-specific +(`*/vnd.*`) and experimental (`*/x-*`) types. It weighs in at ~2.5KB, compared +to 8KB for the full version. To load the lite version: + +```javascript +const mime = require('mime/lite'); +``` + +## Mime .vs. mime-types .vs. mime-db modules + +For those of you wondering about the difference between these [popular] NPM modules, +here's a brief rundown ... + +[`mime-db`](https://github.com/jshttp/mime-db) is "the source of +truth" for MIME type information. It is not an API. Rather, it is a canonical +dataset of mime type definitions pulled from IANA, Apache, NGINX, and custom mappings +submitted by the Node.js community. + +[`mime-types`](https://github.com/jshttp/mime-types) is a thin +wrapper around mime-db that provides an API drop-in compatible(ish) with `mime @ < v1.3.6` API. + +`mime` is, as of v2, a self-contained module bundled with a pre-optimized version +of the `mime-db` dataset. It provides a simplified API with the following characteristics: + +* Intelligently resolved type conflicts (See [mime-score](https://github.com/broofa/mime-score) for details) +* Method naming consistent with industry best-practices +* Compact footprint. E.g. The minified+compressed sizes of the various modules: + +Module | Size +--- | --- +`mime-db` | 18 KB +`mime-types` | same as mime-db +`mime` | 8 KB +`mime/lite` | 2 KB + +## Mime API + +Both `require('mime')` and `require('mime/lite')` return instances of the MIME +class, documented below. + +Note: Inputs to this API are case-insensitive. Outputs (returned values) will +be lowercase. + +### new Mime(typeMap, ... more maps) + +Most users of this module will not need to create Mime instances directly. +However if you would like to create custom mappings, you may do so as follows +... + +```javascript +// Require Mime class +const Mime = require('mime/Mime'); + +// Define mime type -> extensions map +const typeMap = { + 'text/abc': ['abc', 'alpha', 'bet'], + 'text/def': ['leppard'] +}; + +// Create and use Mime instance +const myMime = new Mime(typeMap); +myMime.getType('abc'); // ⇨ 'text/abc' +myMime.getExtension('text/def'); // ⇨ 'leppard' +``` + +If more than one map argument is provided, each map is `define()`ed (see below), in order. + +### mime.getType(pathOrExtension) + +Get mime type for the given path or extension. E.g. + +```javascript +mime.getType('js'); // ⇨ 'application/javascript' +mime.getType('json'); // ⇨ 'application/json' + +mime.getType('txt'); // ⇨ 'text/plain' +mime.getType('dir/text.txt'); // ⇨ 'text/plain' +mime.getType('dir\\text.txt'); // ⇨ 'text/plain' +mime.getType('.text.txt'); // ⇨ 'text/plain' +mime.getType('.txt'); // ⇨ 'text/plain' +``` + +`null` is returned in cases where an extension is not detected or recognized + +```javascript +mime.getType('foo/txt'); // ⇨ null +mime.getType('bogus_type'); // ⇨ null +``` + +### mime.getExtension(type) +Get extension for the given mime type. Charset options (often included in +Content-Type headers) are ignored. + +```javascript +mime.getExtension('text/plain'); // ⇨ 'txt' +mime.getExtension('application/json'); // ⇨ 'json' +mime.getExtension('text/html; charset=utf8'); // ⇨ 'html' +``` + +### mime.define(typeMap[, force = false]) + +Define [more] type mappings. + +`typeMap` is a map of type -> extensions, as documented in `new Mime`, above. + +By default this method will throw an error if you try to map a type to an +extension that is already assigned to another type. Passing `true` for the +`force` argument will suppress this behavior (overriding any previous mapping). + +```javascript +mime.define({'text/x-abc': ['abc', 'abcd']}); + +mime.getType('abcd'); // ⇨ 'text/x-abc' +mime.getExtension('text/x-abc') // ⇨ 'abc' +``` + +## Command Line + + mime [path_or_extension] + +E.g. + + > mime scripts/jquery.js + application/javascript + +---- +Markdown generated from [src/README_js.md](src/README_js.md) by [![RunMD Logo](http://i.imgur.com/h0FVyzU.png)](https://github.com/broofa/runmd) \ No newline at end of file diff --git a/node_modules/mime/cli.js b/node_modules/mime/cli.js new file mode 100755 index 000000000..ab70a49c4 --- /dev/null +++ b/node_modules/mime/cli.js @@ -0,0 +1,46 @@ +#!/usr/bin/env node + +'use strict'; + +process.title = 'mime'; +let mime = require('.'); +let pkg = require('./package.json'); +let args = process.argv.splice(2); + +if (args.includes('--version') || args.includes('-v') || args.includes('--v')) { + console.log(pkg.version); + process.exit(0); +} else if (args.includes('--name') || args.includes('-n') || args.includes('--n')) { + console.log(pkg.name); + process.exit(0); +} else if (args.includes('--help') || args.includes('-h') || args.includes('--h')) { + console.log(pkg.name + ' - ' + pkg.description + '\n'); + console.log(`Usage: + + mime [flags] [path_or_extension] + + Flags: + --help, -h Show this message + --version, -v Display the version + --name, -n Print the name of the program + + Note: the command will exit after it executes if a command is specified + The path_or_extension is the path to the file or the extension of the file. + + Examples: + mime --help + mime --version + mime --name + mime -v + mime src/log.js + mime new.py + mime foo.sh + `); + process.exit(0); +} + +let file = args[0]; +let type = mime.getType(file); + +process.stdout.write(type + '\n'); + diff --git a/node_modules/mime/index.js b/node_modules/mime/index.js new file mode 100644 index 000000000..fadcf8d63 --- /dev/null +++ b/node_modules/mime/index.js @@ -0,0 +1,4 @@ +'use strict'; + +let Mime = require('./Mime'); +module.exports = new Mime(require('./types/standard'), require('./types/other')); diff --git a/node_modules/mime/lite.js b/node_modules/mime/lite.js new file mode 100644 index 000000000..835cffb30 --- /dev/null +++ b/node_modules/mime/lite.js @@ -0,0 +1,4 @@ +'use strict'; + +let Mime = require('./Mime'); +module.exports = new Mime(require('./types/standard')); diff --git a/node_modules/mime/package.json b/node_modules/mime/package.json new file mode 100644 index 000000000..df7f369bd --- /dev/null +++ b/node_modules/mime/package.json @@ -0,0 +1,52 @@ +{ + "author": { + "name": "Robert Kieffer", + "url": "http://github.com/broofa", + "email": "robert@broofa.com" + }, + "engines": { + "node": ">=4.0.0" + }, + "bin": { + "mime": "cli.js" + }, + "contributors": [], + "description": "A comprehensive library for mime-type mapping", + "license": "MIT", + "dependencies": {}, + "devDependencies": { + "benchmark": "*", + "chalk": "4.1.2", + "eslint": "8.1.0", + "mime-db": "1.50.0", + "mime-score": "1.2.0", + "mime-types": "2.1.33", + "mocha": "9.1.3", + "runmd": "*", + "standard-version": "9.3.2" + }, + "files": [ + "index.js", + "lite.js", + "Mime.js", + "cli.js", + "/types" + ], + "scripts": { + "prepare": "node src/build.js && runmd --output README.md src/README_js.md", + "release": "standard-version", + "benchmark": "node src/benchmark.js", + "md": "runmd --watch --output README.md src/README_js.md", + "test": "mocha src/test.js" + }, + "keywords": [ + "util", + "mime" + ], + "name": "mime", + "repository": { + "url": "https://github.com/broofa/mime", + "type": "git" + }, + "version": "2.6.0" +} diff --git a/node_modules/mime/types/other.js b/node_modules/mime/types/other.js new file mode 100644 index 000000000..bb6a03533 --- /dev/null +++ b/node_modules/mime/types/other.js @@ -0,0 +1 @@ +module.exports = {"application/prs.cww":["cww"],"application/vnd.1000minds.decision-model+xml":["1km"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.keynote":["key"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.balsamiq.bmml+xml":["bmml"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.citationstyles.style+xml":["csl"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dbf":["dbf"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mapbox-vector-tile":["mvt"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["*stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.ac+xml":["*ac"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openblox.game+xml":["obgx"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openstreetmap.data+xml":["osm"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.rar":["rar"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.software602.filler.form+xml":["fo"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.syncml.dmddf+xml":["ddf"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["*dmg"],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":["*bdoc"],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["*deb","udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["*iso"],"application/x-iwork-keynote-sffkey":["*key"],"application/x-iwork-numbers-sffnumbers":["*numbers"],"application/x-iwork-pages-sffpages":["*pages"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-keepass2":["kdbx"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":["*exe"],"application/x-msdownload":["*exe","*dll","com","bat","*msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["*wmf","*wmz","*emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":["*prc","*pdb"],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["*rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["*obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["*xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/x-aac":["aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":["*m4a"],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":["*ra"],"audio/x-wav":["*wav"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"image/prs.btif":["btif"],"image/prs.pti":["pti"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.airzip.accelerator.azv":["azv"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["*sub"],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.microsoft.icon":["ico"],"image/vnd.ms-dds":["dds"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.pco.b16":["b16"],"image/vnd.tencent.tap":["tap"],"image/vnd.valve.source.texture":["vtf"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/vnd.zbrush.pcx":["pcx"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["*ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":["*bmp"],"image/x-pcx":["*pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/vnd.wfa.wsc":["wsc"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.opengex":["ogex"],"model/vnd.parasolid.transmit.binary":["x_b"],"model/vnd.parasolid.transmit.text":["x_t"],"model/vnd.sap.vds":["vds"],"model/vnd.usdz+zip":["usdz"],"model/vnd.valve.source.compiled-map":["bsp"],"model/vnd.vtu":["vtu"],"text/prs.lines.tag":["dsc"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":["*org"],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]}; \ No newline at end of file diff --git a/node_modules/mime/types/standard.js b/node_modules/mime/types/standard.js new file mode 100644 index 000000000..5ee9937eb --- /dev/null +++ b/node_modules/mime/types/standard.js @@ -0,0 +1 @@ +module.exports = {"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["es","ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]}; \ No newline at end of file diff --git a/node_modules/minimatch/README.md b/node_modules/minimatch/README.md index ad72b8133..33ede1d6e 100644 --- a/node_modules/minimatch/README.md +++ b/node_modules/minimatch/README.md @@ -2,7 +2,7 @@ A minimal matching utility. -[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.svg)](http://travis-ci.org/isaacs/minimatch) +[![Build Status](https://travis-ci.org/isaacs/minimatch.svg?branch=master)](http://travis-ci.org/isaacs/minimatch) This is the matching library used internally by npm. @@ -171,6 +171,27 @@ Suppress the behavior of treating a leading `!` character as negation. Returns from negate expressions the same as if they were not negated. (Ie, true on a hit, false on a miss.) +### partial + +Compare a partial path to a pattern. As long as the parts of the path that +are present are not contradicted by the pattern, it will be treated as a +match. This is useful in applications where you're walking through a +folder structure, and don't yet have the full path, but want to ensure that +you do not walk down paths that can never be a match. + +For example, + +```js +minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d +minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d +minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a +``` + +### allowWindowsEscape + +Windows path separator `\` is by default converted to `/`, which +prohibits the usage of `\` as a escape character. This flag skips that +behavior and allows using the escape character. ## Comparisons to other fnmatch/glob implementations diff --git a/node_modules/minimatch/minimatch.js b/node_modules/minimatch/minimatch.js index 5b5f8cf44..fda45ade7 100644 --- a/node_modules/minimatch/minimatch.js +++ b/node_modules/minimatch/minimatch.js @@ -1,10 +1,10 @@ module.exports = minimatch minimatch.Minimatch = Minimatch -var path = { sep: '/' } -try { - path = require('path') -} catch (er) {} +var path = (function () { try { return require('path') } catch (e) {}}()) || { + sep: '/' +} +minimatch.sep = path.sep var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} var expand = require('brace-expansion') @@ -56,43 +56,64 @@ function filter (pattern, options) { } function ext (a, b) { - a = a || {} b = b || {} var t = {} - Object.keys(b).forEach(function (k) { - t[k] = b[k] - }) Object.keys(a).forEach(function (k) { t[k] = a[k] }) + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) return t } minimatch.defaults = function (def) { - if (!def || !Object.keys(def).length) return minimatch + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return minimatch + } var orig = minimatch var m = function minimatch (p, pattern, options) { - return orig.minimatch(p, pattern, ext(def, options)) + return orig(p, pattern, ext(def, options)) } m.Minimatch = function Minimatch (pattern, options) { return new orig.Minimatch(pattern, ext(def, options)) } + m.Minimatch.defaults = function defaults (options) { + return orig.defaults(ext(def, options)).Minimatch + } + + m.filter = function filter (pattern, options) { + return orig.filter(pattern, ext(def, options)) + } + + m.defaults = function defaults (options) { + return orig.defaults(ext(def, options)) + } + + m.makeRe = function makeRe (pattern, options) { + return orig.makeRe(pattern, ext(def, options)) + } + + m.braceExpand = function braceExpand (pattern, options) { + return orig.braceExpand(pattern, ext(def, options)) + } + + m.match = function (list, pattern, options) { + return orig.match(list, pattern, ext(def, options)) + } return m } Minimatch.defaults = function (def) { - if (!def || !Object.keys(def).length) return Minimatch return minimatch.defaults(def).Minimatch } function minimatch (p, pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('glob pattern string required') - } + assertValidPattern(pattern) if (!options) options = {} @@ -101,9 +122,6 @@ function minimatch (p, pattern, options) { return false } - // "" only matches "" - if (pattern.trim() === '') return p === '' - return new Minimatch(pattern, options).match(p) } @@ -112,15 +130,14 @@ function Minimatch (pattern, options) { return new Minimatch(pattern, options) } - if (typeof pattern !== 'string') { - throw new TypeError('glob pattern string required') - } + assertValidPattern(pattern) if (!options) options = {} + pattern = pattern.trim() // windows support: need to use /, not \ - if (path.sep !== '/') { + if (!options.allowWindowsEscape && path.sep !== '/') { pattern = pattern.split(path.sep).join('/') } @@ -131,6 +148,7 @@ function Minimatch (pattern, options) { this.negate = false this.comment = false this.empty = false + this.partial = !!options.partial // make the set of regexps etc. this.make() @@ -140,9 +158,6 @@ Minimatch.prototype.debug = function () {} Minimatch.prototype.make = make function make () { - // don't do it more than once. - if (this._made) return - var pattern = this.pattern var options = this.options @@ -162,7 +177,7 @@ function make () { // step 2: expand braces var set = this.globSet = this.braceExpand() - if (options.debug) this.debug = console.error + if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) } this.debug(this.pattern, set) @@ -242,12 +257,11 @@ function braceExpand (pattern, options) { pattern = typeof pattern === 'undefined' ? this.pattern : pattern - if (typeof pattern === 'undefined') { - throw new TypeError('undefined pattern') - } + assertValidPattern(pattern) - if (options.nobrace || - !pattern.match(/\{.*\}/)) { + // Thanks to Yeting Li for + // improving this regexp to avoid a ReDOS vulnerability. + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { // shortcut. no need to expand. return [pattern] } @@ -255,6 +269,17 @@ function braceExpand (pattern, options) { return expand(pattern) } +var MAX_PATTERN_LENGTH = 1024 * 64 +var assertValidPattern = function (pattern) { + if (typeof pattern !== 'string') { + throw new TypeError('invalid pattern') + } + + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long') + } +} + // parse a component of the expanded set. // At this point, no pattern may contain "/" in it // so we're going to return a 2d array, where each entry is the full @@ -269,14 +294,17 @@ function braceExpand (pattern, options) { Minimatch.prototype.parse = parse var SUBPARSE = {} function parse (pattern, isSub) { - if (pattern.length > 1024 * 64) { - throw new TypeError('pattern is too long') - } + assertValidPattern(pattern) var options = this.options // shortcuts - if (!options.noglobstar && pattern === '**') return GLOBSTAR + if (pattern === '**') { + if (!options.noglobstar) + return GLOBSTAR + else + pattern = '*' + } if (pattern === '') return '' var re = '' @@ -332,10 +360,12 @@ function parse (pattern, isSub) { } switch (c) { - case '/': + /* istanbul ignore next */ + case '/': { // completely not allowed, even escaped. // Should already be path-split by now. return false + } case '\\': clearStateChar() @@ -454,25 +484,23 @@ function parse (pattern, isSub) { // handle the case where we left a class open. // "[z-a]" is valid, equivalent to "\[z-a\]" - if (inClass) { - // split where the last [ was, make sure we don't have - // an invalid re. if so, re-walk the contents of the - // would-be class to re-translate any characters that - // were passed through as-is - // TODO: It would probably be faster to determine this - // without a try/catch and a new RegExp, but it's tricky - // to do safely. For now, this is safe and works. - var cs = pattern.substring(classStart + 1, i) - try { - RegExp('[' + cs + ']') - } catch (er) { - // not a valid class! - var sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' - hasMagic = hasMagic || sp[1] - inClass = false - continue - } + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue } // finish up the class. @@ -556,9 +584,7 @@ function parse (pattern, isSub) { // something that could conceivably capture a dot var addPatternStart = false switch (re.charAt(0)) { - case '.': - case '[': - case '(': addPatternStart = true + case '[': case '.': case '(': addPatternStart = true } // Hack to work around lack of negative lookbehind in JS @@ -620,7 +646,7 @@ function parse (pattern, isSub) { var flags = options.nocase ? 'i' : '' try { var regExp = new RegExp('^' + re + '$', flags) - } catch (er) { + } catch (er) /* istanbul ignore next - should be impossible */ { // If it was an invalid regular expression, then it can't match // anything. This trick looks for a character after the end of // the string, which is of course impossible, except in multi-line @@ -678,7 +704,7 @@ function makeRe () { try { this.regexp = new RegExp(re, flags) - } catch (ex) { + } catch (ex) /* istanbul ignore next - should be impossible */ { this.regexp = false } return this.regexp @@ -696,8 +722,8 @@ minimatch.match = function (list, pattern, options) { return list } -Minimatch.prototype.match = match -function match (f, partial) { +Minimatch.prototype.match = function match (f, partial) { + if (typeof partial === 'undefined') partial = this.partial this.debug('match', f, this.pattern) // short-circuit in the case of busted things. // comments, etc. @@ -779,6 +805,7 @@ Minimatch.prototype.matchOne = function (file, pattern, partial) { // should be impossible. // some invalid regexp stuff in the set. + /* istanbul ignore if */ if (p === false) return false if (p === GLOBSTAR) { @@ -852,6 +879,7 @@ Minimatch.prototype.matchOne = function (file, pattern, partial) { // no match was found. // However, in partial mode, we can't say this is necessarily over. // If there's more *pattern* left, then + /* istanbul ignore if */ if (partial) { // ran out of file this.debug('\n>>> no match, partial?', file, fr, pattern, pr) @@ -865,11 +893,7 @@ Minimatch.prototype.matchOne = function (file, pattern, partial) { // patterns with magic have been turned into regexps. var hit if (typeof p === 'string') { - if (options.nocase) { - hit = f.toLowerCase() === p.toLowerCase() - } else { - hit = f === p - } + hit = f === p this.debug('string match', p, f, hit) } else { hit = f.match(p) @@ -900,16 +924,16 @@ Minimatch.prototype.matchOne = function (file, pattern, partial) { // this is ok if we're doing the match as part of // a glob fs traversal. return partial - } else if (pi === pl) { + } else /* istanbul ignore else */ if (pi === pl) { // ran out of pattern, still have file left. // this is only acceptable if we're on the very last // empty segment of a file with a trailing slash. // a/* should match a/b/ - var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') - return emptyFileEnd + return (fi === fl - 1) && (file[fi] === '') } // should be unreachable. + /* istanbul ignore next */ throw new Error('wtf?') } diff --git a/node_modules/minimatch/package.json b/node_modules/minimatch/package.json index 58d58b3e2..566efdfe4 100644 --- a/node_modules/minimatch/package.json +++ b/node_modules/minimatch/package.json @@ -1,64 +1,33 @@ { - "_from": "minimatch@^3.0.4", - "_id": "minimatch@3.0.4", - "_inBundle": false, - "_integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", - "_location": "/minimatch", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "minimatch@^3.0.4", - "name": "minimatch", - "escapedName": "minimatch", - "rawSpec": "^3.0.4", - "saveSpec": null, - "fetchSpec": "^3.0.4" + "author": "Isaac Z. Schlueter (http://blog.izs.me)", + "name": "minimatch", + "description": "a glob matcher in javascript", + "version": "3.1.2", + "publishConfig": { + "tag": "v3-legacy" }, - "_requiredBy": [ - "/glob", - "/test-exclude" - ], - "_resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", - "_shasum": "5166e286457f03306064be5497e8dbb0c3d32083", - "_spec": "minimatch@^3.0.4", - "_where": "/Users/hcliff/src/github-asana-action/node_modules/test-exclude", - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me" + "repository": { + "type": "git", + "url": "git://github.com/isaacs/minimatch.git" + }, + "main": "minimatch.js", + "scripts": { + "test": "tap", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --all; git push origin --tags" }, - "bugs": { - "url": "https://github.com/isaacs/minimatch/issues" + "engines": { + "node": "*" }, - "bundleDependencies": false, "dependencies": { "brace-expansion": "^1.1.7" }, - "deprecated": false, - "description": "a glob matcher in javascript", "devDependencies": { - "tap": "^10.3.2" - }, - "engines": { - "node": "*" + "tap": "^15.1.6" }, + "license": "ISC", "files": [ "minimatch.js" - ], - "homepage": "https://github.com/isaacs/minimatch#readme", - "license": "ISC", - "main": "minimatch.js", - "name": "minimatch", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/minimatch.git" - }, - "scripts": { - "postpublish": "git push origin --all; git push origin --tags", - "postversion": "npm publish", - "preversion": "npm test", - "test": "tap test/*.js --cov" - }, - "version": "3.0.4" + ] } diff --git a/node_modules/object-inspect/.eslintrc b/node_modules/object-inspect/.eslintrc new file mode 100644 index 000000000..21f903923 --- /dev/null +++ b/node_modules/object-inspect/.eslintrc @@ -0,0 +1,53 @@ +{ + "root": true, + "extends": "@ljharb", + "rules": { + "complexity": 0, + "func-style": [2, "declaration"], + "indent": [2, 4], + "max-lines": 1, + "max-lines-per-function": 1, + "max-params": [2, 4], + "max-statements": 0, + "max-statements-per-line": [2, { "max": 2 }], + "no-magic-numbers": 0, + "no-param-reassign": 1, + "strict": 0, // TODO + }, + "overrides": [ + { + "files": ["test/**", "test-*", "example/**"], + "extends": "@ljharb/eslint-config/tests", + "rules": { + "id-length": 0, + }, + }, + { + "files": ["example/**"], + "rules": { + "no-console": 0, + }, + }, + { + "files": ["test/browser/**"], + "env": { + "browser": true, + }, + }, + { + "files": ["test/bigint*"], + "rules": { + "new-cap": [2, { "capIsNewExceptions": ["BigInt"] }], + }, + }, + { + "files": "index.js", + "globals": { + "HTMLElement": false, + }, + "rules": { + "no-use-before-define": 1, + }, + }, + ], +} diff --git a/node_modules/object-inspect/.github/FUNDING.yml b/node_modules/object-inspect/.github/FUNDING.yml new file mode 100644 index 000000000..730276bd1 --- /dev/null +++ b/node_modules/object-inspect/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/object-inspect +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/object-inspect/.nycrc b/node_modules/object-inspect/.nycrc new file mode 100644 index 000000000..58a5db783 --- /dev/null +++ b/node_modules/object-inspect/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "instrumentation": false, + "sourceMap": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "example", + "test", + "test-core-js.js" + ] +} diff --git a/node_modules/object-inspect/CHANGELOG.md b/node_modules/object-inspect/CHANGELOG.md new file mode 100644 index 000000000..c5772b4c0 --- /dev/null +++ b/node_modules/object-inspect/CHANGELOG.md @@ -0,0 +1,389 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.13.1](https://github.com/inspect-js/object-inspect/compare/v1.13.0...v1.13.1) - 2023-10-19 + +### Commits + +- [Fix] in IE 8, global can !== window despite them being prototypes of each other [`30d0859`](https://github.com/inspect-js/object-inspect/commit/30d0859dc4606cf75c2410edcd5d5c6355f8d372) + +## [v1.13.0](https://github.com/inspect-js/object-inspect/compare/v1.12.3...v1.13.0) - 2023-10-14 + +### Commits + +- [New] add special handling for the global object [`431bab2`](https://github.com/inspect-js/object-inspect/commit/431bab21a490ee51d35395966a504501e8c685da) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`fd4f619`](https://github.com/inspect-js/object-inspect/commit/fd4f6193562b4b0e95dcf5c0201b4e8cbbc4f58d) +- [Dev Deps] update `mock-property`, `tape` [`b453f6c`](https://github.com/inspect-js/object-inspect/commit/b453f6ceeebf8a1b738a1029754092e0367a4134) +- [Dev Deps] update `error-cause` [`e8ffc57`](https://github.com/inspect-js/object-inspect/commit/e8ffc577d73b92bb6a4b00c44f14e3319e374888) +- [Dev Deps] update `tape` [`054b8b9`](https://github.com/inspect-js/object-inspect/commit/054b8b9b98633284cf989e582450ebfbbe53503c) +- [Dev Deps] temporarily remove `aud` due to breaking change in transitive deps [`2476845`](https://github.com/inspect-js/object-inspect/commit/2476845e0678dd290c541c81cd3dec8420782c52) +- [Dev Deps] pin `glob`, since v10.3.8+ requires a broken `jackspeak` [`383fa5e`](https://github.com/inspect-js/object-inspect/commit/383fa5eebc0afd705cc778a4b49d8e26452e49a8) +- [Dev Deps] pin `jackspeak` since 2.1.2+ depends on npm aliases, which kill the install process in npm < 6 [`68c244c`](https://github.com/inspect-js/object-inspect/commit/68c244c5174cdd877e5dcb8ee90aa3f44b2f25be) + +## [v1.12.3](https://github.com/inspect-js/object-inspect/compare/v1.12.2...v1.12.3) - 2023-01-12 + +### Commits + +- [Fix] in eg FF 24, collections lack forEach [`75fc226`](https://github.com/inspect-js/object-inspect/commit/75fc22673c82d45f28322b1946bb0eb41b672b7f) +- [actions] update rebase action to use reusable workflow [`250a277`](https://github.com/inspect-js/object-inspect/commit/250a277a095e9dacc029ab8454dcfc15de549dcd) +- [Dev Deps] update `aud`, `es-value-fixtures`, `tape` [`66a19b3`](https://github.com/inspect-js/object-inspect/commit/66a19b3209ccc3c5ef4b34c3cb0160e65d1ce9d5) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `error-cause` [`c43d332`](https://github.com/inspect-js/object-inspect/commit/c43d3324b48384a16fd3dc444e5fc589d785bef3) +- [Tests] add `@pkgjs/support` to `postlint` [`e2618d2`](https://github.com/inspect-js/object-inspect/commit/e2618d22a7a3fa361b6629b53c1752fddc9c4d80) + +## [v1.12.2](https://github.com/inspect-js/object-inspect/compare/v1.12.1...v1.12.2) - 2022-05-26 + +### Commits + +- [Fix] use `util.inspect` for a custom inspection symbol method [`e243bf2`](https://github.com/inspect-js/object-inspect/commit/e243bf2eda6c4403ac6f1146fddb14d12e9646c1) +- [meta] add support info [`ca20ba3`](https://github.com/inspect-js/object-inspect/commit/ca20ba35713c17068ca912a86c542f5e8acb656c) +- [Fix] ignore `cause` in node v16.9 and v16.10 where it has a bug [`86aa553`](https://github.com/inspect-js/object-inspect/commit/86aa553a4a455562c2c56f1540f0bf857b9d314b) + +## [v1.12.1](https://github.com/inspect-js/object-inspect/compare/v1.12.0...v1.12.1) - 2022-05-21 + +### Commits + +- [Tests] use `mock-property` [`4ec8893`](https://github.com/inspect-js/object-inspect/commit/4ec8893ea9bfd28065ca3638cf6762424bf44352) +- [meta] use `npmignore` to autogenerate an npmignore file [`07f868c`](https://github.com/inspect-js/object-inspect/commit/07f868c10bd25a9d18686528339bb749c211fc9a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`b05244b`](https://github.com/inspect-js/object-inspect/commit/b05244b4f331e00c43b3151bc498041be77ccc91) +- [Dev Deps] update `@ljharb/eslint-config`, `error-cause`, `es-value-fixtures`, `functions-have-names`, `tape` [`d037398`](https://github.com/inspect-js/object-inspect/commit/d037398dcc5d531532e4c19c4a711ed677f579c1) +- [Fix] properly handle callable regexes in older engines [`848fe48`](https://github.com/inspect-js/object-inspect/commit/848fe48bd6dd0064ba781ee6f3c5e54a94144c37) + +## [v1.12.0](https://github.com/inspect-js/object-inspect/compare/v1.11.1...v1.12.0) - 2021-12-18 + +### Commits + +- [New] add `numericSeparator` boolean option [`2d2d537`](https://github.com/inspect-js/object-inspect/commit/2d2d537f5359a4300ce1c10241369f8024f89e11) +- [Robustness] cache more prototype methods [`191533d`](https://github.com/inspect-js/object-inspect/commit/191533da8aec98a05eadd73a5a6e979c9c8653e8) +- [New] ensure an Error’s `cause` is displayed [`53bc2ce`](https://github.com/inspect-js/object-inspect/commit/53bc2cee4e5a9cc4986f3cafa22c0685f340715e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`bc164b6`](https://github.com/inspect-js/object-inspect/commit/bc164b6e2e7d36b263970f16f54de63048b84a36) +- [Robustness] cache `RegExp.prototype.test` [`a314ab8`](https://github.com/inspect-js/object-inspect/commit/a314ab8271b905cbabc594c82914d2485a8daf12) +- [meta] fix auto-changelog settings [`5ed0983`](https://github.com/inspect-js/object-inspect/commit/5ed0983be72f73e32e2559997517a95525c7e20d) + +## [v1.11.1](https://github.com/inspect-js/object-inspect/compare/v1.11.0...v1.11.1) - 2021-12-05 + +### Commits + +- [meta] add `auto-changelog` [`7dbdd22`](https://github.com/inspect-js/object-inspect/commit/7dbdd228401d6025d8b7391476d88aee9ea9bbdf) +- [actions] reuse common workflows [`c8823bc`](https://github.com/inspect-js/object-inspect/commit/c8823bc0a8790729680709d45fb6e652432e91aa) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`7532b12`](https://github.com/inspect-js/object-inspect/commit/7532b120598307497b712890f75af8056f6d37a6) +- [Refactor] use `has-tostringtag` to behave correctly in the presence of symbol shams [`94abb5d`](https://github.com/inspect-js/object-inspect/commit/94abb5d4e745bf33253942dea86b3e538d2ff6c6) +- [actions] update codecov uploader [`5ed5102`](https://github.com/inspect-js/object-inspect/commit/5ed51025267a00e53b1341357315490ac4eb0874) +- [Dev Deps] update `eslint`, `tape` [`37b2ad2`](https://github.com/inspect-js/object-inspect/commit/37b2ad26c08d94bfd01d5d07069a0b28ef4e2ad7) +- [meta] add `sideEffects` flag [`d341f90`](https://github.com/inspect-js/object-inspect/commit/d341f905ef8bffa6a694cda6ddc5ba343532cd4f) + +## [v1.11.0](https://github.com/inspect-js/object-inspect/compare/v1.10.3...v1.11.0) - 2021-07-12 + +### Commits + +- [New] `customInspect`: add `symbol` option, to mimic modern util.inspect behavior [`e973a6e`](https://github.com/inspect-js/object-inspect/commit/e973a6e21f8140c5837cf25e9d89bdde88dc3120) +- [Dev Deps] update `eslint` [`05f1cb3`](https://github.com/inspect-js/object-inspect/commit/05f1cb3cbcfe1f238e8b51cf9bc294305b7ed793) + +## [v1.10.3](https://github.com/inspect-js/object-inspect/compare/v1.10.2...v1.10.3) - 2021-05-07 + +### Commits + +- [Fix] handle core-js Symbol shams [`4acfc2c`](https://github.com/inspect-js/object-inspect/commit/4acfc2c4b503498759120eb517abad6d51c9c5d6) +- [readme] update badges [`95c323a`](https://github.com/inspect-js/object-inspect/commit/95c323ad909d6cbabb95dd6015c190ba6db9c1f2) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud` [`cb38f48`](https://github.com/inspect-js/object-inspect/commit/cb38f485de6ec7a95109b5a9bbd0a1deba2f6611) + +## [v1.10.2](https://github.com/inspect-js/object-inspect/compare/v1.10.1...v1.10.2) - 2021-04-17 + +### Commits + +- [Fix] use a robust check for a boxed Symbol [`87f12d6`](https://github.com/inspect-js/object-inspect/commit/87f12d6e69ce530be04659c81a4cd502943acac5) + +## [v1.10.1](https://github.com/inspect-js/object-inspect/compare/v1.10.0...v1.10.1) - 2021-04-17 + +### Commits + +- [Fix] use a robust check for a boxed bigint [`d5ca829`](https://github.com/inspect-js/object-inspect/commit/d5ca8298b6d2e5c7b9334a5b21b96ed95d225c91) + +## [v1.10.0](https://github.com/inspect-js/object-inspect/compare/v1.9.0...v1.10.0) - 2021-04-17 + +### Commits + +- [Tests] increase coverage [`d8abb8a`](https://github.com/inspect-js/object-inspect/commit/d8abb8a62c2f084919df994a433b346e0d87a227) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`4bfec2e`](https://github.com/inspect-js/object-inspect/commit/4bfec2e30aaef6ddef6cbb1448306f9f8b9520b7) +- [New] respect `Symbol.toStringTag` on objects [`799b58f`](https://github.com/inspect-js/object-inspect/commit/799b58f536a45e4484633a8e9daeb0330835f175) +- [Fix] do not allow Symbol.toStringTag to masquerade as builtins [`d6c5b37`](https://github.com/inspect-js/object-inspect/commit/d6c5b37d7e94427796b82432fb0c8964f033a6ab) +- [New] add `WeakRef` support [`b6d898e`](https://github.com/inspect-js/object-inspect/commit/b6d898ee21868c780a7ee66b28532b5b34ed7f09) +- [meta] do not publish github action workflow files [`918cdfc`](https://github.com/inspect-js/object-inspect/commit/918cdfc4b6fe83f559ff6ef04fe66201e3ff5cbd) +- [meta] create `FUNDING.yml` [`0bb5fc5`](https://github.com/inspect-js/object-inspect/commit/0bb5fc516dbcd2cd728bd89cee0b580acc5ce301) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`22c8dc0`](https://github.com/inspect-js/object-inspect/commit/22c8dc0cac113d70f4781e49a950070923a671be) +- [meta] use `prepublishOnly` script for npm 7+ [`e52ee09`](https://github.com/inspect-js/object-inspect/commit/e52ee09e8050b8dbac94ef57f786675567728223) +- [Dev Deps] update `eslint` [`7c4e6fd`](https://github.com/inspect-js/object-inspect/commit/7c4e6fdedcd27cc980e13c9ad834d05a96f3d40c) + +## [v1.9.0](https://github.com/inspect-js/object-inspect/compare/v1.8.0...v1.9.0) - 2020-11-30 + +### Commits + +- [Tests] migrate tests to Github Actions [`d262251`](https://github.com/inspect-js/object-inspect/commit/d262251e13e16d3490b5473672f6b6d6ff86675d) +- [New] add enumerable own Symbols to plain object output [`ee60c03`](https://github.com/inspect-js/object-inspect/commit/ee60c033088cff9d33baa71e59a362a541b48284) +- [Tests] add passing tests [`01ac3e4`](https://github.com/inspect-js/object-inspect/commit/01ac3e4b5a30f97875a63dc9b1416b3bd626afc9) +- [actions] add "Require Allow Edits" action [`c2d7746`](https://github.com/inspect-js/object-inspect/commit/c2d774680cde4ca4af332d84d4121b26f798ba9e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `core-js` [`70058de`](https://github.com/inspect-js/object-inspect/commit/70058de1579fc54d1d15ed6c2dbe246637ce70ff) +- [Fix] hex characters in strings should be uppercased, to match node `assert` [`6ab8faa`](https://github.com/inspect-js/object-inspect/commit/6ab8faaa0abc08fe7a8e2afd8b39c6f1f0e00113) +- [Tests] run `nyc` on all tests [`4c47372`](https://github.com/inspect-js/object-inspect/commit/4c473727879ddc8e28b599202551ddaaf07b6210) +- [Tests] node 0.8 has an unpredictable property order; fix `groups` test by removing property [`f192069`](https://github.com/inspect-js/object-inspect/commit/f192069a978a3b60e6f0e0d45ac7df260ab9a778) +- [New] add enumerable properties to Function inspect result, per node’s `assert` [`fd38e1b`](https://github.com/inspect-js/object-inspect/commit/fd38e1bc3e2a1dc82091ce3e021917462eee64fc) +- [Tests] fix tests for node < 10, due to regex match `groups` [`2ac6462`](https://github.com/inspect-js/object-inspect/commit/2ac6462cc4f72eaa0b63a8cfee9aabe3008b2330) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`44b59e2`](https://github.com/inspect-js/object-inspect/commit/44b59e2676a7f825ef530dfd19dafb599e3b9456) +- [Robustness] cache `Symbol.prototype.toString` [`f3c2074`](https://github.com/inspect-js/object-inspect/commit/f3c2074d8f32faf8292587c07c9678ea931703dd) +- [Dev Deps] update `eslint` [`9411294`](https://github.com/inspect-js/object-inspect/commit/94112944b9245e3302e25453277876402d207e7f) +- [meta] `require-allow-edits` no longer requires an explicit github token [`36c0220`](https://github.com/inspect-js/object-inspect/commit/36c02205de3c2b0e84d53777c5c9fd54a36c48ab) +- [actions] update rebase checkout action to v2 [`55a39a6`](https://github.com/inspect-js/object-inspect/commit/55a39a64e944f19c6a7d8efddf3df27700f20d14) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`f59fd3c`](https://github.com/inspect-js/object-inspect/commit/f59fd3cf406c3a7c7ece140904a80bbc6bacfcca) +- [Dev Deps] update `eslint` [`a492bec`](https://github.com/inspect-js/object-inspect/commit/a492becec644b0155c9c4bc1caf6f9fac11fb2c7) + +## [v1.8.0](https://github.com/inspect-js/object-inspect/compare/v1.7.0...v1.8.0) - 2020-06-18 + +### Fixed + +- [New] add `indent` option [`#27`](https://github.com/inspect-js/object-inspect/issues/27) + +### Commits + +- [Tests] add codecov [`4324cbb`](https://github.com/inspect-js/object-inspect/commit/4324cbb1a2bd7710822a4151ff373570db22453e) +- [New] add `maxStringLength` option [`b3995cb`](https://github.com/inspect-js/object-inspect/commit/b3995cb71e15b5ee127a3094c43994df9d973502) +- [New] add `customInspect` option, to disable custom inspect methods [`28b9179`](https://github.com/inspect-js/object-inspect/commit/28b9179ee802bb3b90810100c11637db90c2fb6d) +- [Tests] add Date and RegExp tests [`3b28eca`](https://github.com/inspect-js/object-inspect/commit/3b28eca57b0367aeadffac604ea09e8bdae7d97b) +- [actions] add automatic rebasing / merge commit blocking [`0d9c6c0`](https://github.com/inspect-js/object-inspect/commit/0d9c6c044e83475ff0bfffb9d35b149834c83a2e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `tape`; add `aud` [`7c204f2`](https://github.com/inspect-js/object-inspect/commit/7c204f22b9e41bc97147f4d32d4cb045b17769a6) +- [readme] fix repo URLs, remove testling [`34ca9a0`](https://github.com/inspect-js/object-inspect/commit/34ca9a0dabfe75bd311f806a326fadad029909a3) +- [Fix] when truncating a deep array, note it as `[Array]` instead of just `[Object]` [`f74c82d`](https://github.com/inspect-js/object-inspect/commit/f74c82dd0b35386445510deb250f34c41be3ec0e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`1a8a5ea`](https://github.com/inspect-js/object-inspect/commit/1a8a5ea069ea2bee89d77caedad83ffa23d35711) +- [Fix] do not be fooled by a function’s own `toString` method [`7cb5c65`](https://github.com/inspect-js/object-inspect/commit/7cb5c657a976f94715c19c10556a30f15bb7d5d7) +- [patch] indicate explicitly that anon functions are anonymous, to match node [`81ebdd4`](https://github.com/inspect-js/object-inspect/commit/81ebdd4215005144074bbdff3f6bafa01407910a) +- [Dev Deps] loosen the `core-js` dep [`e7472e8`](https://github.com/inspect-js/object-inspect/commit/e7472e8e242117670560bd995830c2a4d12080f5) +- [Dev Deps] update `tape` [`699827e`](https://github.com/inspect-js/object-inspect/commit/699827e6b37258b5203c33c78c009bf4b0e6a66d) +- [meta] add `safe-publish-latest` [`c5d2868`](https://github.com/inspect-js/object-inspect/commit/c5d2868d6eb33c472f37a20f89ceef2787046088) +- [Dev Deps] update `@ljharb/eslint-config` [`9199501`](https://github.com/inspect-js/object-inspect/commit/919950195d486114ccebacbdf9d74d7f382693b0) + +## [v1.7.0](https://github.com/inspect-js/object-inspect/compare/v1.6.0...v1.7.0) - 2019-11-10 + +### Commits + +- [Tests] use shared travis-ci configs [`19899ed`](https://github.com/inspect-js/object-inspect/commit/19899edbf31f4f8809acf745ce34ad1ce1bfa63b) +- [Tests] add linting [`a00f057`](https://github.com/inspect-js/object-inspect/commit/a00f057d917f66ea26dd37769c6b810ec4af97e8) +- [Tests] lint last file [`2698047`](https://github.com/inspect-js/object-inspect/commit/2698047b58af1e2e88061598ef37a75f228dddf6) +- [Tests] up to `node` `v12.7`, `v11.15`, `v10.16`, `v8.16`, `v6.17` [`589e87a`](https://github.com/inspect-js/object-inspect/commit/589e87a99cadcff4b600e6a303418e9d922836e8) +- [New] add support for `WeakMap` and `WeakSet` [`3ddb3e4`](https://github.com/inspect-js/object-inspect/commit/3ddb3e4e0c8287130c61a12e0ed9c104b1549306) +- [meta] clean up license so github can detect it properly [`27527bb`](https://github.com/inspect-js/object-inspect/commit/27527bb801520c9610c68cc3b55d6f20a2bee56d) +- [Tests] cover `util.inspect.custom` [`36d47b9`](https://github.com/inspect-js/object-inspect/commit/36d47b9c59056a57ef2f1491602c726359561800) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `tape` [`b614eaa`](https://github.com/inspect-js/object-inspect/commit/b614eaac901da0e5c69151f534671f990a94cace) +- [Tests] fix coverage thresholds [`7b7b176`](https://github.com/inspect-js/object-inspect/commit/7b7b176e15f8bd6e8b2f261ff5a493c2fe78d9c2) +- [Tests] bigint tests now can run on unflagged node [`063af31`](https://github.com/inspect-js/object-inspect/commit/063af31ce9cd13c202e3b67c07ba06dc9b7c0f81) +- [Refactor] add early bailout to `isMap` and `isSet` checks [`fc51047`](https://github.com/inspect-js/object-inspect/commit/fc5104714a3671d37e225813db79470d6335683b) +- [meta] add `funding` field [`7f9953a`](https://github.com/inspect-js/object-inspect/commit/7f9953a113eec7b064a6393cf9f90ba15f1d131b) +- [Tests] Fix invalid strict-mode syntax with hexadecimal [`a8b5425`](https://github.com/inspect-js/object-inspect/commit/a8b542503b4af1599a275209a1a99f5fdedb1ead) +- [Dev Deps] update `@ljharb/eslint-config` [`98df157`](https://github.com/inspect-js/object-inspect/commit/98df1577314d9188a3fc3f17fdcf2fba697ae1bd) +- add copyright to LICENSE [`bb69fd0`](https://github.com/inspect-js/object-inspect/commit/bb69fd017a062d299e44da1f9b2c7dcd67f621e6) +- [Tests] use `npx aud` in `posttest` [`4838353`](https://github.com/inspect-js/object-inspect/commit/4838353593974cf7f905b9ef04c03c094f0cdbe2) +- [Tests] move `0.6` to allowed failures, because it won‘t build on travis [`1bff32a`](https://github.com/inspect-js/object-inspect/commit/1bff32aa52e8aea687f0856b28ba754b3e43ebf7) + +## [v1.6.0](https://github.com/inspect-js/object-inspect/compare/v1.5.0...v1.6.0) - 2018-05-02 + +### Commits + +- [New] add support for boxed BigInt primitives [`356c66a`](https://github.com/inspect-js/object-inspect/commit/356c66a410e7aece7162c8319880a5ef647beaa9) +- [Tests] up to `node` `v10.0`, `v9.11`, `v8.11`, `v6.14`, `v4.9` [`c77b65b`](https://github.com/inspect-js/object-inspect/commit/c77b65bba593811b906b9ec57561c5cba92e2db3) +- [New] Add support for upcoming `BigInt` [`1ac548e`](https://github.com/inspect-js/object-inspect/commit/1ac548e4b27e26466c28c9a5e63e5d4e0591c31f) +- [Tests] run bigint tests in CI with --harmony-bigint flag [`d31b738`](https://github.com/inspect-js/object-inspect/commit/d31b73831880254b5c6cf5691cda9a149fbc5f04) +- [Dev Deps] update `core-js`, `tape` [`ff9eff6`](https://github.com/inspect-js/object-inspect/commit/ff9eff67113341ee1aaf80c1c22d683f43bfbccf) +- [Docs] fix example to use `safer-buffer` [`48cae12`](https://github.com/inspect-js/object-inspect/commit/48cae12a73ec6cacc955175bc56bbe6aee6a211f) + +## [v1.5.0](https://github.com/inspect-js/object-inspect/compare/v1.4.1...v1.5.0) - 2017-12-25 + +### Commits + +- [New] add `quoteStyle` option [`f5a72d2`](https://github.com/inspect-js/object-inspect/commit/f5a72d26edb3959b048f74c056ca7100a6b091e4) +- [Tests] add more test coverage [`30ebe4e`](https://github.com/inspect-js/object-inspect/commit/30ebe4e1fa943b99ecbb85be7614256d536e2759) +- [Tests] require 0.6 to pass [`99a008c`](https://github.com/inspect-js/object-inspect/commit/99a008ccace189a60fd7da18bf00e32c9572b980) + +## [v1.4.1](https://github.com/inspect-js/object-inspect/compare/v1.4.0...v1.4.1) - 2017-12-19 + +### Commits + +- [Tests] up to `node` `v9.3`, `v8.9`, `v6.12` [`6674476`](https://github.com/inspect-js/object-inspect/commit/6674476cc56acaac1bde96c84fed5ef631911906) +- [Fix] `inspect(Object(-0))` should be “Object(-0)”, not “Object(0)” [`d0a031f`](https://github.com/inspect-js/object-inspect/commit/d0a031f1cbb3024ee9982bfe364dd18a7e4d1bd3) + +## [v1.4.0](https://github.com/inspect-js/object-inspect/compare/v1.3.0...v1.4.0) - 2017-10-24 + +### Commits + +- [Tests] add `npm run coverage` [`3b48fb2`](https://github.com/inspect-js/object-inspect/commit/3b48fb25db037235eeb808f0b2830aad7aa36f70) +- [Tests] remove commented-out osx builds [`71e24db`](https://github.com/inspect-js/object-inspect/commit/71e24db8ad6ee3b9b381c5300b0475f2ba595a73) +- [New] add support for `util.inspect.custom`, in node only. [`20cca77`](https://github.com/inspect-js/object-inspect/commit/20cca7762d7e17f15b21a90793dff84acce155df) +- [Tests] up to `node` `v8.6`; use `nvm install-latest-npm` to ensure new npm doesn’t break old node [`252952d`](https://github.com/inspect-js/object-inspect/commit/252952d230d8065851dd3d4d5fe8398aae068529) +- [Tests] up to `node` `v8.8` [`4aa868d`](https://github.com/inspect-js/object-inspect/commit/4aa868d3a62914091d489dd6ec6eed194ee67cd3) +- [Dev Deps] update `core-js`, `tape` [`59483d1`](https://github.com/inspect-js/object-inspect/commit/59483d1df418f852f51fa0db7b24aa6b0209a27a) + +## [v1.3.0](https://github.com/inspect-js/object-inspect/compare/v1.2.2...v1.3.0) - 2017-07-31 + +### Fixed + +- [Fix] Map/Set: work around core-js bug < v2.5.0 [`#9`](https://github.com/inspect-js/object-inspect/issues/9) + +### Commits + +- [New] add support for arrays with additional object keys [`0d19937`](https://github.com/inspect-js/object-inspect/commit/0d199374ee37959e51539616666f420ccb29acb9) +- [Tests] up to `node` `v8.2`, `v7.10`, `v6.11`; fix new npm breaking on older nodes [`e24784a`](https://github.com/inspect-js/object-inspect/commit/e24784a90c49117787157a12a63897c49cf89bbb) +- Only apps should have lockfiles [`c6faebc`](https://github.com/inspect-js/object-inspect/commit/c6faebcb2ee486a889a4a1c4d78c0776c7576185) +- [Dev Deps] update `tape` [`7345a0a`](https://github.com/inspect-js/object-inspect/commit/7345a0aeba7e91b888a079c10004d17696a7f586) + +## [v1.2.2](https://github.com/inspect-js/object-inspect/compare/v1.2.1...v1.2.2) - 2017-03-24 + +### Commits + +- [Tests] up to `node` `v7.7`, `v6.10`, `v4.8`; improve test matrix [`a2ddc15`](https://github.com/inspect-js/object-inspect/commit/a2ddc15a1f2c65af18076eea1c0eb9cbceb478a0) +- [Tests] up to `node` `v7.0`, `v6.9`, `v5.12`, `v4.6`, `io.js` `v3.3`; improve test matrix [`a48949f`](https://github.com/inspect-js/object-inspect/commit/a48949f6b574b2d4d2298109d8e8d0eb3e7a83e7) +- [Performance] check for primitive types as early as possible. [`3b8092a`](https://github.com/inspect-js/object-inspect/commit/3b8092a2a4deffd0575f94334f00194e2d48dad3) +- [Refactor] remove unneeded `else`s. [`7255034`](https://github.com/inspect-js/object-inspect/commit/725503402e08de4f96f6bf2d8edef44ac36f26b6) +- [Refactor] avoid recreating `lowbyte` function every time. [`81edd34`](https://github.com/inspect-js/object-inspect/commit/81edd3475bd15bdd18e84de7472033dcf5004aaa) +- [Fix] differentiate -0 from 0 [`521d345`](https://github.com/inspect-js/object-inspect/commit/521d3456b009da7bf1c5785c8a9df5a9f8718264) +- [Refactor] move object key gathering into separate function [`aca6265`](https://github.com/inspect-js/object-inspect/commit/aca626536eaeef697196c6e9db3e90e7e0355b6a) +- [Refactor] consolidate wrapping logic for boxed primitives into a function. [`4e440cd`](https://github.com/inspect-js/object-inspect/commit/4e440cd9065df04802a2a1dead03f48c353ca301) +- [Robustness] use `typeof` instead of comparing to literal `undefined` [`5ca6f60`](https://github.com/inspect-js/object-inspect/commit/5ca6f601937506daff8ed2fcf686363b55807b69) +- [Refactor] consolidate Map/Set notations. [`4e576e5`](https://github.com/inspect-js/object-inspect/commit/4e576e5d7ed2f9ec3fb7f37a0d16732eb10758a9) +- [Tests] ensure that this function remains anonymous, despite ES6 name inference. [`7540ae5`](https://github.com/inspect-js/object-inspect/commit/7540ae591278756db614fa4def55ca413150e1a3) +- [Refactor] explicitly coerce Error objects to strings. [`7f4ca84`](https://github.com/inspect-js/object-inspect/commit/7f4ca8424ee8dc2c0ca5a422d94f7fac40327261) +- [Refactor] split up `var` declarations for debuggability [`6f2c11e`](https://github.com/inspect-js/object-inspect/commit/6f2c11e6a85418586a00292dcec5e97683f89bc3) +- [Robustness] cache `Object.prototype.toString` [`df44a20`](https://github.com/inspect-js/object-inspect/commit/df44a20adfccf31529d60d1df2079bfc3c836e27) +- [Dev Deps] update `tape` [`3ec714e`](https://github.com/inspect-js/object-inspect/commit/3ec714eba57bc3f58a6eb4fca1376f49e70d300a) +- [Dev Deps] update `tape` [`beb72d9`](https://github.com/inspect-js/object-inspect/commit/beb72d969653747d7cde300393c28755375329b0) + +## [v1.2.1](https://github.com/inspect-js/object-inspect/compare/v1.2.0...v1.2.1) - 2016-04-09 + +### Fixed + +- [Fix] fix Boolean `false` object inspection. [`#7`](https://github.com/substack/object-inspect/pull/7) + +## [v1.2.0](https://github.com/inspect-js/object-inspect/compare/v1.1.0...v1.2.0) - 2016-04-09 + +### Fixed + +- [New] add support for inspecting String/Number/Boolean objects. [`#6`](https://github.com/inspect-js/object-inspect/issues/6) + +### Commits + +- [Dev Deps] update `tape` [`742caa2`](https://github.com/inspect-js/object-inspect/commit/742caa262cf7af4c815d4821c8bd0129c1446432) + +## [v1.1.0](https://github.com/inspect-js/object-inspect/compare/1.0.2...v1.1.0) - 2015-12-14 + +### Merged + +- [New] add ES6 Map/Set support. [`#4`](https://github.com/inspect-js/object-inspect/pull/4) + +### Fixed + +- [New] add ES6 Map/Set support. [`#3`](https://github.com/inspect-js/object-inspect/issues/3) + +### Commits + +- Update `travis.yml` to test on bunches of `iojs` and `node` versions. [`4c1fd65`](https://github.com/inspect-js/object-inspect/commit/4c1fd65cc3bd95307e854d114b90478324287fd2) +- [Dev Deps] update `tape` [`88a907e`](https://github.com/inspect-js/object-inspect/commit/88a907e33afbe408e4b5d6e4e42a33143f88848c) + +## [1.0.2](https://github.com/inspect-js/object-inspect/compare/1.0.1...1.0.2) - 2015-08-07 + +### Commits + +- [Fix] Cache `Object.prototype.hasOwnProperty` in case it's deleted later. [`1d0075d`](https://github.com/inspect-js/object-inspect/commit/1d0075d3091dc82246feeb1f9871cb2b8ed227b3) +- [Dev Deps] Update `tape` [`ca8d5d7`](https://github.com/inspect-js/object-inspect/commit/ca8d5d75635ddbf76f944e628267581e04958457) +- gitignore node_modules since this is a reusable modules. [`ed41407`](https://github.com/inspect-js/object-inspect/commit/ed41407811743ca530cdeb28f982beb96026af82) + +## [1.0.1](https://github.com/inspect-js/object-inspect/compare/1.0.0...1.0.1) - 2015-07-19 + +### Commits + +- Make `inspect` work with symbol primitives and objects, including in node 0.11 and 0.12. [`ddf1b94`](https://github.com/inspect-js/object-inspect/commit/ddf1b94475ab951f1e3bccdc0a48e9073cfbfef4) +- bump tape [`103d674`](https://github.com/inspect-js/object-inspect/commit/103d67496b504bdcfdd765d303a773f87ec106e2) +- use newer travis config [`d497276`](https://github.com/inspect-js/object-inspect/commit/d497276c1da14234bb5098a59cf20de75fbc316a) + +## [1.0.0](https://github.com/inspect-js/object-inspect/compare/0.4.0...1.0.0) - 2014-08-05 + +### Commits + +- error inspect works properly [`260a22d`](https://github.com/inspect-js/object-inspect/commit/260a22d134d3a8a482c67d52091c6040c34f4299) +- seen coverage [`57269e8`](https://github.com/inspect-js/object-inspect/commit/57269e8baa992a7439047f47325111fdcbcb8417) +- htmlelement instance coverage [`397ffe1`](https://github.com/inspect-js/object-inspect/commit/397ffe10a1980350868043ef9de65686d438979f) +- more element coverage [`6905cc2`](https://github.com/inspect-js/object-inspect/commit/6905cc2f7df35600177e613b0642b4df5efd3eca) +- failing test for type errors [`385b615`](https://github.com/inspect-js/object-inspect/commit/385b6152e49b51b68449a662f410b084ed7c601a) +- fn name coverage [`edc906d`](https://github.com/inspect-js/object-inspect/commit/edc906d40fca6b9194d304062c037ee8e398c4c2) +- server-side element test [`362d1d3`](https://github.com/inspect-js/object-inspect/commit/362d1d3e86f187651c29feeb8478110afada385b) +- custom inspect fn [`e89b0f6`](https://github.com/inspect-js/object-inspect/commit/e89b0f6fe6d5e03681282af83732a509160435a6) +- fixed browser test [`b530882`](https://github.com/inspect-js/object-inspect/commit/b5308824a1c8471c5617e394766a03a6977102a9) +- depth test, matches node [`1cfd9e0`](https://github.com/inspect-js/object-inspect/commit/1cfd9e0285a4ae1dff44101ad482915d9bf47e48) +- exercise hasOwnProperty path [`8d753fb`](https://github.com/inspect-js/object-inspect/commit/8d753fb362a534fa1106e4d80f2ee9bea06a66d9) +- more cases covered for errors [`c5c46a5`](https://github.com/inspect-js/object-inspect/commit/c5c46a569ec4606583497e8550f0d8c7ad39a4a4) +- \W obj key test case [`b0eceee`](https://github.com/inspect-js/object-inspect/commit/b0eceeea6e0eb94d686c1046e99b9e25e5005f75) +- coverage for explicit depth param [`e12b91c`](https://github.com/inspect-js/object-inspect/commit/e12b91cd59683362f3a0e80f46481a0211e26c15) + +## [0.4.0](https://github.com/inspect-js/object-inspect/compare/0.3.1...0.4.0) - 2014-03-21 + +### Commits + +- passing lowbyte interpolation test [`b847511`](https://github.com/inspect-js/object-inspect/commit/b8475114f5def7e7961c5353d48d3d8d9a520985) +- lowbyte test [`4a2b0e1`](https://github.com/inspect-js/object-inspect/commit/4a2b0e142667fc933f195472759385ac08f3946c) + +## [0.3.1](https://github.com/inspect-js/object-inspect/compare/0.3.0...0.3.1) - 2014-03-04 + +### Commits + +- sort keys [`a07b19c`](https://github.com/inspect-js/object-inspect/commit/a07b19cc3b1521a82d4fafb6368b7a9775428a05) + +## [0.3.0](https://github.com/inspect-js/object-inspect/compare/0.2.0...0.3.0) - 2014-03-04 + +### Commits + +- [] and {} instead of [ ] and { } [`654c44b`](https://github.com/inspect-js/object-inspect/commit/654c44b2865811f3519e57bb8526e0821caf5c6b) + +## [0.2.0](https://github.com/inspect-js/object-inspect/compare/0.1.3...0.2.0) - 2014-03-04 + +### Commits + +- failing holes test [`99cdfad`](https://github.com/inspect-js/object-inspect/commit/99cdfad03c6474740275a75636fe6ca86c77737a) +- regex already work [`e324033`](https://github.com/inspect-js/object-inspect/commit/e324033267025995ec97d32ed0a65737c99477a6) +- failing undef/null test [`1f88a00`](https://github.com/inspect-js/object-inspect/commit/1f88a00265d3209719dda8117b7e6360b4c20943) +- holes in the all example [`7d345f3`](https://github.com/inspect-js/object-inspect/commit/7d345f3676dcbe980cff89a4f6c243269ebbb709) +- check for .inspect(), fixes Buffer use-case [`c3f7546`](https://github.com/inspect-js/object-inspect/commit/c3f75466dbca125347d49847c05262c292f12b79) +- fixes for holes [`ce25f73`](https://github.com/inspect-js/object-inspect/commit/ce25f736683de4b92ff27dc5471218415e2d78d8) +- weird null behavior [`405c1ea`](https://github.com/inspect-js/object-inspect/commit/405c1ea72cd5a8cf3b498c3eaa903d01b9fbcab5) +- tape is actually a devDependency, upgrade [`703b0ce`](https://github.com/inspect-js/object-inspect/commit/703b0ce6c5817b4245a082564bccd877e0bb6990) +- put date in the example [`a342219`](https://github.com/inspect-js/object-inspect/commit/a3422190eeaa013215f46df2d0d37b48595ac058) +- passing the null test [`4ab737e`](https://github.com/inspect-js/object-inspect/commit/4ab737ebf862a75d247ebe51e79307a34d6380d4) + +## [0.1.3](https://github.com/inspect-js/object-inspect/compare/0.1.1...0.1.3) - 2013-07-26 + +### Commits + +- special isElement() check [`882768a`](https://github.com/inspect-js/object-inspect/commit/882768a54035d30747be9de1baf14e5aa0daa128) +- oh right old IEs don't have indexOf either [`36d1275`](https://github.com/inspect-js/object-inspect/commit/36d12756c38b08a74370b0bb696c809e529913a5) + +## [0.1.1](https://github.com/inspect-js/object-inspect/compare/0.1.0...0.1.1) - 2013-07-26 + +### Commits + +- tests! [`4422fd9`](https://github.com/inspect-js/object-inspect/commit/4422fd95532c2745aa6c4f786f35f1090be29998) +- fix for ie<9, doesn't have hasOwnProperty [`6b7d611`](https://github.com/inspect-js/object-inspect/commit/6b7d61183050f6da801ea04473211da226482613) +- fix for all IEs: no f.name [`4e0c2f6`](https://github.com/inspect-js/object-inspect/commit/4e0c2f6dfd01c306d067d7163319acc97c94ee50) +- badges [`5ed0d88`](https://github.com/inspect-js/object-inspect/commit/5ed0d88e4e407f9cb327fa4a146c17921f9680f3) + +## [0.1.0](https://github.com/inspect-js/object-inspect/compare/0.0.0...0.1.0) - 2013-07-26 + +### Commits + +- [Function] for functions [`ad5c485`](https://github.com/inspect-js/object-inspect/commit/ad5c485098fc83352cb540a60b2548ca56820e0b) + +## 0.0.0 - 2013-07-26 + +### Commits + +- working browser example [`34be6b6`](https://github.com/inspect-js/object-inspect/commit/34be6b6548f9ce92bdc3c27572857ba0c4a1218d) +- package.json etc [`cad51f2`](https://github.com/inspect-js/object-inspect/commit/cad51f23fc6bcf1a456ed6abe16088256c2f632f) +- docs complete [`b80cce2`](https://github.com/inspect-js/object-inspect/commit/b80cce2490c4e7183a9ee11ea89071f0abec4446) +- circular example [`4b4a7b9`](https://github.com/inspect-js/object-inspect/commit/4b4a7b92209e4e6b4630976cb6bcd17d14165a59) +- string rep [`7afb479`](https://github.com/inspect-js/object-inspect/commit/7afb479baa798d27f09e0a178b72ea327f60f5c8) diff --git a/node_modules/object-inspect/LICENSE b/node_modules/object-inspect/LICENSE new file mode 100644 index 000000000..ca64cc1e6 --- /dev/null +++ b/node_modules/object-inspect/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 James Halliday + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/object-inspect/example/all.js b/node_modules/object-inspect/example/all.js new file mode 100644 index 000000000..2f3355c50 --- /dev/null +++ b/node_modules/object-inspect/example/all.js @@ -0,0 +1,23 @@ +'use strict'; + +var inspect = require('../'); +var Buffer = require('safer-buffer').Buffer; + +var holes = ['a', 'b']; +holes[4] = 'e'; +holes[6] = 'g'; + +var obj = { + a: 1, + b: [3, 4, undefined, null], + c: undefined, + d: null, + e: { + regex: /^x/i, + buf: Buffer.from('abc'), + holes: holes + }, + now: new Date() +}; +obj.self = obj; +console.log(inspect(obj)); diff --git a/node_modules/object-inspect/example/circular.js b/node_modules/object-inspect/example/circular.js new file mode 100644 index 000000000..487a7c169 --- /dev/null +++ b/node_modules/object-inspect/example/circular.js @@ -0,0 +1,6 @@ +'use strict'; + +var inspect = require('../'); +var obj = { a: 1, b: [3, 4] }; +obj.c = obj; +console.log(inspect(obj)); diff --git a/node_modules/object-inspect/example/fn.js b/node_modules/object-inspect/example/fn.js new file mode 100644 index 000000000..9b5db8de0 --- /dev/null +++ b/node_modules/object-inspect/example/fn.js @@ -0,0 +1,5 @@ +'use strict'; + +var inspect = require('../'); +var obj = [1, 2, function f(n) { return n + 5; }, 4]; +console.log(inspect(obj)); diff --git a/node_modules/object-inspect/example/inspect.js b/node_modules/object-inspect/example/inspect.js new file mode 100644 index 000000000..e2df7c9f4 --- /dev/null +++ b/node_modules/object-inspect/example/inspect.js @@ -0,0 +1,10 @@ +'use strict'; + +/* eslint-env browser */ +var inspect = require('../'); + +var d = document.createElement('div'); +d.setAttribute('id', 'beep'); +d.innerHTML = 'woooiiiii'; + +console.log(inspect([d, { a: 3, b: 4, c: [5, 6, [7, [8, [9]]]] }])); diff --git a/node_modules/object-inspect/index.js b/node_modules/object-inspect/index.js new file mode 100644 index 000000000..ff2033492 --- /dev/null +++ b/node_modules/object-inspect/index.js @@ -0,0 +1,524 @@ +var hasMap = typeof Map === 'function' && Map.prototype; +var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; +var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; +var mapForEach = hasMap && Map.prototype.forEach; +var hasSet = typeof Set === 'function' && Set.prototype; +var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; +var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; +var setForEach = hasSet && Set.prototype.forEach; +var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype; +var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; +var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype; +var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; +var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype; +var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; +var booleanValueOf = Boolean.prototype.valueOf; +var objectToString = Object.prototype.toString; +var functionToString = Function.prototype.toString; +var $match = String.prototype.match; +var $slice = String.prototype.slice; +var $replace = String.prototype.replace; +var $toUpperCase = String.prototype.toUpperCase; +var $toLowerCase = String.prototype.toLowerCase; +var $test = RegExp.prototype.test; +var $concat = Array.prototype.concat; +var $join = Array.prototype.join; +var $arrSlice = Array.prototype.slice; +var $floor = Math.floor; +var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null; +var gOPS = Object.getOwnPropertySymbols; +var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null; +var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object'; +// ie, `has-tostringtag/shams +var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol') + ? Symbol.toStringTag + : null; +var isEnumerable = Object.prototype.propertyIsEnumerable; + +var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ( + [].__proto__ === Array.prototype // eslint-disable-line no-proto + ? function (O) { + return O.__proto__; // eslint-disable-line no-proto + } + : null +); + +function addNumericSeparator(num, str) { + if ( + num === Infinity + || num === -Infinity + || num !== num + || (num && num > -1000 && num < 1000) + || $test.call(/e/, str) + ) { + return str; + } + var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; + if (typeof num === 'number') { + var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num) + if (int !== num) { + var intStr = String(int); + var dec = $slice.call(str, intStr.length + 1); + return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, ''); + } + } + return $replace.call(str, sepRegex, '$&_'); +} + +var utilInspect = require('./util.inspect'); +var inspectCustom = utilInspect.custom; +var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; + +module.exports = function inspect_(obj, options, depth, seen) { + var opts = options || {}; + + if (has(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + if ( + has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number' + ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity + : opts.maxStringLength !== null + ) + ) { + throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); + } + var customInspect = has(opts, 'customInspect') ? opts.customInspect : true; + if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') { + throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`'); + } + + if ( + has(opts, 'indent') + && opts.indent !== null + && opts.indent !== '\t' + && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0) + ) { + throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); + } + if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') { + throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); + } + var numericSeparator = opts.numericSeparator; + + if (typeof obj === 'undefined') { + return 'undefined'; + } + if (obj === null) { + return 'null'; + } + if (typeof obj === 'boolean') { + return obj ? 'true' : 'false'; + } + + if (typeof obj === 'string') { + return inspectString(obj, opts); + } + if (typeof obj === 'number') { + if (obj === 0) { + return Infinity / obj > 0 ? '0' : '-0'; + } + var str = String(obj); + return numericSeparator ? addNumericSeparator(obj, str) : str; + } + if (typeof obj === 'bigint') { + var bigIntStr = String(obj) + 'n'; + return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; + } + + var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; + if (typeof depth === 'undefined') { depth = 0; } + if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { + return isArray(obj) ? '[Array]' : '[Object]'; + } + + var indent = getIndent(opts, depth); + + if (typeof seen === 'undefined') { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return '[Circular]'; + } + + function inspect(value, from, noIndent) { + if (from) { + seen = $arrSlice.call(seen); + seen.push(from); + } + if (noIndent) { + var newOpts = { + depth: opts.depth + }; + if (has(opts, 'quoteStyle')) { + newOpts.quoteStyle = opts.quoteStyle; + } + return inspect_(value, newOpts, depth + 1, seen); + } + return inspect_(value, opts, depth + 1, seen); + } + + if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable + var name = nameOf(obj); + var keys = arrObjKeys(obj, inspect); + return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : ''); + } + if (isSymbol(obj)) { + var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj); + return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s = '<' + $toLowerCase.call(String(obj.nodeName)); + var attrs = obj.attributes || []; + for (var i = 0; i < attrs.length; i++) { + s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts); + } + s += '>'; + if (obj.childNodes && obj.childNodes.length) { s += '...'; } + s += ''; + return s; + } + if (isArray(obj)) { + if (obj.length === 0) { return '[]'; } + var xs = arrObjKeys(obj, inspect); + if (indent && !singleLineValues(xs)) { + return '[' + indentedJoin(xs, indent) + ']'; + } + return '[ ' + $join.call(xs, ', ') + ' ]'; + } + if (isError(obj)) { + var parts = arrObjKeys(obj, inspect); + if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) { + return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }'; + } + if (parts.length === 0) { return '[' + String(obj) + ']'; } + return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }'; + } + if (typeof obj === 'object' && customInspect) { + if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); + } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') { + return obj.inspect(); + } + } + if (isMap(obj)) { + var mapParts = []; + if (mapForEach) { + mapForEach.call(obj, function (value, key) { + mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj)); + }); + } + return collectionOf('Map', mapSize.call(obj), mapParts, indent); + } + if (isSet(obj)) { + var setParts = []; + if (setForEach) { + setForEach.call(obj, function (value) { + setParts.push(inspect(value, obj)); + }); + } + return collectionOf('Set', setSize.call(obj), setParts, indent); + } + if (isWeakMap(obj)) { + return weakCollectionOf('WeakMap'); + } + if (isWeakSet(obj)) { + return weakCollectionOf('WeakSet'); + } + if (isWeakRef(obj)) { + return weakCollectionOf('WeakRef'); + } + if (isNumber(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString(obj)) { + return markBoxed(inspect(String(obj))); + } + // note: in IE 8, sometimes `global !== window` but both are the prototypes of each other + /* eslint-env browser */ + if (typeof window !== 'undefined' && obj === window) { + return '{ [object Window] }'; + } + if (obj === global) { + return '{ [object globalThis] }'; + } + if (!isDate(obj) && !isRegExp(obj)) { + var ys = arrObjKeys(obj, inspect); + var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; + var protoTag = obj instanceof Object ? '' : 'null prototype'; + var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : ''; + var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : ''; + var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : ''); + if (ys.length === 0) { return tag + '{}'; } + if (indent) { + return tag + '{' + indentedJoin(ys, indent) + '}'; + } + return tag + '{ ' + $join.call(ys, ', ') + ' }'; + } + return String(obj); +}; + +function wrapQuotes(s, defaultStyle, opts) { + var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'"; + return quoteChar + s + quoteChar; +} + +function quote(s) { + return $replace.call(String(s), /"/g, '"'); +} + +function isArray(obj) { return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isDate(obj) { return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isError(obj) { return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isString(obj) { return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isNumber(obj) { return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } + +// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives +function isSymbol(obj) { + if (hasShammedSymbols) { + return obj && typeof obj === 'object' && obj instanceof Symbol; + } + if (typeof obj === 'symbol') { + return true; + } + if (!obj || typeof obj !== 'object' || !symToString) { + return false; + } + try { + symToString.call(obj); + return true; + } catch (e) {} + return false; +} + +function isBigInt(obj) { + if (!obj || typeof obj !== 'object' || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e) {} + return false; +} + +var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; +function has(obj, key) { + return hasOwn.call(obj, key); +} + +function toStr(obj) { + return objectToString.call(obj); +} + +function nameOf(f) { + if (f.name) { return f.name; } + var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/); + if (m) { return m[1]; } + return null; +} + +function indexOf(xs, x) { + if (xs.indexOf) { return xs.indexOf(x); } + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) { return i; } + } + return -1; +} + +function isMap(x) { + if (!mapSize || !x || typeof x !== 'object') { + return false; + } + try { + mapSize.call(x); + try { + setSize.call(x); + } catch (s) { + return true; + } + return x instanceof Map; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakMap(x) { + if (!weakMapHas || !x || typeof x !== 'object') { + return false; + } + try { + weakMapHas.call(x, weakMapHas); + try { + weakSetHas.call(x, weakSetHas); + } catch (s) { + return true; + } + return x instanceof WeakMap; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakRef(x) { + if (!weakRefDeref || !x || typeof x !== 'object') { + return false; + } + try { + weakRefDeref.call(x); + return true; + } catch (e) {} + return false; +} + +function isSet(x) { + if (!setSize || !x || typeof x !== 'object') { + return false; + } + try { + setSize.call(x); + try { + mapSize.call(x); + } catch (m) { + return true; + } + return x instanceof Set; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakSet(x) { + if (!weakSetHas || !x || typeof x !== 'object') { + return false; + } + try { + weakSetHas.call(x, weakSetHas); + try { + weakMapHas.call(x, weakMapHas); + } catch (s) { + return true; + } + return x instanceof WeakSet; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isElement(x) { + if (!x || typeof x !== 'object') { return false; } + if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { + return true; + } + return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function'; +} + +function inspectString(str, opts) { + if (str.length > opts.maxStringLength) { + var remaining = str.length - opts.maxStringLength; + var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : ''); + return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; + } + // eslint-disable-next-line no-control-regex + var s = $replace.call($replace.call(str, /(['\\])/g, '\\$1'), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s, 'single', opts); +} + +function lowbyte(c) { + var n = c.charCodeAt(0); + var x = { + 8: 'b', + 9: 't', + 10: 'n', + 12: 'f', + 13: 'r' + }[n]; + if (x) { return '\\' + x; } + return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16)); +} + +function markBoxed(str) { + return 'Object(' + str + ')'; +} + +function weakCollectionOf(type) { + return type + ' { ? }'; +} + +function collectionOf(type, size, entries, indent) { + var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', '); + return type + ' (' + size + ') {' + joinedEntries + '}'; +} + +function singleLineValues(xs) { + for (var i = 0; i < xs.length; i++) { + if (indexOf(xs[i], '\n') >= 0) { + return false; + } + } + return true; +} + +function getIndent(opts, depth) { + var baseIndent; + if (opts.indent === '\t') { + baseIndent = '\t'; + } else if (typeof opts.indent === 'number' && opts.indent > 0) { + baseIndent = $join.call(Array(opts.indent + 1), ' '); + } else { + return null; + } + return { + base: baseIndent, + prev: $join.call(Array(depth + 1), baseIndent) + }; +} + +function indentedJoin(xs, indent) { + if (xs.length === 0) { return ''; } + var lineJoiner = '\n' + indent.prev + indent.base; + return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev; +} + +function arrObjKeys(obj, inspect) { + var isArr = isArray(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i = 0; i < obj.length; i++) { + xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; + } + } + var syms = typeof gOPS === 'function' ? gOPS(obj) : []; + var symMap; + if (hasShammedSymbols) { + symMap = {}; + for (var k = 0; k < syms.length; k++) { + symMap['$' + syms[k]] = syms[k]; + } + } + + for (var key in obj) { // eslint-disable-line no-restricted-syntax + if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) { + // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section + continue; // eslint-disable-line no-restricted-syntax, no-continue + } else if ($test.call(/[^\w$]/, key)) { + xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); + } else { + xs.push(key + ': ' + inspect(obj[key], obj)); + } + } + if (typeof gOPS === 'function') { + for (var j = 0; j < syms.length; j++) { + if (isEnumerable.call(obj, syms[j])) { + xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj)); + } + } + } + return xs; +} diff --git a/node_modules/object-inspect/package-support.json b/node_modules/object-inspect/package-support.json new file mode 100644 index 000000000..5cc12d058 --- /dev/null +++ b/node_modules/object-inspect/package-support.json @@ -0,0 +1,20 @@ +{ + "versions": [ + { + "version": "*", + "target": { + "node": "all" + }, + "response": { + "type": "time-permitting" + }, + "backing": { + "npm-funding": true, + "donations": [ + "https://github.com/ljharb", + "https://tidelift.com/funding/github/npm/object-inspect" + ] + } + } + ] +} diff --git a/node_modules/object-inspect/package.json b/node_modules/object-inspect/package.json new file mode 100644 index 000000000..02de342ec --- /dev/null +++ b/node_modules/object-inspect/package.json @@ -0,0 +1,99 @@ +{ + "name": "object-inspect", + "version": "1.13.1", + "description": "string representations of objects in node and the browser", + "main": "index.js", + "sideEffects": false, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "@pkgjs/support": "^0.0.6", + "auto-changelog": "^2.4.0", + "core-js": "^2.6.12", + "error-cause": "^1.0.6", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "for-each": "^0.3.3", + "functions-have-names": "^1.2.3", + "glob": "=10.3.7", + "globalthis": "^1.0.3", + "has-tostringtag": "^1.0.0", + "in-publish": "^2.0.1", + "jackspeak": "=2.1.1", + "make-arrow-function": "^1.2.0", + "mock-property": "^1.0.2", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "string.prototype.repeat": "^1.0.0", + "tape": "^5.7.1" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "pretest": "npm run lint", + "lint": "eslint --ext=js,mjs .", + "postlint": "npx @pkgjs/support validate", + "test": "npm run tests-only && npm run test:corejs", + "tests-only": "nyc tape 'test/*.js'", + "test:corejs": "nyc tape test-core-js.js 'test/*.js'", + "posttest": "npx aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "testling": { + "files": [ + "test/*.js", + "test/browser/*.js" + ], + "browsers": [ + "ie/6..latest", + "chrome/latest", + "firefox/latest", + "safari/latest", + "opera/latest", + "iphone/latest", + "ipad/latest", + "android/latest" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/object-inspect.git" + }, + "homepage": "https://github.com/inspect-js/object-inspect", + "keywords": [ + "inspect", + "util.inspect", + "object", + "stringify", + "pretty" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "browser": { + "./util.inspect.js": false + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "./test-core-js.js" + ] + }, + "support": true +} diff --git a/node_modules/object-inspect/readme.markdown b/node_modules/object-inspect/readme.markdown new file mode 100644 index 000000000..9ff6bec36 --- /dev/null +++ b/node_modules/object-inspect/readme.markdown @@ -0,0 +1,86 @@ +# object-inspect [![Version Badge][2]][1] + +string representations of objects in node and the browser + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +# example + +## circular + +``` js +var inspect = require('object-inspect'); +var obj = { a: 1, b: [3,4] }; +obj.c = obj; +console.log(inspect(obj)); +``` + +## dom element + +``` js +var inspect = require('object-inspect'); + +var d = document.createElement('div'); +d.setAttribute('id', 'beep'); +d.innerHTML = 'woooiiiii'; + +console.log(inspect([ d, { a: 3, b : 4, c: [5,6,[7,[8,[9]]]] } ])); +``` + +output: + +``` +[
...
, { a: 3, b: 4, c: [ 5, 6, [ 7, [ 8, [ ... ] ] ] ] } ] +``` + +# methods + +``` js +var inspect = require('object-inspect') +``` + +## var s = inspect(obj, opts={}) + +Return a string `s` with the string representation of `obj` up to a depth of `opts.depth`. + +Additional options: + - `quoteStyle`: must be "single" or "double", if present. Default `'single'` for strings, `'double'` for HTML elements. + - `maxStringLength`: must be `0`, a positive integer, `Infinity`, or `null`, if present. Default `Infinity`. + - `customInspect`: When `true`, a custom inspect method function will be invoked (either undere the `util.inspect.custom` symbol, or the `inspect` property). When the string `'symbol'`, only the symbol method will be invoked. Default `true`. + - `indent`: must be "\t", `null`, or a positive integer. Default `null`. + - `numericSeparator`: must be a boolean, if present. Default `false`. If `true`, all numbers will be printed with numeric separators (eg, `1234.5678` will be printed as `'1_234.567_8'`) + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install object-inspect +``` + +# license + +MIT + +[1]: https://npmjs.org/package/object-inspect +[2]: https://versionbadg.es/inspect-js/object-inspect.svg +[5]: https://david-dm.org/inspect-js/object-inspect.svg +[6]: https://david-dm.org/inspect-js/object-inspect +[7]: https://david-dm.org/inspect-js/object-inspect/dev-status.svg +[8]: https://david-dm.org/inspect-js/object-inspect#info=devDependencies +[11]: https://nodei.co/npm/object-inspect.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/object-inspect.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/object-inspect.svg +[downloads-url]: https://npm-stat.com/charts.html?package=object-inspect +[codecov-image]: https://codecov.io/gh/inspect-js/object-inspect/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/object-inspect/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/object-inspect +[actions-url]: https://github.com/inspect-js/object-inspect/actions diff --git a/node_modules/object-inspect/test-core-js.js b/node_modules/object-inspect/test-core-js.js new file mode 100644 index 000000000..e53c40022 --- /dev/null +++ b/node_modules/object-inspect/test-core-js.js @@ -0,0 +1,26 @@ +'use strict'; + +require('core-js'); + +var inspect = require('./'); +var test = require('tape'); + +test('Maps', function (t) { + t.equal(inspect(new Map([[1, 2]])), 'Map (1) {1 => 2}'); + t.end(); +}); + +test('WeakMaps', function (t) { + t.equal(inspect(new WeakMap([[{}, 2]])), 'WeakMap { ? }'); + t.end(); +}); + +test('Sets', function (t) { + t.equal(inspect(new Set([[1, 2]])), 'Set (1) {[ 1, 2 ]}'); + t.end(); +}); + +test('WeakSets', function (t) { + t.equal(inspect(new WeakSet([[1, 2]])), 'WeakSet { ? }'); + t.end(); +}); diff --git a/node_modules/object-inspect/test/bigint.js b/node_modules/object-inspect/test/bigint.js new file mode 100644 index 000000000..4ecc31df8 --- /dev/null +++ b/node_modules/object-inspect/test/bigint.js @@ -0,0 +1,58 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); + +test('bigint', { skip: typeof BigInt === 'undefined' }, function (t) { + t.test('primitives', function (st) { + st.plan(3); + + st.equal(inspect(BigInt(-256)), '-256n'); + st.equal(inspect(BigInt(0)), '0n'); + st.equal(inspect(BigInt(256)), '256n'); + }); + + t.test('objects', function (st) { + st.plan(3); + + st.equal(inspect(Object(BigInt(-256))), 'Object(-256n)'); + st.equal(inspect(Object(BigInt(0))), 'Object(0n)'); + st.equal(inspect(Object(BigInt(256))), 'Object(256n)'); + }); + + t.test('syntactic primitives', function (st) { + st.plan(3); + + /* eslint-disable no-new-func */ + st.equal(inspect(Function('return -256n')()), '-256n'); + st.equal(inspect(Function('return 0n')()), '0n'); + st.equal(inspect(Function('return 256n')()), '256n'); + }); + + t.test('toStringTag', { skip: !hasToStringTag }, function (st) { + st.plan(1); + + var faker = {}; + faker[Symbol.toStringTag] = 'BigInt'; + st.equal( + inspect(faker), + '{ [Symbol(Symbol.toStringTag)]: \'BigInt\' }', + 'object lying about being a BigInt inspects as an object' + ); + }); + + t.test('numericSeparator', function (st) { + st.equal(inspect(BigInt(0), { numericSeparator: false }), '0n', '0n, numericSeparator false'); + st.equal(inspect(BigInt(0), { numericSeparator: true }), '0n', '0n, numericSeparator true'); + + st.equal(inspect(BigInt(1234), { numericSeparator: false }), '1234n', '1234n, numericSeparator false'); + st.equal(inspect(BigInt(1234), { numericSeparator: true }), '1_234n', '1234n, numericSeparator true'); + st.equal(inspect(BigInt(-1234), { numericSeparator: false }), '-1234n', '1234n, numericSeparator false'); + st.equal(inspect(BigInt(-1234), { numericSeparator: true }), '-1_234n', '1234n, numericSeparator true'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/browser/dom.js b/node_modules/object-inspect/test/browser/dom.js new file mode 100644 index 000000000..210c0b233 --- /dev/null +++ b/node_modules/object-inspect/test/browser/dom.js @@ -0,0 +1,15 @@ +var inspect = require('../../'); +var test = require('tape'); + +test('dom element', function (t) { + t.plan(1); + + var d = document.createElement('div'); + d.setAttribute('id', 'beep'); + d.innerHTML = 'woooiiiii'; + + t.equal( + inspect([d, { a: 3, b: 4, c: [5, 6, [7, [8, [9]]]] }]), + '[
...
, { a: 3, b: 4, c: [ 5, 6, [ 7, [ 8, [Object] ] ] ] } ]' + ); +}); diff --git a/node_modules/object-inspect/test/circular.js b/node_modules/object-inspect/test/circular.js new file mode 100644 index 000000000..5df4233cb --- /dev/null +++ b/node_modules/object-inspect/test/circular.js @@ -0,0 +1,16 @@ +var inspect = require('../'); +var test = require('tape'); + +test('circular', function (t) { + t.plan(2); + var obj = { a: 1, b: [3, 4] }; + obj.c = obj; + t.equal(inspect(obj), '{ a: 1, b: [ 3, 4 ], c: [Circular] }'); + + var double = {}; + double.a = [double]; + double.b = {}; + double.b.inner = double.b; + double.b.obj = double; + t.equal(inspect(double), '{ a: [ [Circular] ], b: { inner: [Circular], obj: [Circular] } }'); +}); diff --git a/node_modules/object-inspect/test/deep.js b/node_modules/object-inspect/test/deep.js new file mode 100644 index 000000000..99ce32a08 --- /dev/null +++ b/node_modules/object-inspect/test/deep.js @@ -0,0 +1,12 @@ +var inspect = require('../'); +var test = require('tape'); + +test('deep', function (t) { + t.plan(4); + var obj = [[[[[[500]]]]]]; + t.equal(inspect(obj), '[ [ [ [ [ [Array] ] ] ] ] ]'); + t.equal(inspect(obj, { depth: 4 }), '[ [ [ [ [Array] ] ] ] ]'); + t.equal(inspect(obj, { depth: 2 }), '[ [ [Array] ] ]'); + + t.equal(inspect([[[{ a: 1 }]]], { depth: 3 }), '[ [ [ [Object] ] ] ]'); +}); diff --git a/node_modules/object-inspect/test/element.js b/node_modules/object-inspect/test/element.js new file mode 100644 index 000000000..47fa9e240 --- /dev/null +++ b/node_modules/object-inspect/test/element.js @@ -0,0 +1,53 @@ +var inspect = require('../'); +var test = require('tape'); + +test('element', function (t) { + t.plan(3); + var elem = { + nodeName: 'div', + attributes: [{ name: 'class', value: 'row' }], + getAttribute: function (key) { return key; }, + childNodes: [] + }; + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); + t.deepEqual(inspect(obj, { quoteStyle: 'single' }), "[ 1,
, 3 ]"); + t.deepEqual(inspect(obj, { quoteStyle: 'double' }), '[ 1,
, 3 ]'); +}); + +test('element no attr', function (t) { + t.plan(1); + var elem = { + nodeName: 'div', + getAttribute: function (key) { return key; }, + childNodes: [] + }; + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); +}); + +test('element with contents', function (t) { + t.plan(1); + var elem = { + nodeName: 'div', + getAttribute: function (key) { return key; }, + childNodes: [{ nodeName: 'b' }] + }; + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
...
, 3 ]'); +}); + +test('element instance', function (t) { + t.plan(1); + var h = global.HTMLElement; + global.HTMLElement = function (name, attr) { + this.nodeName = name; + this.attributes = attr; + }; + global.HTMLElement.prototype.getAttribute = function () {}; + + var elem = new global.HTMLElement('div', []); + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); + global.HTMLElement = h; +}); diff --git a/node_modules/object-inspect/test/err.js b/node_modules/object-inspect/test/err.js new file mode 100644 index 000000000..cc1d884ab --- /dev/null +++ b/node_modules/object-inspect/test/err.js @@ -0,0 +1,48 @@ +var test = require('tape'); +var ErrorWithCause = require('error-cause/Error'); + +var inspect = require('../'); + +test('type error', function (t) { + t.plan(1); + var aerr = new TypeError(); + aerr.foo = 555; + aerr.bar = [1, 2, 3]; + + var berr = new TypeError('tuv'); + berr.baz = 555; + + var cerr = new SyntaxError(); + cerr.message = 'whoa'; + cerr['a-b'] = 5; + + var withCause = new ErrorWithCause('foo', { cause: 'bar' }); + var withCausePlus = new ErrorWithCause('foo', { cause: 'bar' }); + withCausePlus.foo = 'bar'; + var withUndefinedCause = new ErrorWithCause('foo', { cause: undefined }); + var withEnumerableCause = new Error('foo'); + withEnumerableCause.cause = 'bar'; + + var obj = [ + new TypeError(), + new TypeError('xxx'), + aerr, + berr, + cerr, + withCause, + withCausePlus, + withUndefinedCause, + withEnumerableCause + ]; + t.equal(inspect(obj), '[ ' + [ + '[TypeError]', + '[TypeError: xxx]', + '{ [TypeError] foo: 555, bar: [ 1, 2, 3 ] }', + '{ [TypeError: tuv] baz: 555 }', + '{ [SyntaxError: whoa] message: \'whoa\', \'a-b\': 5 }', + 'cause' in Error.prototype ? '[Error: foo]' : '{ [Error: foo] [cause]: \'bar\' }', + '{ [Error: foo] ' + ('cause' in Error.prototype ? '' : '[cause]: \'bar\', ') + 'foo: \'bar\' }', + 'cause' in Error.prototype ? '[Error: foo]' : '{ [Error: foo] [cause]: undefined }', + '{ [Error: foo] cause: \'bar\' }' + ].join(', ') + ' ]'); +}); diff --git a/node_modules/object-inspect/test/fakes.js b/node_modules/object-inspect/test/fakes.js new file mode 100644 index 000000000..a65c08c15 --- /dev/null +++ b/node_modules/object-inspect/test/fakes.js @@ -0,0 +1,29 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); +var forEach = require('for-each'); + +test('fakes', { skip: !hasToStringTag }, function (t) { + forEach([ + 'Array', + 'Boolean', + 'Date', + 'Error', + 'Number', + 'RegExp', + 'String' + ], function (expected) { + var faker = {}; + faker[Symbol.toStringTag] = expected; + + t.equal( + inspect(faker), + '{ [Symbol(Symbol.toStringTag)]: \'' + expected + '\' }', + 'faker masquerading as ' + expected + ' is not shown as one' + ); + }); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/fn.js b/node_modules/object-inspect/test/fn.js new file mode 100644 index 000000000..de3ca625e --- /dev/null +++ b/node_modules/object-inspect/test/fn.js @@ -0,0 +1,76 @@ +var inspect = require('../'); +var test = require('tape'); +var arrow = require('make-arrow-function')(); +var functionsHaveConfigurableNames = require('functions-have-names').functionsHaveConfigurableNames(); + +test('function', function (t) { + t.plan(1); + var obj = [1, 2, function f(n) { return n; }, 4]; + t.equal(inspect(obj), '[ 1, 2, [Function: f], 4 ]'); +}); + +test('function name', function (t) { + t.plan(1); + var f = (function () { + return function () {}; + }()); + f.toString = function toStr() { return 'function xxx () {}'; }; + var obj = [1, 2, f, 4]; + t.equal(inspect(obj), '[ 1, 2, [Function (anonymous)] { toString: [Function: toStr] }, 4 ]'); +}); + +test('anon function', function (t) { + var f = (function () { + return function () {}; + }()); + var obj = [1, 2, f, 4]; + t.equal(inspect(obj), '[ 1, 2, [Function (anonymous)], 4 ]'); + + t.end(); +}); + +test('arrow function', { skip: !arrow }, function (t) { + t.equal(inspect(arrow), '[Function (anonymous)]'); + + t.end(); +}); + +test('truly nameless function', { skip: !arrow || !functionsHaveConfigurableNames }, function (t) { + function f() {} + Object.defineProperty(f, 'name', { value: false }); + t.equal(f.name, false); + t.equal( + inspect(f), + '[Function: f]', + 'named function with falsy `.name` does not hide its original name' + ); + + function g() {} + Object.defineProperty(g, 'name', { value: true }); + t.equal(g.name, true); + t.equal( + inspect(g), + '[Function: true]', + 'named function with truthy `.name` hides its original name' + ); + + var anon = function () {}; // eslint-disable-line func-style + Object.defineProperty(anon, 'name', { value: null }); + t.equal(anon.name, null); + t.equal( + inspect(anon), + '[Function (anonymous)]', + 'anon function with falsy `.name` does not hide its anonymity' + ); + + var anon2 = function () {}; // eslint-disable-line func-style + Object.defineProperty(anon2, 'name', { value: 1 }); + t.equal(anon2.name, 1); + t.equal( + inspect(anon2), + '[Function: 1]', + 'anon function with truthy `.name` hides its anonymity' + ); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/global.js b/node_modules/object-inspect/test/global.js new file mode 100644 index 000000000..c57216aeb --- /dev/null +++ b/node_modules/object-inspect/test/global.js @@ -0,0 +1,17 @@ +'use strict'; + +var inspect = require('../'); + +var test = require('tape'); +var globalThis = require('globalthis')(); + +test('global object', function (t) { + /* eslint-env browser */ + var expected = typeof window === 'undefined' ? 'globalThis' : 'Window'; + t.equal( + inspect([globalThis]), + '[ { [object ' + expected + '] } ]' + ); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/has.js b/node_modules/object-inspect/test/has.js new file mode 100644 index 000000000..01800dee6 --- /dev/null +++ b/node_modules/object-inspect/test/has.js @@ -0,0 +1,15 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var mockProperty = require('mock-property'); + +test('when Object#hasOwnProperty is deleted', function (t) { + t.plan(1); + var arr = [1, , 3]; // eslint-disable-line no-sparse-arrays + + t.teardown(mockProperty(Array.prototype, 1, { value: 2 })); // this is needed to account for "in" vs "hasOwnProperty" + t.teardown(mockProperty(Object.prototype, 'hasOwnProperty', { 'delete': true })); + + t.equal(inspect(arr), '[ 1, , 3 ]'); +}); diff --git a/node_modules/object-inspect/test/holes.js b/node_modules/object-inspect/test/holes.js new file mode 100644 index 000000000..87fc8c84a --- /dev/null +++ b/node_modules/object-inspect/test/holes.js @@ -0,0 +1,15 @@ +var test = require('tape'); +var inspect = require('../'); + +var xs = ['a', 'b']; +xs[5] = 'f'; +xs[7] = 'j'; +xs[8] = 'k'; + +test('holes', function (t) { + t.plan(1); + t.equal( + inspect(xs), + "[ 'a', 'b', , , , 'f', , 'j', 'k' ]" + ); +}); diff --git a/node_modules/object-inspect/test/indent-option.js b/node_modules/object-inspect/test/indent-option.js new file mode 100644 index 000000000..89d8fcedf --- /dev/null +++ b/node_modules/object-inspect/test/indent-option.js @@ -0,0 +1,271 @@ +var test = require('tape'); +var forEach = require('for-each'); + +var inspect = require('../'); + +test('bad indent options', function (t) { + forEach([ + undefined, + true, + false, + -1, + 1.2, + Infinity, + -Infinity, + NaN + ], function (indent) { + t['throws']( + function () { inspect('', { indent: indent }); }, + TypeError, + inspect(indent) + ' is invalid' + ); + }); + + t.end(); +}); + +test('simple object with indent', function (t) { + t.plan(2); + + var obj = { a: 1, b: 2 }; + + var expectedSpaces = [ + '{', + ' a: 1,', + ' b: 2', + '}' + ].join('\n'); + var expectedTabs = [ + '{', + ' a: 1,', + ' b: 2', + '}' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('two deep object with indent', function (t) { + t.plan(2); + + var obj = { a: 1, b: { c: 3, d: 4 } }; + + var expectedSpaces = [ + '{', + ' a: 1,', + ' b: {', + ' c: 3,', + ' d: 4', + ' }', + '}' + ].join('\n'); + var expectedTabs = [ + '{', + ' a: 1,', + ' b: {', + ' c: 3,', + ' d: 4', + ' }', + '}' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('simple array with all single line elements', function (t) { + t.plan(2); + + var obj = [1, 2, 3, 'asdf\nsdf']; + + var expected = '[ 1, 2, 3, \'asdf\\nsdf\' ]'; + + t.equal(inspect(obj, { indent: 2 }), expected, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expected, 'tabs'); +}); + +test('array with complex elements', function (t) { + t.plan(2); + + var obj = [1, { a: 1, b: { c: 1 } }, 'asdf\nsdf']; + + var expectedSpaces = [ + '[', + ' 1,', + ' {', + ' a: 1,', + ' b: {', + ' c: 1', + ' }', + ' },', + ' \'asdf\\nsdf\'', + ']' + ].join('\n'); + var expectedTabs = [ + '[', + ' 1,', + ' {', + ' a: 1,', + ' b: {', + ' c: 1', + ' }', + ' },', + ' \'asdf\\nsdf\'', + ']' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('values', function (t) { + t.plan(2); + var obj = [{}, [], { 'a-b': 5 }]; + + var expectedSpaces = [ + '[', + ' {},', + ' [],', + ' {', + ' \'a-b\': 5', + ' }', + ']' + ].join('\n'); + var expectedTabs = [ + '[', + ' {},', + ' [],', + ' {', + ' \'a-b\': 5', + ' }', + ']' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('Map', { skip: typeof Map !== 'function' }, function (t) { + var map = new Map(); + map.set({ a: 1 }, ['b']); + map.set(3, NaN); + + var expectedStringSpaces = [ + 'Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + '}' + ].join('\n'); + var expectedStringTabs = [ + 'Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + '}' + ].join('\n'); + var expectedStringTabsDoubleQuotes = [ + 'Map (2) {', + ' { a: 1 } => [ "b" ],', + ' 3 => NaN', + '}' + ].join('\n'); + + t.equal( + inspect(map, { indent: 2 }), + expectedStringSpaces, + 'Map keys are not indented (two)' + ); + t.equal( + inspect(map, { indent: '\t' }), + expectedStringTabs, + 'Map keys are not indented (tabs)' + ); + t.equal( + inspect(map, { indent: '\t', quoteStyle: 'double' }), + expectedStringTabsDoubleQuotes, + 'Map keys are not indented (tabs + double quotes)' + ); + + t.equal(inspect(new Map(), { indent: 2 }), 'Map (0) {}', 'empty Map should show as empty (two)'); + t.equal(inspect(new Map(), { indent: '\t' }), 'Map (0) {}', 'empty Map should show as empty (tabs)'); + + var nestedMap = new Map(); + nestedMap.set(nestedMap, map); + var expectedNestedSpaces = [ + 'Map (1) {', + ' [Circular] => Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + ' }', + '}' + ].join('\n'); + var expectedNestedTabs = [ + 'Map (1) {', + ' [Circular] => Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + ' }', + '}' + ].join('\n'); + t.equal(inspect(nestedMap, { indent: 2 }), expectedNestedSpaces, 'Map containing a Map should work (two)'); + t.equal(inspect(nestedMap, { indent: '\t' }), expectedNestedTabs, 'Map containing a Map should work (tabs)'); + + t.end(); +}); + +test('Set', { skip: typeof Set !== 'function' }, function (t) { + var set = new Set(); + set.add({ a: 1 }); + set.add(['b']); + var expectedStringSpaces = [ + 'Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + '}' + ].join('\n'); + var expectedStringTabs = [ + 'Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + '}' + ].join('\n'); + t.equal(inspect(set, { indent: 2 }), expectedStringSpaces, 'new Set([{ a: 1 }, ["b"]]) should show size and contents (two)'); + t.equal(inspect(set, { indent: '\t' }), expectedStringTabs, 'new Set([{ a: 1 }, ["b"]]) should show size and contents (tabs)'); + + t.equal(inspect(new Set(), { indent: 2 }), 'Set (0) {}', 'empty Set should show as empty (two)'); + t.equal(inspect(new Set(), { indent: '\t' }), 'Set (0) {}', 'empty Set should show as empty (tabs)'); + + var nestedSet = new Set(); + nestedSet.add(set); + nestedSet.add(nestedSet); + var expectedNestedSpaces = [ + 'Set (2) {', + ' Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + ' },', + ' [Circular]', + '}' + ].join('\n'); + var expectedNestedTabs = [ + 'Set (2) {', + ' Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + ' },', + ' [Circular]', + '}' + ].join('\n'); + t.equal(inspect(nestedSet, { indent: 2 }), expectedNestedSpaces, 'Set containing a Set should work (two)'); + t.equal(inspect(nestedSet, { indent: '\t' }), expectedNestedTabs, 'Set containing a Set should work (tabs)'); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/inspect.js b/node_modules/object-inspect/test/inspect.js new file mode 100644 index 000000000..1abf81b1f --- /dev/null +++ b/node_modules/object-inspect/test/inspect.js @@ -0,0 +1,139 @@ +var test = require('tape'); +var hasSymbols = require('has-symbols/shams')(); +var utilInspect = require('../util.inspect'); +var repeat = require('string.prototype.repeat'); + +var inspect = require('..'); + +test('inspect', function (t) { + t.plan(5); + + var obj = [{ inspect: function xyzInspect() { return '!XYZ¡'; } }, []]; + var stringResult = '[ !XYZ¡, [] ]'; + var falseResult = '[ { inspect: [Function: xyzInspect] }, [] ]'; + + t.equal(inspect(obj), stringResult); + t.equal(inspect(obj, { customInspect: true }), stringResult); + t.equal(inspect(obj, { customInspect: 'symbol' }), falseResult); + t.equal(inspect(obj, { customInspect: false }), falseResult); + t['throws']( + function () { inspect(obj, { customInspect: 'not a boolean or "symbol"' }); }, + TypeError, + '`customInspect` must be a boolean or the string "symbol"' + ); +}); + +test('inspect custom symbol', { skip: !hasSymbols || !utilInspect || !utilInspect.custom }, function (t) { + t.plan(4); + + var obj = { inspect: function stringInspect() { return 'string'; } }; + obj[utilInspect.custom] = function custom() { return 'symbol'; }; + + var symbolResult = '[ symbol, [] ]'; + var stringResult = '[ string, [] ]'; + var falseResult = '[ { inspect: [Function: stringInspect]' + (utilInspect.custom ? ', [' + inspect(utilInspect.custom) + ']: [Function: custom]' : '') + ' }, [] ]'; + + var symbolStringFallback = utilInspect.custom ? symbolResult : stringResult; + var symbolFalseFallback = utilInspect.custom ? symbolResult : falseResult; + + t.equal(inspect([obj, []]), symbolStringFallback); + t.equal(inspect([obj, []], { customInspect: true }), symbolStringFallback); + t.equal(inspect([obj, []], { customInspect: 'symbol' }), symbolFalseFallback); + t.equal(inspect([obj, []], { customInspect: false }), falseResult); +}); + +test('symbols', { skip: !hasSymbols }, function (t) { + t.plan(2); + + var obj = { a: 1 }; + obj[Symbol('test')] = 2; + obj[Symbol.iterator] = 3; + Object.defineProperty(obj, Symbol('non-enum'), { + enumerable: false, + value: 4 + }); + + if (typeof Symbol.iterator === 'symbol') { + t.equal(inspect(obj), '{ a: 1, [Symbol(test)]: 2, [Symbol(Symbol.iterator)]: 3 }', 'object with symbols'); + t.equal(inspect([obj, []]), '[ { a: 1, [Symbol(test)]: 2, [Symbol(Symbol.iterator)]: 3 }, [] ]', 'object with symbols in array'); + } else { + // symbol sham key ordering is unreliable + t.match( + inspect(obj), + /^(?:{ a: 1, \[Symbol\(test\)\]: 2, \[Symbol\(Symbol.iterator\)\]: 3 }|{ a: 1, \[Symbol\(Symbol.iterator\)\]: 3, \[Symbol\(test\)\]: 2 })$/, + 'object with symbols (nondeterministic symbol sham key ordering)' + ); + t.match( + inspect([obj, []]), + /^\[ (?:{ a: 1, \[Symbol\(test\)\]: 2, \[Symbol\(Symbol.iterator\)\]: 3 }|{ a: 1, \[Symbol\(Symbol.iterator\)\]: 3, \[Symbol\(test\)\]: 2 }), \[\] \]$/, + 'object with symbols in array (nondeterministic symbol sham key ordering)' + ); + } +}); + +test('maxStringLength', function (t) { + t['throws']( + function () { inspect('', { maxStringLength: -1 }); }, + TypeError, + 'maxStringLength must be >= 0, or Infinity, not negative' + ); + + var str = repeat('a', 1e8); + + t.equal( + inspect([str], { maxStringLength: 10 }), + '[ \'aaaaaaaaaa\'... 99999990 more characters ]', + 'maxStringLength option limits output' + ); + + t.equal( + inspect(['f'], { maxStringLength: null }), + '[ \'\'... 1 more character ]', + 'maxStringLength option accepts `null`' + ); + + t.equal( + inspect([str], { maxStringLength: Infinity }), + '[ \'' + str + '\' ]', + 'maxStringLength option accepts ∞' + ); + + t.end(); +}); + +test('inspect options', { skip: !utilInspect.custom }, function (t) { + var obj = {}; + obj[utilInspect.custom] = function () { + return JSON.stringify(arguments); + }; + t.equal( + inspect(obj), + utilInspect(obj, { depth: 5 }), + 'custom symbols will use node\'s inspect' + ); + t.equal( + inspect(obj, { depth: 2 }), + utilInspect(obj, { depth: 2 }), + 'a reduced depth will be passed to node\'s inspect' + ); + t.equal( + inspect({ d1: obj }, { depth: 3 }), + '{ d1: ' + utilInspect(obj, { depth: 2 }) + ' }', + 'deep objects will receive a reduced depth' + ); + t.equal( + inspect({ d1: obj }, { depth: 1 }), + '{ d1: [Object] }', + 'unlike nodejs inspect, customInspect will not be used once the depth is exceeded.' + ); + t.end(); +}); + +test('inspect URL', { skip: typeof URL === 'undefined' }, function (t) { + t.match( + inspect(new URL('https://nodejs.org')), + /nodejs\.org/, // Different environments stringify it differently + 'url can be inspected' + ); + t.end(); +}); diff --git a/node_modules/object-inspect/test/lowbyte.js b/node_modules/object-inspect/test/lowbyte.js new file mode 100644 index 000000000..68a345d85 --- /dev/null +++ b/node_modules/object-inspect/test/lowbyte.js @@ -0,0 +1,12 @@ +var test = require('tape'); +var inspect = require('../'); + +var obj = { x: 'a\r\nb', y: '\x05! \x1f \x12' }; + +test('interpolate low bytes', function (t) { + t.plan(1); + t.equal( + inspect(obj), + "{ x: 'a\\r\\nb', y: '\\x05! \\x1F \\x12' }" + ); +}); diff --git a/node_modules/object-inspect/test/number.js b/node_modules/object-inspect/test/number.js new file mode 100644 index 000000000..8f287e8e2 --- /dev/null +++ b/node_modules/object-inspect/test/number.js @@ -0,0 +1,58 @@ +var test = require('tape'); +var v = require('es-value-fixtures'); +var forEach = require('for-each'); + +var inspect = require('../'); + +test('negative zero', function (t) { + t.equal(inspect(0), '0', 'inspect(0) === "0"'); + t.equal(inspect(Object(0)), 'Object(0)', 'inspect(Object(0)) === "Object(0)"'); + + t.equal(inspect(-0), '-0', 'inspect(-0) === "-0"'); + t.equal(inspect(Object(-0)), 'Object(-0)', 'inspect(Object(-0)) === "Object(-0)"'); + + t.end(); +}); + +test('numericSeparator', function (t) { + forEach(v.nonBooleans, function (nonBoolean) { + t['throws']( + function () { inspect(true, { numericSeparator: nonBoolean }); }, + TypeError, + inspect(nonBoolean) + ' is not a boolean' + ); + }); + + t.test('3 digit numbers', function (st) { + var failed = false; + for (var i = -999; i < 1000; i += 1) { + var actual = inspect(i); + var actualSepNo = inspect(i, { numericSeparator: false }); + var actualSepYes = inspect(i, { numericSeparator: true }); + var expected = String(i); + if (actual !== expected || actualSepNo !== expected || actualSepYes !== expected) { + failed = true; + t.equal(actual, expected); + t.equal(actualSepNo, expected); + t.equal(actualSepYes, expected); + } + } + + st.notOk(failed, 'all 3 digit numbers passed'); + + st.end(); + }); + + t.equal(inspect(1e3), '1000', '1000'); + t.equal(inspect(1e3, { numericSeparator: false }), '1000', '1000, numericSeparator false'); + t.equal(inspect(1e3, { numericSeparator: true }), '1_000', '1000, numericSeparator true'); + t.equal(inspect(-1e3), '-1000', '-1000'); + t.equal(inspect(-1e3, { numericSeparator: false }), '-1000', '-1000, numericSeparator false'); + t.equal(inspect(-1e3, { numericSeparator: true }), '-1_000', '-1000, numericSeparator true'); + + t.equal(inspect(1234.5678, { numericSeparator: true }), '1_234.567_8', 'fractional numbers get separators'); + t.equal(inspect(1234.56789, { numericSeparator: true }), '1_234.567_89', 'fractional numbers get separators'); + t.equal(inspect(1234.567891, { numericSeparator: true }), '1_234.567_891', 'fractional numbers get separators'); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/quoteStyle.js b/node_modules/object-inspect/test/quoteStyle.js new file mode 100644 index 000000000..ae4d734bf --- /dev/null +++ b/node_modules/object-inspect/test/quoteStyle.js @@ -0,0 +1,17 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); + +test('quoteStyle option', function (t) { + t['throws'](function () { inspect(null, { quoteStyle: false }); }, 'false is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: true }); }, 'true is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: '' }); }, '"" is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: {} }); }, '{} is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: [] }); }, '[] is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: 42 }); }, '42 is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: NaN }); }, 'NaN is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: function () {} }); }, 'a function is not a valid value'); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/toStringTag.js b/node_modules/object-inspect/test/toStringTag.js new file mode 100644 index 000000000..95f82703d --- /dev/null +++ b/node_modules/object-inspect/test/toStringTag.js @@ -0,0 +1,40 @@ +'use strict'; + +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); + +var inspect = require('../'); + +test('Symbol.toStringTag', { skip: !hasToStringTag }, function (t) { + t.plan(4); + + var obj = { a: 1 }; + t.equal(inspect(obj), '{ a: 1 }', 'object, no Symbol.toStringTag'); + + obj[Symbol.toStringTag] = 'foo'; + t.equal(inspect(obj), '{ a: 1, [Symbol(Symbol.toStringTag)]: \'foo\' }', 'object with Symbol.toStringTag'); + + t.test('null objects', { skip: 'toString' in { __proto__: null } }, function (st) { + st.plan(2); + + var dict = { __proto__: null, a: 1 }; + st.equal(inspect(dict), '[Object: null prototype] { a: 1 }', 'null object with Symbol.toStringTag'); + + dict[Symbol.toStringTag] = 'Dict'; + st.equal(inspect(dict), '[Dict: null prototype] { a: 1, [Symbol(Symbol.toStringTag)]: \'Dict\' }', 'null object with Symbol.toStringTag'); + }); + + t.test('instances', function (st) { + st.plan(4); + + function C() { + this.a = 1; + } + st.equal(Object.prototype.toString.call(new C()), '[object Object]', 'instance, no toStringTag, Object.prototype.toString'); + st.equal(inspect(new C()), 'C { a: 1 }', 'instance, no toStringTag'); + + C.prototype[Symbol.toStringTag] = 'Class!'; + st.equal(Object.prototype.toString.call(new C()), '[object Class!]', 'instance, with toStringTag, Object.prototype.toString'); + st.equal(inspect(new C()), 'C [Class!] { a: 1 }', 'instance, with toStringTag'); + }); +}); diff --git a/node_modules/object-inspect/test/undef.js b/node_modules/object-inspect/test/undef.js new file mode 100644 index 000000000..e3f496122 --- /dev/null +++ b/node_modules/object-inspect/test/undef.js @@ -0,0 +1,12 @@ +var test = require('tape'); +var inspect = require('../'); + +var obj = { a: 1, b: [3, 4, undefined, null], c: undefined, d: null }; + +test('undef and null', function (t) { + t.plan(1); + t.equal( + inspect(obj), + '{ a: 1, b: [ 3, 4, undefined, null ], c: undefined, d: null }' + ); +}); diff --git a/node_modules/object-inspect/test/values.js b/node_modules/object-inspect/test/values.js new file mode 100644 index 000000000..4832b9fe9 --- /dev/null +++ b/node_modules/object-inspect/test/values.js @@ -0,0 +1,211 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var mockProperty = require('mock-property'); +var hasSymbols = require('has-symbols/shams')(); +var hasToStringTag = require('has-tostringtag/shams')(); + +test('values', function (t) { + t.plan(1); + var obj = [{}, [], { 'a-b': 5 }]; + t.equal(inspect(obj), '[ {}, [], { \'a-b\': 5 } ]'); +}); + +test('arrays with properties', function (t) { + t.plan(1); + var arr = [3]; + arr.foo = 'bar'; + var obj = [1, 2, arr]; + obj.baz = 'quux'; + obj.index = -1; + t.equal(inspect(obj), '[ 1, 2, [ 3, foo: \'bar\' ], baz: \'quux\', index: -1 ]'); +}); + +test('has', function (t) { + t.plan(1); + t.teardown(mockProperty(Object.prototype, 'hasOwnProperty', { 'delete': true })); + + t.equal(inspect({ a: 1, b: 2 }), '{ a: 1, b: 2 }'); +}); + +test('indexOf seen', function (t) { + t.plan(1); + var xs = [1, 2, 3, {}]; + xs.push(xs); + + var seen = []; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[ 1, 2, 3, {}, [Circular] ]' + ); +}); + +test('seen seen', function (t) { + t.plan(1); + var xs = [1, 2, 3]; + + var seen = [xs]; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[Circular]' + ); +}); + +test('seen seen seen', function (t) { + t.plan(1); + var xs = [1, 2, 3]; + + var seen = [5, xs]; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[Circular]' + ); +}); + +test('symbols', { skip: !hasSymbols }, function (t) { + var sym = Symbol('foo'); + t.equal(inspect(sym), 'Symbol(foo)', 'Symbol("foo") should be "Symbol(foo)"'); + if (typeof sym === 'symbol') { + // Symbol shams are incapable of differentiating boxed from unboxed symbols + t.equal(inspect(Object(sym)), 'Object(Symbol(foo))', 'Object(Symbol("foo")) should be "Object(Symbol(foo))"'); + } + + t.test('toStringTag', { skip: !hasToStringTag }, function (st) { + st.plan(1); + + var faker = {}; + faker[Symbol.toStringTag] = 'Symbol'; + st.equal( + inspect(faker), + '{ [Symbol(Symbol.toStringTag)]: \'Symbol\' }', + 'object lying about being a Symbol inspects as an object' + ); + }); + + t.end(); +}); + +test('Map', { skip: typeof Map !== 'function' }, function (t) { + var map = new Map(); + map.set({ a: 1 }, ['b']); + map.set(3, NaN); + var expectedString = 'Map (2) {' + inspect({ a: 1 }) + ' => ' + inspect(['b']) + ', 3 => NaN}'; + t.equal(inspect(map), expectedString, 'new Map([[{ a: 1 }, ["b"]], [3, NaN]]) should show size and contents'); + t.equal(inspect(new Map()), 'Map (0) {}', 'empty Map should show as empty'); + + var nestedMap = new Map(); + nestedMap.set(nestedMap, map); + t.equal(inspect(nestedMap), 'Map (1) {[Circular] => ' + expectedString + '}', 'Map containing a Map should work'); + + t.end(); +}); + +test('WeakMap', { skip: typeof WeakMap !== 'function' }, function (t) { + var map = new WeakMap(); + map.set({ a: 1 }, ['b']); + var expectedString = 'WeakMap { ? }'; + t.equal(inspect(map), expectedString, 'new WeakMap([[{ a: 1 }, ["b"]]]) should not show size or contents'); + t.equal(inspect(new WeakMap()), 'WeakMap { ? }', 'empty WeakMap should not show as empty'); + + t.end(); +}); + +test('Set', { skip: typeof Set !== 'function' }, function (t) { + var set = new Set(); + set.add({ a: 1 }); + set.add(['b']); + var expectedString = 'Set (2) {' + inspect({ a: 1 }) + ', ' + inspect(['b']) + '}'; + t.equal(inspect(set), expectedString, 'new Set([{ a: 1 }, ["b"]]) should show size and contents'); + t.equal(inspect(new Set()), 'Set (0) {}', 'empty Set should show as empty'); + + var nestedSet = new Set(); + nestedSet.add(set); + nestedSet.add(nestedSet); + t.equal(inspect(nestedSet), 'Set (2) {' + expectedString + ', [Circular]}', 'Set containing a Set should work'); + + t.end(); +}); + +test('WeakSet', { skip: typeof WeakSet !== 'function' }, function (t) { + var map = new WeakSet(); + map.add({ a: 1 }); + var expectedString = 'WeakSet { ? }'; + t.equal(inspect(map), expectedString, 'new WeakSet([{ a: 1 }]) should not show size or contents'); + t.equal(inspect(new WeakSet()), 'WeakSet { ? }', 'empty WeakSet should not show as empty'); + + t.end(); +}); + +test('WeakRef', { skip: typeof WeakRef !== 'function' }, function (t) { + var ref = new WeakRef({ a: 1 }); + var expectedString = 'WeakRef { ? }'; + t.equal(inspect(ref), expectedString, 'new WeakRef({ a: 1 }) should not show contents'); + + t.end(); +}); + +test('FinalizationRegistry', { skip: typeof FinalizationRegistry !== 'function' }, function (t) { + var registry = new FinalizationRegistry(function () {}); + var expectedString = 'FinalizationRegistry [FinalizationRegistry] {}'; + t.equal(inspect(registry), expectedString, 'new FinalizationRegistry(function () {}) should work normallys'); + + t.end(); +}); + +test('Strings', function (t) { + var str = 'abc'; + + t.equal(inspect(str), "'" + str + "'", 'primitive string shows as such'); + t.equal(inspect(str, { quoteStyle: 'single' }), "'" + str + "'", 'primitive string shows as such, single quoted'); + t.equal(inspect(str, { quoteStyle: 'double' }), '"' + str + '"', 'primitive string shows as such, double quoted'); + t.equal(inspect(Object(str)), 'Object(' + inspect(str) + ')', 'String object shows as such'); + t.equal(inspect(Object(str), { quoteStyle: 'single' }), 'Object(' + inspect(str, { quoteStyle: 'single' }) + ')', 'String object shows as such, single quoted'); + t.equal(inspect(Object(str), { quoteStyle: 'double' }), 'Object(' + inspect(str, { quoteStyle: 'double' }) + ')', 'String object shows as such, double quoted'); + + t.end(); +}); + +test('Numbers', function (t) { + var num = 42; + + t.equal(inspect(num), String(num), 'primitive number shows as such'); + t.equal(inspect(Object(num)), 'Object(' + inspect(num) + ')', 'Number object shows as such'); + + t.end(); +}); + +test('Booleans', function (t) { + t.equal(inspect(true), String(true), 'primitive true shows as such'); + t.equal(inspect(Object(true)), 'Object(' + inspect(true) + ')', 'Boolean object true shows as such'); + + t.equal(inspect(false), String(false), 'primitive false shows as such'); + t.equal(inspect(Object(false)), 'Object(' + inspect(false) + ')', 'Boolean false object shows as such'); + + t.end(); +}); + +test('Date', function (t) { + var now = new Date(); + t.equal(inspect(now), String(now), 'Date shows properly'); + t.equal(inspect(new Date(NaN)), 'Invalid Date', 'Invalid Date shows properly'); + + t.end(); +}); + +test('RegExps', function (t) { + t.equal(inspect(/a/g), '/a/g', 'regex shows properly'); + t.equal(inspect(new RegExp('abc', 'i')), '/abc/i', 'new RegExp shows properly'); + + var match = 'abc abc'.match(/[ab]+/); + delete match.groups; // for node < 10 + t.equal(inspect(match), '[ \'ab\', index: 0, input: \'abc abc\' ]', 'RegExp match object shows properly'); + + t.end(); +}); diff --git a/node_modules/object-inspect/util.inspect.js b/node_modules/object-inspect/util.inspect.js new file mode 100644 index 000000000..7784fab55 --- /dev/null +++ b/node_modules/object-inspect/util.inspect.js @@ -0,0 +1 @@ +module.exports = require('util').inspect; diff --git a/node_modules/pify/index.js b/node_modules/pify/index.js new file mode 100644 index 000000000..df56221d9 --- /dev/null +++ b/node_modules/pify/index.js @@ -0,0 +1,68 @@ +'use strict'; + +const processFn = (fn, options) => function (...args) { + const P = options.promiseModule; + + return new P((resolve, reject) => { + if (options.multiArgs) { + args.push((...result) => { + if (options.errorFirst) { + if (result[0]) { + reject(result); + } else { + result.shift(); + resolve(result); + } + } else { + resolve(result); + } + }); + } else if (options.errorFirst) { + args.push((error, result) => { + if (error) { + reject(error); + } else { + resolve(result); + } + }); + } else { + args.push(resolve); + } + + fn.apply(this, args); + }); +}; + +module.exports = (input, options) => { + options = Object.assign({ + exclude: [/.+(Sync|Stream)$/], + errorFirst: true, + promiseModule: Promise + }, options); + + const objType = typeof input; + if (!(input !== null && (objType === 'object' || objType === 'function'))) { + throw new TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${input === null ? 'null' : objType}\``); + } + + const filter = key => { + const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key); + return options.include ? options.include.some(match) : !options.exclude.some(match); + }; + + let ret; + if (objType === 'function') { + ret = function (...args) { + return options.excludeMain ? input(...args) : processFn(input, options).apply(this, args); + }; + } else { + ret = Object.create(Object.getPrototypeOf(input)); + } + + for (const key in input) { // eslint-disable-line guard-for-in + const property = input[key]; + ret[key] = typeof property === 'function' && filter(key) ? processFn(property, options) : property; + } + + return ret; +}; diff --git a/node_modules/pify/license b/node_modules/pify/license new file mode 100644 index 000000000..e7af2f771 --- /dev/null +++ b/node_modules/pify/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/pify/package.json b/node_modules/pify/package.json new file mode 100644 index 000000000..a5468cd29 --- /dev/null +++ b/node_modules/pify/package.json @@ -0,0 +1,51 @@ +{ + "name": "pify", + "version": "4.0.1", + "description": "Promisify a callback-style function", + "license": "MIT", + "repository": "sindresorhus/pify", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava", + "optimization-test": "node --allow-natives-syntax optimization-test.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "promise", + "promises", + "promisify", + "all", + "denodify", + "denodeify", + "callback", + "cb", + "node", + "then", + "thenify", + "convert", + "transform", + "wrap", + "wrapper", + "bind", + "to", + "async", + "await", + "es2015", + "bluebird" + ], + "devDependencies": { + "ava": "^0.25.0", + "pinkie-promise": "^2.0.0", + "v8-natives": "^1.1.0", + "xo": "^0.23.0" + } +} diff --git a/node_modules/pify/readme.md b/node_modules/pify/readme.md new file mode 100644 index 000000000..7ae3f1c56 --- /dev/null +++ b/node_modules/pify/readme.md @@ -0,0 +1,145 @@ +# pify [![Build Status](https://travis-ci.org/sindresorhus/pify.svg?branch=master)](https://travis-ci.org/sindresorhus/pify) + +> Promisify a callback-style function + +--- + +
+ + Get professional support for 'pify' with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +--- + + +## Install + +``` +$ npm install pify +``` + + +## Usage + +```js +const fs = require('fs'); +const pify = require('pify'); + +// Promisify a single function +pify(fs.readFile)('package.json', 'utf8').then(data => { + console.log(JSON.parse(data).name); + //=> 'pify' +}); + +// Promisify all methods in a module +pify(fs).readFile('package.json', 'utf8').then(data => { + console.log(JSON.parse(data).name); + //=> 'pify' +}); +``` + + +## API + +### pify(input, [options]) + +Returns a `Promise` wrapped version of the supplied function or module. + +#### input + +Type: `Function` `Object` + +Callback-style function or module whose methods you want to promisify. + +#### options + +##### multiArgs + +Type: `boolean`
+Default: `false` + +By default, the promisified function will only return the second argument from the callback, which works fine for most APIs. This option can be useful for modules like `request` that return multiple arguments. Turning this on will make it return an array of all arguments from the callback, excluding the error argument, instead of just the second argument. This also applies to rejections, where it returns an array of all the callback arguments, including the error. + +```js +const request = require('request'); +const pify = require('pify'); + +pify(request, {multiArgs: true})('https://sindresorhus.com').then(result => { + const [httpResponse, body] = result; +}); +``` + +##### include + +Type: `string[]` `RegExp[]` + +Methods in a module to promisify. Remaining methods will be left untouched. + +##### exclude + +Type: `string[]` `RegExp[]`
+Default: `[/.+(Sync|Stream)$/]` + +Methods in a module **not** to promisify. Methods with names ending with `'Sync'` are excluded by default. + +##### excludeMain + +Type: `boolean`
+Default: `false` + +If given module is a function itself, it will be promisified. Turn this option on if you want to promisify only methods of the module. + +```js +const pify = require('pify'); + +function fn() { + return true; +} + +fn.method = (data, callback) => { + setImmediate(() => { + callback(null, data); + }); +}; + +// Promisify methods but not `fn()` +const promiseFn = pify(fn, {excludeMain: true}); + +if (promiseFn()) { + promiseFn.method('hi').then(data => { + console.log(data); + }); +} +``` + +##### errorFirst + +Type: `boolean`
+Default: `true` + +Whether the callback has an error as the first argument. You'll want to set this to `false` if you're dealing with an API that doesn't have an error as the first argument, like `fs.exists()`, some browser APIs, Chrome Extension APIs, etc. + +##### promiseModule + +Type: `Function` + +Custom promise module to use instead of the native one. + +Check out [`pinkie-promise`](https://github.com/floatdrop/pinkie-promise) if you need a tiny promise polyfill. + + +## Related + +- [p-event](https://github.com/sindresorhus/p-event) - Promisify an event by waiting for it to be emitted +- [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently +- [More…](https://github.com/sindresorhus/promise-fun) + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/readable-stream/CONTRIBUTING.md b/node_modules/readable-stream/CONTRIBUTING.md new file mode 100644 index 000000000..f478d58dc --- /dev/null +++ b/node_modules/readable-stream/CONTRIBUTING.md @@ -0,0 +1,38 @@ +# Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +* (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +* (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +* (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +* (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. + +## Moderation Policy + +The [Node.js Moderation Policy] applies to this WG. + +## Code of Conduct + +The [Node.js Code of Conduct][] applies to this WG. + +[Node.js Code of Conduct]: +https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md +[Node.js Moderation Policy]: +https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md diff --git a/node_modules/readable-stream/GOVERNANCE.md b/node_modules/readable-stream/GOVERNANCE.md new file mode 100644 index 000000000..16ffb93f2 --- /dev/null +++ b/node_modules/readable-stream/GOVERNANCE.md @@ -0,0 +1,136 @@ +### Streams Working Group + +The Node.js Streams is jointly governed by a Working Group +(WG) +that is responsible for high-level guidance of the project. + +The WG has final authority over this project including: + +* Technical direction +* Project governance and process (including this policy) +* Contribution policy +* GitHub repository hosting +* Conduct guidelines +* Maintaining the list of additional Collaborators + +For the current list of WG members, see the project +[README.md](./README.md#current-project-team-members). + +### Collaborators + +The readable-stream GitHub repository is +maintained by the WG and additional Collaborators who are added by the +WG on an ongoing basis. + +Individuals making significant and valuable contributions are made +Collaborators and given commit-access to the project. These +individuals are identified by the WG and their addition as +Collaborators is discussed during the WG meeting. + +_Note:_ If you make a significant contribution and are not considered +for commit-access log an issue or contact a WG member directly and it +will be brought up in the next WG meeting. + +Modifications of the contents of the readable-stream repository are +made on +a collaborative basis. Anybody with a GitHub account may propose a +modification via pull request and it will be considered by the project +Collaborators. All pull requests must be reviewed and accepted by a +Collaborator with sufficient expertise who is able to take full +responsibility for the change. In the case of pull requests proposed +by an existing Collaborator, an additional Collaborator is required +for sign-off. Consensus should be sought if additional Collaborators +participate and there is disagreement around a particular +modification. See _Consensus Seeking Process_ below for further detail +on the consensus model used for governance. + +Collaborators may opt to elevate significant or controversial +modifications, or modifications that have not found consensus to the +WG for discussion by assigning the ***WG-agenda*** tag to a pull +request or issue. The WG should serve as the final arbiter where +required. + +For the current list of Collaborators, see the project +[README.md](./README.md#members). + +### WG Membership + +WG seats are not time-limited. There is no fixed size of the WG. +However, the expected target is between 6 and 12, to ensure adequate +coverage of important areas of expertise, balanced with the ability to +make decisions efficiently. + +There is no specific set of requirements or qualifications for WG +membership beyond these rules. + +The WG may add additional members to the WG by unanimous consensus. + +A WG member may be removed from the WG by voluntary resignation, or by +unanimous consensus of all other WG members. + +Changes to WG membership should be posted in the agenda, and may be +suggested as any other agenda item (see "WG Meetings" below). + +If an addition or removal is proposed during a meeting, and the full +WG is not in attendance to participate, then the addition or removal +is added to the agenda for the subsequent meeting. This is to ensure +that all members are given the opportunity to participate in all +membership decisions. If a WG member is unable to attend a meeting +where a planned membership decision is being made, then their consent +is assumed. + +No more than 1/3 of the WG members may be affiliated with the same +employer. If removal or resignation of a WG member, or a change of +employment by a WG member, creates a situation where more than 1/3 of +the WG membership shares an employer, then the situation must be +immediately remedied by the resignation or removal of one or more WG +members affiliated with the over-represented employer(s). + +### WG Meetings + +The WG meets occasionally on a Google Hangout On Air. A designated moderator +approved by the WG runs the meeting. Each meeting should be +published to YouTube. + +Items are added to the WG agenda that are considered contentious or +are modifications of governance, contribution policy, WG membership, +or release process. + +The intention of the agenda is not to approve or review all patches; +that should happen continuously on GitHub and be handled by the larger +group of Collaborators. + +Any community member or contributor can ask that something be added to +the next meeting's agenda by logging a GitHub Issue. Any Collaborator, +WG member or the moderator can add the item to the agenda by adding +the ***WG-agenda*** tag to the issue. + +Prior to each WG meeting the moderator will share the Agenda with +members of the WG. WG members can add any items they like to the +agenda at the beginning of each meeting. The moderator and the WG +cannot veto or remove items. + +The WG may invite persons or representatives from certain projects to +participate in a non-voting capacity. + +The moderator is responsible for summarizing the discussion of each +agenda item and sends it as a pull request after the meeting. + +### Consensus Seeking Process + +The WG follows a +[Consensus +Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) +decision-making model. + +When an agenda item has appeared to reach a consensus the moderator +will ask "Does anyone object?" as a final call for dissent from the +consensus. + +If an agenda item cannot reach a consensus a WG member can call for +either a closing vote or a vote to table the issue to the next +meeting. The call for a vote must be seconded by a majority of the WG +or else the discussion will continue. Simple majority wins. + +Note that changes to WG membership require a majority consensus. See +"WG Membership" above. diff --git a/node_modules/readable-stream/LICENSE b/node_modules/readable-stream/LICENSE new file mode 100644 index 000000000..2873b3b2e --- /dev/null +++ b/node_modules/readable-stream/LICENSE @@ -0,0 +1,47 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" diff --git a/node_modules/readable-stream/README.md b/node_modules/readable-stream/README.md new file mode 100644 index 000000000..19117c1a0 --- /dev/null +++ b/node_modules/readable-stream/README.md @@ -0,0 +1,106 @@ +# readable-stream + +***Node.js core streams for userland*** [![Build Status](https://travis-ci.com/nodejs/readable-stream.svg?branch=master)](https://travis-ci.com/nodejs/readable-stream) + + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) + + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/readabe-stream.svg)](https://saucelabs.com/u/readabe-stream) + +```bash +npm install --save readable-stream +``` + +This package is a mirror of the streams implementations in Node.js. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.18.1/docs/api/stream.html). + +If you want to guarantee a stable streams base, regardless of what version of +Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). + +As of version 2.0.0 **readable-stream** uses semantic versioning. + +## Version 3.x.x + +v3.x.x of `readable-stream` is a cut from Node 10. This version supports Node 6, 8, and 10, as well as evergreen browsers, IE 11 and latest Safari. The breaking changes introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows: + +1. Error codes: https://github.com/nodejs/node/pull/13310, + https://github.com/nodejs/node/pull/13291, + https://github.com/nodejs/node/pull/16589, + https://github.com/nodejs/node/pull/15042, + https://github.com/nodejs/node/pull/15665, + https://github.com/nodejs/readable-stream/pull/344 +2. 'readable' have precedence over flowing + https://github.com/nodejs/node/pull/18994 +3. make virtual methods errors consistent + https://github.com/nodejs/node/pull/18813 +4. updated streams error handling + https://github.com/nodejs/node/pull/18438 +5. writable.end should return this. + https://github.com/nodejs/node/pull/18780 +6. readable continues to read when push('') + https://github.com/nodejs/node/pull/18211 +7. add custom inspect to BufferList + https://github.com/nodejs/node/pull/17907 +8. always defer 'readable' with nextTick + https://github.com/nodejs/node/pull/17979 + +## Version 2.x.x +v2.x.x of `readable-stream` is a cut of the stream module from Node 8 (there have been no semver-major changes from Node 4 to 8). This version supports all Node.js versions from 0.8, as well as evergreen browsers and IE 10 & 11. + +### Big Thanks + +Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce] + +# Usage + +You can swap your `require('stream')` with `require('readable-stream')` +without any changes, if you are just using one of the main classes and +functions. + +```js +const { + Readable, + Writable, + Transform, + Duplex, + pipeline, + finished +} = require('readable-stream') +```` + +Note that `require('stream')` will return `Stream`, while +`require('readable-stream')` will return `Readable`. We discourage using +whatever is exported directly, but rather use one of the properties as +shown in the example above. + +# Streams Working Group + +`readable-stream` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + + +## Team Members + +* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <calvin.metcalf@gmail.com> + - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 +* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com> +* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <matteo.collina@gmail.com> + - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E +* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) <shestak.irina@gmail.com> +* **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) <yoshuawuyts@gmail.com> + +[sauce]: https://saucelabs.com diff --git a/node_modules/readable-stream/errors-browser.js b/node_modules/readable-stream/errors-browser.js new file mode 100644 index 000000000..fb8e73e18 --- /dev/null +++ b/node_modules/readable-stream/errors-browser.js @@ -0,0 +1,127 @@ +'use strict'; + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +var codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); + + function NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } + + return NodeError; + }(Base); + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; +} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + + +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith + + +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + + +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + + return str.substring(this_len - search.length, this_len) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + + +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner; + + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + var msg; + + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } + + msg += ". Received type ".concat(typeof actual); + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg; +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); +module.exports.codes = codes; diff --git a/node_modules/readable-stream/errors.js b/node_modules/readable-stream/errors.js new file mode 100644 index 000000000..8471526d6 --- /dev/null +++ b/node_modules/readable-stream/errors.js @@ -0,0 +1,116 @@ +'use strict'; + +const codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error + } + + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } + + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + + codes[code] = NodeError; +} + +// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } + + msg += `. Received type ${typeof actual}`; + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + +module.exports.codes = codes; diff --git a/node_modules/readable-stream/experimentalWarning.js b/node_modules/readable-stream/experimentalWarning.js new file mode 100644 index 000000000..78e841495 --- /dev/null +++ b/node_modules/readable-stream/experimentalWarning.js @@ -0,0 +1,17 @@ +'use strict' + +var experimentalWarnings = new Set(); + +function emitExperimentalWarning(feature) { + if (experimentalWarnings.has(feature)) return; + var msg = feature + ' is an experimental feature. This feature could ' + + 'change at any time'; + experimentalWarnings.add(feature); + process.emitWarning(msg, 'ExperimentalWarning'); +} + +function noop() {} + +module.exports.emitExperimentalWarning = process.emitWarning + ? emitExperimentalWarning + : noop; diff --git a/node_modules/readable-stream/lib/_stream_duplex.js b/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 000000000..19abfa604 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,126 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +}; +/**/ + +module.exports = Duplex; +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); +require('inherits')(Duplex, Readable); +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } +} +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); + +// the no-half-open enforcer +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(onEndNT, this); +} +function onEndNT(self) { + self.end(); +} +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_passthrough.js b/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 000000000..24a6bdde2 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,37 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict'; + +module.exports = PassThrough; +var Transform = require('./_stream_transform'); +require('inherits')(PassThrough, Transform); +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); +} +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_readable.js b/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 000000000..df1f608d5 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,1027 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +module.exports = Readable; + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = require('events').EventEmitter; +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +var Buffer = require('buffer').Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ +var debugUtil = require('util'); +var debug; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ + +var BufferList = require('./internal/streams/buffer_list'); +var destroyImpl = require('./internal/streams/destroy'); +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; + +// Lazy loaded to improve the startup performance. +var StringDecoder; +var createReadableStreamAsyncIterator; +var from; +require('inherits')(Readable, Stream); +var errorOrDestroy = destroyImpl.errorOrDestroy; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'end' (and potentially 'finish') + this.autoDestroy = !!options.autoDestroy; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + if (!(this instanceof Readable)) return new Readable(options); + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); + + // legacy + this.readable = true; + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + Stream.call(this); +} +Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } + + // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + return !state.ended && (state.length < state.highWaterMark || state.length === 0); +} +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + return er; +} +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; + // If setEncoding(null), decoder.encoding equals utf8 + this._readableState.encoding = this._readableState.decoder.encoding; + + // Iterate over current buffer to convert already stored Buffers: + var p = this._readableState.buffer.head; + var content = ''; + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + this._readableState.buffer.clear(); + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; +}; + +// Don't raise the hwm > 1GB +var MAX_HWM = 0x40000000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + if (ret !== null) this.emit('data', ret); + return ret; +}; +function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } +} +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } + + // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } +} +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + return dest; +}; +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; + + // Try start flowing on next tick if stream isn't explicitly paused + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; + + // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } +} +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + state.flowing = !state.readableListening; + resume(this, state); + } + state.paused = false; + return this; +}; +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } +} +function resume_(stream, state) { + debug('resume', state.reading); + if (!state.reading) { + stream.read(0); + } + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + this._readableState.paused = true; + return this; +}; +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null); +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + return this; +}; +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); + } + return createReadableStreamAsyncIterator(this); + }; +} +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } +}); +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } +}); +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } +}); + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; +} +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } +} +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); + + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } +} +if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = require('./internal/streams/from'); + } + return from(Readable, iterable, opts); + }; +} +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_transform.js b/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 000000000..1ccb7157b --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,190 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict'; + +module.exports = Transform; +var _require$codes = require('../errors').codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; +var Duplex = require('./_stream_duplex'); +require('inherits')(Transform, Duplex); +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + ts.writechunk = null; + ts.writecb = null; + if (data != null) + // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} +function prefinish() { + var _this = this; + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; +function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) + // single equals check for both `null` and `undefined` + stream.push(data); + + // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); +} \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_writable.js b/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 000000000..292415e23 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,641 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict'; + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +var Buffer = require('buffer').Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +var destroyImpl = require('./internal/streams/destroy'); +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; +var errorOrDestroy = destroyImpl.errorOrDestroy; +require('inherits')(Writable, Stream); +function nop() {} +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'finish' (and potentially 'end') + this.autoDestroy = !!options.autoDestroy; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; +} +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); + + // legacy. + this.writable = true; + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); +}; +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); + // TODO: defer error events consistently everywhere, not just the cb + errorOrDestroy(stream, er); + process.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var er; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); + } + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } + return true; +} +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; +}; +Writable.prototype.cork = function () { + this._writableState.corked++; +}; +Writable.prototype.uncork = function () { + var state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + return ret; +} +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } +} +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + if (entry === null) state.lastBufferedRequest = null; + } + state.bufferedRequest = entry; + state.bufferProcessing = false; +} +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); +}; +Writable.prototype._writev = null; +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending) endWritable(this, state, cb); + return this; +}; +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + errorOrDestroy(stream, err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + return need; +} +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + + // reuse the free corkReq. + state.corkedRequestsFree.next = corkReq; +} +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/async_iterator.js b/node_modules/readable-stream/lib/internal/streams/async_iterator.js new file mode 100644 index 000000000..742c5a467 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/async_iterator.js @@ -0,0 +1,180 @@ +'use strict'; + +var _Object$setPrototypeO; +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var finished = require('./end-of-stream'); +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); +function createIterResult(value, done) { + return { + value: value, + done: done + }; +} +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data = iter[kStream].read(); + // we defer if data is null + // we can be expecting either 'end' or + // 'error' + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } +} +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + iter[kHandlePromise](resolve, reject); + }, reject); + }; +} +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + if (error !== null) { + return Promise.reject(error); + } + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } + + // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + var lastPromise = this[kLastPromise]; + var promise; + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + promise = new Promise(this[kHandlePromise]); + } + this[kLastPromise] = promise; + return promise; + } +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + resolve(createIterResult(undefined, true)); + }); + }); +}), _Object$setPrototypeO), AsyncIteratorPrototype); +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; + // reject if we are waiting for data in the Promise + // returned by next() and store the error + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + iterator[kError] = err; + return; + } + var resolve = iterator[kLastResolve]; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; +}; +module.exports = createReadableStreamAsyncIterator; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/buffer_list.js b/node_modules/readable-stream/lib/internal/streams/buffer_list.js new file mode 100644 index 000000000..69bda497d --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/buffer_list.js @@ -0,0 +1,183 @@ +'use strict'; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var _require = require('buffer'), + Buffer = _require.Buffer; +var _require2 = require('util'), + inspect = _require2.inspect; +var custom = inspect && inspect.custom || 'inspect'; +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} +module.exports = /*#__PURE__*/function () { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) ret += s + p.data; + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + } + + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } + + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Consumes a specified amount of bytes from the buffered data. + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread(_objectSpread({}, options), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; +}(); \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/destroy.js b/node_modules/readable-stream/lib/internal/streams/destroy.js new file mode 100644 index 000000000..31a17c4dc --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/destroy.js @@ -0,0 +1,96 @@ +'use strict'; + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + return this; +} +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} +function emitErrorNT(self, err) { + self.emit('error', err); +} +function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +} +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/end-of-stream.js b/node_modules/readable-stream/lib/internal/streams/end-of-stream.js new file mode 100644 index 000000000..59c671b5a --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/end-of-stream.js @@ -0,0 +1,86 @@ +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). + +'use strict'; + +var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + callback.apply(this, args); + }; +} +function noop() {} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + var writableEnded = stream._writableState && stream._writableState.finished; + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + var readableEnded = stream._readableState && stream._readableState.endEmitted; + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + var onerror = function onerror(err) { + callback.call(stream, err); + }; + var onclose = function onclose() { + var err; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +} +module.exports = eos; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/from-browser.js b/node_modules/readable-stream/lib/internal/streams/from-browser.js new file mode 100644 index 000000000..a4ce56f3c --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/from-browser.js @@ -0,0 +1,3 @@ +module.exports = function () { + throw new Error('Readable.from is not available in the browser') +}; diff --git a/node_modules/readable-stream/lib/internal/streams/from.js b/node_modules/readable-stream/lib/internal/streams/from.js new file mode 100644 index 000000000..0a34ee92e --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/from.js @@ -0,0 +1,52 @@ +'use strict'; + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE; +function from(Readable, iterable, opts) { + var iterator; + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); + // Reading boolean to protect against _read + // being called before last iteration completion. + var reading = false; + readable._read = function () { + if (!reading) { + reading = true; + next(); + } + }; + function next() { + return _next2.apply(this, arguments); + } + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _yield$iterator$next = yield iterator.next(), + value = _yield$iterator$next.value, + done = _yield$iterator$next.done; + if (done) { + readable.push(null); + } else if (readable.push(yield value)) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } + return readable; +} +module.exports = from; diff --git a/node_modules/readable-stream/lib/internal/streams/pipeline.js b/node_modules/readable-stream/lib/internal/streams/pipeline.js new file mode 100644 index 000000000..e6f39241f --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/pipeline.js @@ -0,0 +1,86 @@ +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). + +'use strict'; + +var eos; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} +var _require$codes = require('../../../errors').codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = require('./end-of-stream'); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; + + // request.destroy just do .end - .abort is what we want + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} +function call(fn) { + fn(); +} +function pipe(from, to) { + return from.pipe(to); +} +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); +} +module.exports = pipeline; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/state.js b/node_modules/readable-stream/lib/internal/streams/state.js new file mode 100644 index 000000000..3fbf8927e --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/state.js @@ -0,0 +1,22 @@ +'use strict'; + +var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); + } + + // Default value + return state.objectMode ? 16 : 16 * 1024; +} +module.exports = { + getHighWaterMark: getHighWaterMark +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/stream-browser.js b/node_modules/readable-stream/lib/internal/streams/stream-browser.js new file mode 100644 index 000000000..9332a3fda --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/stream-browser.js @@ -0,0 +1 @@ +module.exports = require('events').EventEmitter; diff --git a/node_modules/readable-stream/lib/internal/streams/stream.js b/node_modules/readable-stream/lib/internal/streams/stream.js new file mode 100644 index 000000000..ce2ad5b6e --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/stream.js @@ -0,0 +1 @@ +module.exports = require('stream'); diff --git a/node_modules/readable-stream/package.json b/node_modules/readable-stream/package.json new file mode 100644 index 000000000..ade59e71a --- /dev/null +++ b/node_modules/readable-stream/package.json @@ -0,0 +1,68 @@ +{ + "name": "readable-stream", + "version": "3.6.2", + "description": "Streams3, a user-land copy of the stream library from Node.js", + "main": "readable.js", + "engines": { + "node": ">= 6" + }, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "devDependencies": { + "@babel/cli": "^7.2.0", + "@babel/core": "^7.2.0", + "@babel/polyfill": "^7.0.0", + "@babel/preset-env": "^7.2.0", + "airtap": "0.0.9", + "assert": "^1.4.0", + "bl": "^2.0.0", + "deep-strict-equal": "^0.2.0", + "events.once": "^2.0.2", + "glob": "^7.1.2", + "gunzip-maybe": "^1.4.1", + "hyperquest": "^2.1.3", + "lolex": "^2.6.0", + "nyc": "^11.0.0", + "pump": "^3.0.0", + "rimraf": "^2.6.2", + "tap": "^12.0.0", + "tape": "^4.9.0", + "tar-fs": "^1.16.2", + "util-promisify": "^2.1.0" + }, + "scripts": { + "test": "tap -J --no-esm test/parallel/*.js test/ours/*.js", + "ci": "TAP=1 tap --no-esm test/parallel/*.js test/ours/*.js | tee test.tap", + "test-browsers": "airtap --sauce-connect --loopback airtap.local -- test/browser.js", + "test-browser-local": "airtap --open --local -- test/browser.js", + "cover": "nyc npm test", + "report": "nyc report --reporter=lcov", + "update-browser-errors": "babel -o errors-browser.js errors.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/readable-stream" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false, + "worker_threads": false, + "./errors": "./errors-browser.js", + "./readable.js": "./readable-browser.js", + "./lib/internal/streams/from.js": "./lib/internal/streams/from-browser.js", + "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js" + }, + "nyc": { + "include": [ + "lib/**.js" + ] + }, + "license": "MIT" +} diff --git a/node_modules/readable-stream/readable-browser.js b/node_modules/readable-stream/readable-browser.js new file mode 100644 index 000000000..adbf60de8 --- /dev/null +++ b/node_modules/readable-stream/readable-browser.js @@ -0,0 +1,9 @@ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); +exports.finished = require('./lib/internal/streams/end-of-stream.js'); +exports.pipeline = require('./lib/internal/streams/pipeline.js'); diff --git a/node_modules/readable-stream/readable.js b/node_modules/readable-stream/readable.js new file mode 100644 index 000000000..9e0ca120d --- /dev/null +++ b/node_modules/readable-stream/readable.js @@ -0,0 +1,16 @@ +var Stream = require('stream'); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream.Readable; + Object.assign(module.exports, Stream); + module.exports.Stream = Stream; +} else { + exports = module.exports = require('./lib/_stream_readable.js'); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = require('./lib/_stream_writable.js'); + exports.Duplex = require('./lib/_stream_duplex.js'); + exports.Transform = require('./lib/_stream_transform.js'); + exports.PassThrough = require('./lib/_stream_passthrough.js'); + exports.finished = require('./lib/internal/streams/end-of-stream.js'); + exports.pipeline = require('./lib/internal/streams/pipeline.js'); +} diff --git a/node_modules/readdirp/LICENSE b/node_modules/readdirp/LICENSE new file mode 100644 index 000000000..037cbb4e6 --- /dev/null +++ b/node_modules/readdirp/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/readdirp/README.md b/node_modules/readdirp/README.md new file mode 100644 index 000000000..465593c9d --- /dev/null +++ b/node_modules/readdirp/README.md @@ -0,0 +1,122 @@ +# readdirp [![Weekly downloads](https://img.shields.io/npm/dw/readdirp.svg)](https://github.com/paulmillr/readdirp) + +Recursive version of [fs.readdir](https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback). Exposes a **stream API** and a **promise API**. + + +```sh +npm install readdirp +``` + +```javascript +const readdirp = require('readdirp'); + +// Use streams to achieve small RAM & CPU footprint. +// 1) Streams example with for-await. +for await (const entry of readdirp('.')) { + const {path} = entry; + console.log(`${JSON.stringify({path})}`); +} + +// 2) Streams example, non for-await. +// Print out all JS files along with their size within the current folder & subfolders. +readdirp('.', {fileFilter: '*.js', alwaysStat: true}) + .on('data', (entry) => { + const {path, stats: {size}} = entry; + console.log(`${JSON.stringify({path, size})}`); + }) + // Optionally call stream.destroy() in `warn()` in order to abort and cause 'close' to be emitted + .on('warn', error => console.error('non-fatal error', error)) + .on('error', error => console.error('fatal error', error)) + .on('end', () => console.log('done')); + +// 3) Promise example. More RAM and CPU than streams / for-await. +const files = await readdirp.promise('.'); +console.log(files.map(file => file.path)); + +// Other options. +readdirp('test', { + fileFilter: '*.js', + directoryFilter: ['!.git', '!*modules'] + // directoryFilter: (di) => di.basename.length === 9 + type: 'files_directories', + depth: 1 +}); +``` + +For more examples, check out `examples` directory. + +## API + +`const stream = readdirp(root[, options])` — **Stream API** + +- Reads given root recursively and returns a `stream` of [entry infos](#entryinfo) +- Optionally can be used like `for await (const entry of stream)` with node.js 10+ (`asyncIterator`). +- `on('data', (entry) => {})` [entry info](#entryinfo) for every file / dir. +- `on('warn', (error) => {})` non-fatal `Error` that prevents a file / dir from being processed. Example: inaccessible to the user. +- `on('error', (error) => {})` fatal `Error` which also ends the stream. Example: illegal options where passed. +- `on('end')` — we are done. Called when all entries were found and no more will be emitted. +- `on('close')` — stream is destroyed via `stream.destroy()`. + Could be useful if you want to manually abort even on a non fatal error. + At that point the stream is no longer `readable` and no more entries, warning or errors are emitted +- To learn more about streams, consult the very detailed [nodejs streams documentation](https://nodejs.org/api/stream.html) + or the [stream-handbook](https://github.com/substack/stream-handbook) + +`const entries = await readdirp.promise(root[, options])` — **Promise API**. Returns a list of [entry infos](#entryinfo). + +First argument is awalys `root`, path in which to start reading and recursing into subdirectories. + +### options + +- `fileFilter: ["*.js"]`: filter to include or exclude files. A `Function`, Glob string or Array of glob strings. + - **Function**: a function that takes an entry info as a parameter and returns true to include or false to exclude the entry + - **Glob string**: a string (e.g., `*.js`) which is matched using [picomatch](https://github.com/micromatch/picomatch), so go there for more + information. Globstars (`**`) are not supported since specifying a recursive pattern for an already recursive function doesn't make sense. Negated globs (as explained in the minimatch documentation) are allowed, e.g., `!*.txt` matches everything but text files. + - **Array of glob strings**: either need to be all inclusive or all exclusive (negated) patterns otherwise an error is thrown. + `['*.json', '*.js']` includes all JavaScript and Json files. + `['!.git', '!node_modules']` includes all directories except the '.git' and 'node_modules'. + - Directories that do not pass a filter will not be recursed into. +- `directoryFilter: ['!.git']`: filter to include/exclude directories found and to recurse into. Directories that do not pass a filter will not be recursed into. +- `depth: 5`: depth at which to stop recursing even if more subdirectories are found +- `type: 'files'`: determines if data events on the stream should be emitted for `'files'` (default), `'directories'`, `'files_directories'`, or `'all'`. Setting to `'all'` will also include entries for other types of file descriptors like character devices, unix sockets and named pipes. +- `alwaysStat: false`: always return `stats` property for every file. Default is `false`, readdirp will return `Dirent` entries. Setting it to `true` can double readdir execution time - use it only when you need file `size`, `mtime` etc. Cannot be enabled on node <10.10.0. +- `lstat: false`: include symlink entries in the stream along with files. When `true`, `fs.lstat` would be used instead of `fs.stat` + +### `EntryInfo` + +Has the following properties: + +- `path: 'assets/javascripts/react.js'`: path to the file/directory (relative to given root) +- `fullPath: '/Users/dev/projects/app/assets/javascripts/react.js'`: full path to the file/directory found +- `basename: 'react.js'`: name of the file/directory +- `dirent: fs.Dirent`: built-in [dir entry object](https://nodejs.org/api/fs.html#fs_class_fs_dirent) - only with `alwaysStat: false` +- `stats: fs.Stats`: built in [stat object](https://nodejs.org/api/fs.html#fs_class_fs_stats) - only with `alwaysStat: true` + +## Changelog + +- 3.5 (Oct 13, 2020) disallows recursive directory-based symlinks. + Before, it could have entered infinite loop. +- 3.4 (Mar 19, 2020) adds support for directory-based symlinks. +- 3.3 (Dec 6, 2019) stabilizes RAM consumption and enables perf management with `highWaterMark` option. Fixes race conditions related to `for-await` looping. +- 3.2 (Oct 14, 2019) improves performance by 250% and makes streams implementation more idiomatic. +- 3.1 (Jul 7, 2019) brings `bigint` support to `stat` output on Windows. This is backwards-incompatible for some cases. Be careful. It you use it incorrectly, you'll see "TypeError: Cannot mix BigInt and other types, use explicit conversions". +- 3.0 brings huge performance improvements and stream backpressure support. +- Upgrading 2.x to 3.x: + - Signature changed from `readdirp(options)` to `readdirp(root, options)` + - Replaced callback API with promise API. + - Renamed `entryType` option to `type` + - Renamed `entryType: 'both'` to `'files_directories'` + - `EntryInfo` + - Renamed `stat` to `stats` + - Emitted only when `alwaysStat: true` + - `dirent` is emitted instead of `stats` by default with `alwaysStat: false` + - Renamed `name` to `basename` + - Removed `parentDir` and `fullParentDir` properties +- Supported node.js versions: + - 3.x: node 8+ + - 2.x: node 0.6+ + +## License + +Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller () + +MIT License, see [LICENSE](LICENSE) file. diff --git a/node_modules/readdirp/index.d.ts b/node_modules/readdirp/index.d.ts new file mode 100644 index 000000000..cbbd76ca1 --- /dev/null +++ b/node_modules/readdirp/index.d.ts @@ -0,0 +1,43 @@ +// TypeScript Version: 3.2 + +/// + +import * as fs from 'fs'; +import { Readable } from 'stream'; + +declare namespace readdir { + interface EntryInfo { + path: string; + fullPath: string; + basename: string; + stats?: fs.Stats; + dirent?: fs.Dirent; + } + + interface ReaddirpOptions { + root?: string; + fileFilter?: string | string[] | ((entry: EntryInfo) => boolean); + directoryFilter?: string | string[] | ((entry: EntryInfo) => boolean); + type?: 'files' | 'directories' | 'files_directories' | 'all'; + lstat?: boolean; + depth?: number; + alwaysStat?: boolean; + } + + interface ReaddirpStream extends Readable, AsyncIterable { + read(): EntryInfo; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + function promise( + root: string, + options?: ReaddirpOptions + ): Promise; +} + +declare function readdir( + root: string, + options?: readdir.ReaddirpOptions +): readdir.ReaddirpStream; + +export = readdir; diff --git a/node_modules/readdirp/index.js b/node_modules/readdirp/index.js new file mode 100644 index 000000000..cf739b2dc --- /dev/null +++ b/node_modules/readdirp/index.js @@ -0,0 +1,287 @@ +'use strict'; + +const fs = require('fs'); +const { Readable } = require('stream'); +const sysPath = require('path'); +const { promisify } = require('util'); +const picomatch = require('picomatch'); + +const readdir = promisify(fs.readdir); +const stat = promisify(fs.stat); +const lstat = promisify(fs.lstat); +const realpath = promisify(fs.realpath); + +/** + * @typedef {Object} EntryInfo + * @property {String} path + * @property {String} fullPath + * @property {fs.Stats=} stats + * @property {fs.Dirent=} dirent + * @property {String} basename + */ + +const BANG = '!'; +const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR'; +const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]); +const FILE_TYPE = 'files'; +const DIR_TYPE = 'directories'; +const FILE_DIR_TYPE = 'files_directories'; +const EVERYTHING_TYPE = 'all'; +const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE]; + +const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code); +const [maj, min] = process.versions.node.split('.').slice(0, 2).map(n => Number.parseInt(n, 10)); +const wantBigintFsStats = process.platform === 'win32' && (maj > 10 || (maj === 10 && min >= 5)); + +const normalizeFilter = filter => { + if (filter === undefined) return; + if (typeof filter === 'function') return filter; + + if (typeof filter === 'string') { + const glob = picomatch(filter.trim()); + return entry => glob(entry.basename); + } + + if (Array.isArray(filter)) { + const positive = []; + const negative = []; + for (const item of filter) { + const trimmed = item.trim(); + if (trimmed.charAt(0) === BANG) { + negative.push(picomatch(trimmed.slice(1))); + } else { + positive.push(picomatch(trimmed)); + } + } + + if (negative.length > 0) { + if (positive.length > 0) { + return entry => + positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename)); + } + return entry => !negative.some(f => f(entry.basename)); + } + return entry => positive.some(f => f(entry.basename)); + } +}; + +class ReaddirpStream extends Readable { + static get defaultOptions() { + return { + root: '.', + /* eslint-disable no-unused-vars */ + fileFilter: (path) => true, + directoryFilter: (path) => true, + /* eslint-enable no-unused-vars */ + type: FILE_TYPE, + lstat: false, + depth: 2147483648, + alwaysStat: false + }; + } + + constructor(options = {}) { + super({ + objectMode: true, + autoDestroy: true, + highWaterMark: options.highWaterMark || 4096 + }); + const opts = { ...ReaddirpStream.defaultOptions, ...options }; + const { root, type } = opts; + + this._fileFilter = normalizeFilter(opts.fileFilter); + this._directoryFilter = normalizeFilter(opts.directoryFilter); + + const statMethod = opts.lstat ? lstat : stat; + // Use bigint stats if it's windows and stat() supports options (node 10+). + if (wantBigintFsStats) { + this._stat = path => statMethod(path, { bigint: true }); + } else { + this._stat = statMethod; + } + + this._maxDepth = opts.depth; + this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type); + this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type); + this._wantsEverything = type === EVERYTHING_TYPE; + this._root = sysPath.resolve(root); + this._isDirent = ('Dirent' in fs) && !opts.alwaysStat; + this._statsProp = this._isDirent ? 'dirent' : 'stats'; + this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent }; + + // Launch stream with one parent, the root dir. + this.parents = [this._exploreDir(root, 1)]; + this.reading = false; + this.parent = undefined; + } + + async _read(batch) { + if (this.reading) return; + this.reading = true; + + try { + while (!this.destroyed && batch > 0) { + const { path, depth, files = [] } = this.parent || {}; + + if (files.length > 0) { + const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path)); + for (const entry of await Promise.all(slice)) { + if (this.destroyed) return; + + const entryType = await this._getEntryType(entry); + if (entryType === 'directory' && this._directoryFilter(entry)) { + if (depth <= this._maxDepth) { + this.parents.push(this._exploreDir(entry.fullPath, depth + 1)); + } + + if (this._wantsDir) { + this.push(entry); + batch--; + } + } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) { + if (this._wantsFile) { + this.push(entry); + batch--; + } + } + } + } else { + const parent = this.parents.pop(); + if (!parent) { + this.push(null); + break; + } + this.parent = await parent; + if (this.destroyed) return; + } + } + } catch (error) { + this.destroy(error); + } finally { + this.reading = false; + } + } + + async _exploreDir(path, depth) { + let files; + try { + files = await readdir(path, this._rdOptions); + } catch (error) { + this._onError(error); + } + return { files, depth, path }; + } + + async _formatEntry(dirent, path) { + let entry; + try { + const basename = this._isDirent ? dirent.name : dirent; + const fullPath = sysPath.resolve(sysPath.join(path, basename)); + entry = { path: sysPath.relative(this._root, fullPath), fullPath, basename }; + entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath); + } catch (err) { + this._onError(err); + } + return entry; + } + + _onError(err) { + if (isNormalFlowError(err) && !this.destroyed) { + this.emit('warn', err); + } else { + this.destroy(err); + } + } + + async _getEntryType(entry) { + // entry may be undefined, because a warning or an error were emitted + // and the statsProp is undefined + const stats = entry && entry[this._statsProp]; + if (!stats) { + return; + } + if (stats.isFile()) { + return 'file'; + } + if (stats.isDirectory()) { + return 'directory'; + } + if (stats && stats.isSymbolicLink()) { + const full = entry.fullPath; + try { + const entryRealPath = await realpath(full); + const entryRealPathStats = await lstat(entryRealPath); + if (entryRealPathStats.isFile()) { + return 'file'; + } + if (entryRealPathStats.isDirectory()) { + const len = entryRealPath.length; + if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath.sep) { + const recursiveError = new Error( + `Circular symlink detected: "${full}" points to "${entryRealPath}"` + ); + recursiveError.code = RECURSIVE_ERROR_CODE; + return this._onError(recursiveError); + } + return 'directory'; + } + } catch (error) { + this._onError(error); + } + } + } + + _includeAsFile(entry) { + const stats = entry && entry[this._statsProp]; + + return stats && this._wantsEverything && !stats.isDirectory(); + } +} + +/** + * @typedef {Object} ReaddirpArguments + * @property {Function=} fileFilter + * @property {Function=} directoryFilter + * @property {String=} type + * @property {Number=} depth + * @property {String=} root + * @property {Boolean=} lstat + * @property {Boolean=} bigint + */ + +/** + * Main function which ends up calling readdirRec and reads all files and directories in given root recursively. + * @param {String} root Root directory + * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth + */ +const readdirp = (root, options = {}) => { + let type = options.entryType || options.type; + if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility + if (type) options.type = type; + if (!root) { + throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)'); + } else if (typeof root !== 'string') { + throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)'); + } else if (type && !ALL_TYPES.includes(type)) { + throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`); + } + + options.root = root; + return new ReaddirpStream(options); +}; + +const readdirpPromise = (root, options = {}) => { + return new Promise((resolve, reject) => { + const files = []; + readdirp(root, options) + .on('data', entry => files.push(entry)) + .on('end', () => resolve(files)) + .on('error', error => reject(error)); + }); +}; + +readdirp.promise = readdirpPromise; +readdirp.ReaddirpStream = ReaddirpStream; +readdirp.default = readdirp; + +module.exports = readdirp; diff --git a/node_modules/readdirp/package.json b/node_modules/readdirp/package.json new file mode 100644 index 000000000..dba53888e --- /dev/null +++ b/node_modules/readdirp/package.json @@ -0,0 +1,122 @@ +{ + "name": "readdirp", + "description": "Recursive version of fs.readdir with streaming API.", + "version": "3.6.0", + "homepage": "https://github.com/paulmillr/readdirp", + "repository": { + "type": "git", + "url": "git://github.com/paulmillr/readdirp.git" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/paulmillr/readdirp/issues" + }, + "author": "Thorsten Lorenz (thlorenz.com)", + "contributors": [ + "Thorsten Lorenz (thlorenz.com)", + "Paul Miller (https://paulmillr.com)" + ], + "main": "index.js", + "engines": { + "node": ">=8.10.0" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "recursive", + "fs", + "stream", + "streams", + "readdir", + "filesystem", + "find", + "filter" + ], + "scripts": { + "dtslint": "dtslint", + "nyc": "nyc", + "mocha": "mocha --exit", + "lint": "eslint --report-unused-disable-directives --ignore-path .gitignore .", + "test": "npm run lint && nyc npm run mocha" + }, + "dependencies": { + "picomatch": "^2.2.1" + }, + "devDependencies": { + "@types/node": "^14", + "chai": "^4.2", + "chai-subset": "^1.6", + "dtslint": "^3.3.0", + "eslint": "^7.0.0", + "mocha": "^7.1.1", + "nyc": "^15.0.0", + "rimraf": "^3.0.0", + "typescript": "^4.0.3" + }, + "nyc": { + "reporter": [ + "html", + "text" + ] + }, + "eslintConfig": { + "root": true, + "extends": "eslint:recommended", + "parserOptions": { + "ecmaVersion": 9, + "sourceType": "script" + }, + "env": { + "node": true, + "es6": true + }, + "rules": { + "array-callback-return": "error", + "no-empty": [ + "error", + { + "allowEmptyCatch": true + } + ], + "no-else-return": [ + "error", + { + "allowElseIf": false + } + ], + "no-lonely-if": "error", + "no-var": "error", + "object-shorthand": "error", + "prefer-arrow-callback": [ + "error", + { + "allowNamedFunctions": true + } + ], + "prefer-const": [ + "error", + { + "ignoreReadBeforeAssign": true + } + ], + "prefer-destructuring": [ + "error", + { + "object": true, + "array": false + } + ], + "prefer-spread": "error", + "prefer-template": "error", + "radix": "error", + "semi": "error", + "strict": "error", + "quotes": [ + "error", + "single" + ] + } + } +} diff --git a/node_modules/readline/.npmignore b/node_modules/readline/.npmignore deleted file mode 100644 index 1ca957177..000000000 --- a/node_modules/readline/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -npm-debug.log diff --git a/node_modules/readline/README.md b/node_modules/readline/README.md deleted file mode 100644 index 88a116d49..000000000 --- a/node_modules/readline/README.md +++ /dev/null @@ -1,66 +0,0 @@ -## _readline_ -> Read a file line by line. - -## Install - -## Important. In node 10 there is a core module named readline. Please use linebyline instead, it is the same module just renamed: -[Npm linebyline](https://www.npmjs.com/package/linebyline) - -```sh -npm install linebyline -``` - -## Test -```sh -npm install . -npm test - -``` - - -## What's this? - -Simple streaming readline module for NodeJS. Reads a file and buffers new lines emitting a _line_ event for each line. - -## Usage -### Simple -```js - var readline = require('linebyline'), - rl = readline('./somefile.txt'); - rl.on('line', function(line, lineCount, byteCount) { - // do something with the line of text - }) - .on('error', function(e) { - // something went wrong - }); -``` - -### ASCII file decoding -As the underlying `fs.createReadStream` doesn't care about the specific ASCII encoding of the file, an alternative way to decode the file is by telling the `readline` library to retain buffer and then decoding it using a converter (e.g. [`iconv-lite`](https://www.npmjs.com/package/iconv-lite)). -```js - var readline = require('linebyline'), - rl = readline('./file-in-win1251.txt', { - retainBuffer: true //tell readline to retain buffer - }); - rl.on("line", function (data,linecount){ - var line = iconv.decode(data, 'win1251'); - // do something with the line of converted text - }); -``` -##API -## readLine(readingObject[, options]) -### Params: - -* `readingObject` - file path or stream object -* `options` can include: - * `maxLineLength` - override the default 4K buffer size (lines longer than this will not be read) - * `retainBuffer` - avoid converting to String prior to emitting 'line' event; will pass raw buffer with encoded data to the callback - -### Return: - -* **EventEmitter** - - -## License - -BSD © [Craig Brookes](http://craigbrookes.com/) diff --git a/node_modules/readline/package.json b/node_modules/readline/package.json deleted file mode 100644 index 4b90b8ce0..000000000 --- a/node_modules/readline/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "_from": "readline@^1.3.0", - "_id": "readline@1.3.0", - "_inBundle": false, - "_integrity": "sha1-xYDXfvLPyHUrEySYBg3JeTp6wBw=", - "_location": "/readline", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "readline@^1.3.0", - "name": "readline", - "escapedName": "readline", - "rawSpec": "^1.3.0", - "saveSpec": null, - "fetchSpec": "^1.3.0" - }, - "_requiredBy": [ - "/asana" - ], - "_resolved": "https://registry.npmjs.org/readline/-/readline-1.3.0.tgz", - "_shasum": "c580d77ef2cfc8752b132498060dc9793a7ac01c", - "_spec": "readline@^1.3.0", - "_where": "/Users/christopher/Projects/github-actions-asana/node_modules/asana", - "author": { - "name": "craig brookes" - }, - "bugs": { - "url": "https://github.com/maleck13/readline/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "Simple streaming readline module.", - "devDependencies": { - "iconv-lite": "0.4.13", - "tap": "0.4.3" - }, - "homepage": "https://github.com/maleck13/readline#readme", - "keywords": [ - "readline", - "line by line", - "file" - ], - "license": "BSD", - "main": "readline.js", - "name": "readline", - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/maleck13/readline.git" - }, - "scripts": { - "test": "tap --tap --stderr --timeout=120 test/*.js" - }, - "version": "1.3.0" -} diff --git a/node_modules/readline/readline.js b/node_modules/readline/readline.js deleted file mode 100644 index e11a7a564..000000000 --- a/node_modules/readline/readline.js +++ /dev/null @@ -1,60 +0,0 @@ -var fs = require('fs'), - EventEmitter = require('events').EventEmitter, - util = require('util'); - -var readLine = module.exports = function(file, opts) { - if (!(this instanceof readLine)) return new readLine(file, opts); - - EventEmitter.call(this); - opts = opts || {}; - opts.maxLineLength = opts.maxLineLength || 4096; // 4K - opts.retainBuffer = !!opts.retainBuffer; //do not convert to String prior to invoking emit 'line' event - var self = this, - lineBuffer = new Buffer(opts.maxLineLength), - lineLength = 0, - lineCount = 0, - byteCount = 0, - emit = function(lineCount, byteCount) { - try { - var line = lineBuffer.slice(0, lineLength); - self.emit('line', opts.retainBuffer? line : line.toString(), lineCount, byteCount); - } catch (err) { - self.emit('error', err); - } finally { - lineLength = 0; // Empty buffer. - } - }; - this.input = ('string' === typeof file) ? fs.createReadStream(file, opts) : file; - this.input.on('open', function(fd) { - self.emit('open', fd); - }) - .on('data', function(data) { - for (var i = 0; i < data.length; i++) { - if (data[i] == 10 || data[i] == 13) { // Newline char was found. - if (data[i] == 10) { - lineCount++; - emit(lineCount, byteCount); - } - } else { - lineBuffer[lineLength] = data[i]; // Buffer new line data. - lineLength++; - } - byteCount++; - } - }) - .on('error', function(err) { - self.emit('error', err); - }) - .on('end', function() { - // Emit last line if anything left over since EOF won't trigger it. - if (lineLength) { - lineCount++; - emit(lineCount, byteCount); - } - self.emit('end'); - }) - .on('close', function() { - self.emit('close'); - }); -}; -util.inherits(readLine, EventEmitter); diff --git a/node_modules/readline/test/fixtures/afile.txt b/node_modules/readline/test/fixtures/afile.txt deleted file mode 100644 index 08f8b67f2..000000000 --- a/node_modules/readline/test/fixtures/afile.txt +++ /dev/null @@ -1,39773 +0,0 @@ -The Project Gutenberg EBook of The Adventures of Sherlock Holmes -by Sir Arthur Conan Doyle -(#15 in our series by Sir Arthur Conan Doyle) - -Copyright laws are changing all over the world. Be sure to check the -copyright laws for your country before downloading or redistributing -this or any other Project Gutenberg eBook. - -This header should be the first thing seen when viewing this Project -Gutenberg file. Please do not remove it. Do not change or edit the -header without written permission. - -Please read the "legal small print," and other information about the -eBook and Project Gutenberg at the bottom of this file. Included is -important information about your specific rights and restrictions in -how the file may be used. You can also find out about how to make a -donation to Project Gutenberg, and how to get involved. - - -**Welcome To The World of Free Plain Vanilla Electronic Texts** - -**eBooks Readable By Both Humans and By Computers, Since 1971** - -*****These eBooks Were Prepared By Thousands of Volunteers!***** - - -Title: The Adventures of Sherlock Holmes - -Author: Sir Arthur Conan Doyle - -Release Date: March, 1999 [EBook #1661] -[Most recently updated: November 29, 2002] - -Edition: 12 - -Language: English - -Character set encoding: ASCII - -*** START OF THE PROJECT GUTENBERG EBOOK, THE ADVENTURES OF SHERLOCK HOLMES *** - - - - -(Additional editing by Jose Menendez) - - - -THE ADVENTURES OF -SHERLOCK HOLMES - -BY - -SIR ARTHUR CONAN DOYLE - -CONTENTS - -I. A Scandal in Bohemia -II. The Red-Headed League -III. A Case of Identity -IV. The Boscombe Valley Mystery -V. The Five Orange Pips -VI. The Man with the Twisted Lip -VII. The Adventure of the Blue Carbuncle -VIII. The Adventure of the Speckled Band -IX. The Adventure of the Engineer's Thumb -X. The Adventure of the Noble Bachelor -XI. The Adventure of the Beryl Coronet -XII. The Adventure of the Copper Beeches - - -ADVENTURE I. A SCANDAL IN BOHEMIA - -I. - - -To Sherlock Holmes she is always the woman. I have seldom heard him mention her under any other name. In his eyes she eclipses and predominates the whole of her sex. It was not that he felt any emotion akin to love for Irene Adler. All emotions, and that one particularly, were abhorrent to his cold, precise but admirably balanced mind. He was, I take it, the most perfect reasoning and observing machine that the world has seen, but as a lover he would have placed himself in a false position. He never spoke of the softer passions, save with a gibe and a sneer. They were admirable things for the observer--excellent for drawing the veil from men's motives and actions. But for the trained reasoner to admit such intrusions into his own delicate and finely adjusted temperament was to introduce a distracting factor which might throw a doubt upon all his mental results. Grit in a sensitive instrument, or a crack in one of his own high-power lenses, would not be more disturbing than a strong emotion in a nature such as his. And yet there was but one woman to him, and that woman was the late Irene Adler, of dubious and questionable memory. - -I had seen little of Holmes lately. My marriage had drifted us away from each other. My own complete happiness, and the home-centred interests which rise up around the man who first finds himself master of his own establishment, were sufficient to absorb all my attention, while Holmes, who loathed every form of society with his whole Bohemian soul, remained in our lodgings in Baker Street, buried among his old books, and alternating from week to week between cocaine and ambition, the drowsiness of the drug, and the fierce energy of his own keen nature. He was still, as ever, deeply attracted by the study of crime, and occupied his immense faculties and extraordinary powers of observation in following out those clues, and clearing up those mysteries which had been abandoned as hopeless by the official police. From time to time I heard some vague account of his doings: of his summons to Odessa in the case of the Trepoff murder, of his clearing up of the singular tragedy of the Atkinson brothers at Trincomalee, and finally of the mission which he had accomplished so delicately and successfully for the reigning family of Holland. Beyond these signs of his activity, however, which I merely shared with all the readers of the daily press, I knew little of my former friend and companion. - -One night--it was on the twentieth of March, 1888--I was returning from a journey to a patient (for I had now returned to civil practice), when my way led me through Baker Street. As I passed the well-remembered door, which must always be associated in my mind with my wooing, and with the dark incidents of the Study in Scarlet, I was seized with a keen desire to see Holmes again, and to know how he was employing his extraordinary powers. His rooms were brilliantly lit, and, even as I looked up, I saw his tall, spare figure pass twice in a dark silhouette against the blind. He was pacing the room swiftly, eagerly, with his head sunk upon his chest and his hands clasped behind him. To me, who knew his every mood and habit, his attitude and manner told their own story. He was at work again. He had risen out of his drug-created dreams and was hot upon the scent of some new problem. I rang the bell and was shown up to the chamber which had formerly been in part my own. - -His manner was not effusive. It seldom was; but he was glad, I think, to see me. With hardly a word spoken, but with a kindly eye, he waved me to an armchair, threw across his case of cigars, and indicated a spirit case and a gasogene in the corner. Then he stood before the fire and looked me over in his singular introspective fashion. - -"Wedlock suits you," he remarked. "I think, Watson, that you have put on seven and a half pounds since I saw you." - -"Seven!" I answered. - -"Indeed, I should have thought a little more. Just a trifle more, I fancy, Watson. And in practice again, I observe. You did not tell me that you intended to go into harness." - -"Then, how do you know?" - -"I see it, I deduce it. How do I know that you have been getting yourself very wet lately, and that you have a most clumsy and careless servant girl?" - -"My dear Holmes," said I, "this is too much. You would certainly have been burned, had you lived a few centuries ago. It is true that I had a country walk on Thursday and came home in a dreadful mess, but as I have changed my clothes I can't imagine how you deduce it. As to Mary Jane, she is incorrigible, and my wife has given her notice, but there, again, I fail to see how you work it out." - -He chuckled to himself and rubbed his long, nervous hands together. - -"It is simplicity itself," said he; "my eyes tell me that on the inside of your left shoe, just where the firelight strikes it, the leather is scored by six almost parallel cuts. Obviously they have been caused by someone who has very carelessly scraped round the edges of the sole in order to remove crusted mud from it. Hence, you see, my double deduction that you had been out in vile weather, and that you had a particularly malignant boot-slitting specimen of the London slavey. As to your practice, if a gentleman walks into my rooms smelling of iodoform, with a black mark of nitrate of silver upon his right forefinger, and a bulge on the right side of his top-hat to show where he has secreted his stethoscope, I must be dull, indeed, if I do not pronounce him to be an active member of the medical profession." - -I could not help laughing at the ease with which he explained his process of deduction. "When I hear you give your reasons," I remarked, "the thing always appears to me to be so ridiculously simple that I could easily do it myself, though at each successive instance of your reasoning I am baffled until you explain your process. And yet I believe that my eyes are as good as yours." - -"Quite so," he answered, lighting a cigarette, and throwing himself down into an armchair. "You see, but you do not observe. The distinction is clear. For example, you have frequently seen the steps which lead up from the hall to this room." - -"Frequently." - -"How often?" - -"Well, some hundreds of times." - -"Then how many are there?" - -"How many? I don't know." - -"Quite so! You have not observed. And yet you have seen. That is just my point. Now, I know that there are seventeen steps, because I have both seen and observed. By the way, since you are interested in these little problems, and since you are good enough to chronicle one or two of my trifling experiences, you may be interested in this." He threw over a sheet of thick, pink-tinted notepaper which had been lying open upon the table. "It came by the last post," said he. "Read it aloud." - -The note was undated, and without either signature or address. - -"There will call upon you to-night, at a quarter to eight o'clock," it said, "a gentleman who desires to consult you upon a matter of the very deepest moment. Your recent services to one of the royal houses of Europe have shown that you are one who may safely be trusted with matters which are of an importance which can hardly be exaggerated. This account of you we have from all quarters received. Be in your chamber then at that hour, and do not take it amiss if your visitor wear a mask." - -"This is indeed a mystery," I remarked. "What do you imagine that it means?" - -"I have no data yet. It is a capital mistake to theorise before one has data. Insensibly one begins to twist facts to suit theories, instead of theories to suit facts. But the note itself. What do you deduce from it?" - -I carefully examined the writing, and the paper upon which it was written. - -"The man who wrote it was presumably well to do," I remarked, endeavouring to imitate my companion's processes. "Such paper could not be bought under half a crown a packet. It is peculiarly strong and stiff." - -"Peculiar--that is the very word," said Holmes. "It is not an English paper at all. Hold it up to the light." - -I did so, and saw a large "E" with a small "g," a "P," and a large "G" with a small "t" woven into the texture of the paper. - -"What do you make of that?" asked Holmes. - -"The name of the maker, no doubt; or his monogram, rather." - -"Not at all. The 'G' with the small 't' stands for 'Gesellschaft,' which is the German for 'Company.' It is a customary contraction like our 'Co.' 'P,' of course, stands for 'Papier.' Now for the 'Eg.' Let us glance at our Continental Gazetteer." He took down a heavy brown volume from his shelves. "Eglow, Eglonitz--here we are, Egria. It is in a German-speaking country--in Bohemia, not far from Carlsbad. 'Remarkable as being the scene of the death of Wallenstein, and for its numerous glass-factories and paper-mills.' Ha, ha, my boy, what do you make of that?" His eyes sparkled, and he sent up a great blue triumphant cloud from his cigarette. - -"The paper was made in Bohemia," I said. - -"Precisely. And the man who wrote the note is a German. Do you note the peculiar construction of the sentence--'This account of you we have from all quarters received.' A Frenchman or Russian could not have written that. It is the German who is so uncourteous to his verbs. It only remains, therefore, to discover what is wanted by this German who writes upon Bohemian paper and prefers wearing a mask to showing his face. And here he comes, if I am not mistaken, to resolve all our doubts." - -As he spoke there was the sharp sound of horses' hoofs and grating wheels against the curb, followed by a sharp pull at the bell. Holmes whistled. - -"A pair, by the sound," said he. "Yes," he continued, glancing out of the window. "A nice little brougham and a pair of beauties. A hundred and fifty guineas apiece. There's money in this case, Watson, if there is nothing else." - -"I think that I had better go, Holmes." - -"Not a bit, Doctor. Stay where you are. I am lost without my Boswell. And this promises to be interesting. It would be a pity to miss it." - -"But your client--" - -"Never mind him. I may want your help, and so may he. Here he comes. Sit down in that armchair, Doctor, and give us your best attention." - -A slow and heavy step, which had been heard upon the stairs and in the passage, paused immediately outside the door. Then there was a loud and authoritative tap. - -"Come in!" said Holmes. - -A man entered who could hardly have been less than six feet six inches in height, with the chest and limbs of a Hercules. His dress was rich with a richness which would, in England, be looked upon as akin to bad taste. Heavy bands of astrakhan were slashed across the sleeves and fronts of his double-breasted coat, while the deep blue cloak which was thrown over his shoulders was lined with flame-coloured silk and secured at the neck with a brooch which consisted of a single flaming beryl. Boots which extended halfway up his calves, and which were trimmed at the tops with rich brown fur, completed the impression of barbaric opulence which was suggested by his whole appearance. He carried a broad-brimmed hat in his hand, while he wore across the upper part of his face, extending down past the cheekbones, a black vizard mask, which he had apparently adjusted that very moment, for his hand was still raised to it as he entered. From the lower part of the face he appeared to be a man of strong character, with a thick, hanging lip, and a long, straight chin suggestive of resolution pushed to the length of obstinacy. - -"You had my note?" he asked with a deep harsh voice and a strongly marked German accent. "I told you that I would call." He looked from one to the other of us, as if uncertain which to address. - -"Pray take a seat," said Holmes. "This is my friend and colleague, Dr. Watson, who is occasionally good enough to help me in my cases. Whom have I the honour to address?" - -"You may address me as the Count Von Kramm, a Bohemian nobleman. I understand that this gentleman, your friend, is a man of honour and discretion, whom I may trust with a matter of the most extreme importance. If not, I should much prefer to communicate with you alone." - -I rose to go, but Holmes caught me by the wrist and pushed me back into my chair. "It is both, or none," said he. "You may say before this gentleman anything which you may say to me." - -The Count shrugged his broad shoulders. "Then I must begin," said he, "by binding you both to absolute secrecy for two years; at the end of that time the matter will be of no importance. At present it is not too much to say that it is of such weight it may have an influence upon European history." - -"I promise," said Holmes. - -"And I." - -"You will excuse this mask," continued our strange visitor. "The august person who employs me wishes his agent to be unknown to you, and I may confess at once that the title by which I have just called myself is not exactly my own." - -"I was aware of it," said Holmes dryly. - -"The circumstances are of great delicacy, and every precaution has to be taken to quench what might grow to be an immense scandal and seriously compromise one of the reigning families of Europe. To speak plainly, the matter implicates the great House of Ormstein, hereditary kings of Bohemia." - -"I was also aware of that," murmured Holmes, settling himself down in his armchair and closing his eyes. - -Our visitor glanced with some apparent surprise at the languid, lounging figure of the man who had been no doubt depicted to him as the most incisive reasoner and most energetic agent in Europe. Holmes slowly reopened his eyes and looked impatiently at his gigantic client. - -"If your Majesty would condescend to state your case," he remarked, "I should be better able to advise you." - -The man sprang from his chair and paced up and down the room in uncontrollable agitation. Then, with a gesture of desperation, he tore the mask from his face and hurled it upon the ground. "You are right," he cried; "I am the King. Why should I attempt to conceal it?" - -"Why, indeed?" murmured Holmes. "Your Majesty had not spoken before I was aware that I was addressing Wilhelm Gottsreich Sigismond von Ormstein, Grand Duke of Cassel-Felstein, and hereditary King of Bohemia." - -"But you can understand," said our strange visitor, sitting down once more and passing his hand over his high white forehead, "you can understand that I am not accustomed to doing such business in my own person. Yet the matter was so delicate that I could not confide it to an agent without putting myself in his power. I have come incognito from Prague for the purpose of consulting you." - -"Then, pray consult," said Holmes, shutting his eyes once more. - -"The facts are briefly these: Some five years ago, during a lengthy visit to Warsaw, I made the acquaintance of the well-known adventuress, Irene Adler. The name is no doubt familiar to you." - -"Kindly look her up in my index, Doctor," murmured Holmes without opening his eyes. For many years he had adopted a system of docketing all paragraphs concerning men and things, so that it was difficult to name a subject or a person on which he could not at once furnish information. In this case I found her biography sandwiched in between that of a Hebrew rabbi and that of a staff-commander who had written a monograph upon the deep-sea fishes. - -"Let me see!" said Holmes. "Hum! Born in New Jersey in the year 1858. Contralto--hum! La Scala, hum! Prima donna Imperial Opera of Warsaw--yes! Retired from operatic stage--ha! Living in London--quite so! Your Majesty, as I understand, became entangled with this young person, wrote her some compromising letters, and is now desirous of getting those letters back." - -"Precisely so. But how--" - -"Was there a secret marriage?" - -"None." - -"No legal papers or certificates?" - -"None." - -"Then I fail to follow your Majesty. If this young person should produce her letters for blackmailing or other purposes, how is she to prove their authenticity?" - -"There is the writing." - -"Pooh, pooh! Forgery." - -"My private note-paper." - -"Stolen." - -"My own seal." - -"Imitated." - -"My photograph." - -"Bought." - -"We were both in the photograph." - -"Oh, dear! That is very bad! Your Majesty has indeed committed an indiscretion." - -"I was mad--insane." - -"You have compromised yourself seriously." - -"I was only Crown Prince then. I was young. I am but thirty now." - -"It must be recovered." - -"We have tried and failed." - -"Your Majesty must pay. It must be bought." - -"She will not sell." - -"Stolen, then." - -"Five attempts have been made. Twice burglars in my pay ransacked her house. Once we diverted her luggage when she travelled. Twice she has been waylaid. There has been no result." - - - -"On the contrary, Watson, you can see everything. You fail, however, to reason from what you see. You are too timid in drawing your inferences." - -"Then, pray tell me what it is that you can infer from this hat?" - -He picked it up and gazed at it in the peculiar introspective fashion which was characteristic of him. "It is perhaps less suggestive than it might have been," he remarked, "and yet there are a few inferences which are very distinct, and a few others which represent at least a strong balance of probability. That the man was highly intellectual is of course obvious upon the face of it, and also that he was fairly well-to-do within the last three years, although he has now fallen upon evil days. He had foresight, but has less now than formerly, pointing to a moral retrogression, which, when taken with the decline of his fortunes, seems to indicate some evil influence, probably drink, at work upon him. This may account also for the obvious fact that his wife has ceased to love him." - -"My dear Holmes!" - -"He has, however, retained some degree of self-respect," he continued, disregarding my remonstrance. "He is a man who leads a sedentary life, goes out little, is out of training entirely, is middle-aged, has grizzled hair which he has had cut within the last few days, and which he anoints with lime-cream. These are the more patent facts which are to be deduced from his hat. Also, by the way, that it is extremely improbable that he has gas laid on in his house." - -"You are certainly joking, Holmes." - -"Not in the least. Is it possible that even now, when I give you these results, you are unable to see how they are attained?" - -"I have no doubt that I am very stupid, but I must confess that I am unable to follow you. For example, how did you deduce that this man was intellectual?" - -For answer Holmes clapped the hat upon his head. It came right over the forehead and settled upon the bridge of his nose. "It is a question of cubic capacity," said he; "a man with so large a brain must have something in it." - -"The decline of his fortunes, then?" - -"This hat is three years old. These flat brims curled at the edge came in then. It is a hat of the very best quality. Look at the band of ribbed silk and the excellent lining. If this man could afford to buy so expensive a hat three years ago, and has had no hat since, then he has assuredly gone down in the world." - -"Well, that is clear enough, certainly. But how about the foresight and the moral retrogression?" - -Sherlock Holmes laughed. "Here is the foresight," said he putting his finger upon the little disc and loop of the hat-securer. "They are never sold upon hats. If this man ordered one, it is a sign of a certain amount of foresight, since he went out of his way to take this precaution against the wind. But since we see that he has broken the elastic and has not troubled to replace it, it is obvious that he has less foresight now than formerly, which is a distinct proof of a weakening nature. On the other hand, he has endeavoured to conceal some of these stains upon the felt by daubing them with ink, which is a sign that he has not entirely lost his self-respect." - -"Your reasoning is certainly plausible." - -"The further points, that he is middle-aged, that his hair is grizzled, that it has been recently cut, and that he uses lime-cream, are all to be gathered from a close examination of the lower part of the lining. The lens discloses a large number of hair-ends, clean cut by the scissors of the barber. They all appear to be adhesive, and there is a distinct odour of lime-cream. This dust, you will observe, is not the gritty, grey dust of the street but the fluffy brown dust of the house, showing that it has been hung up indoors most of the time, while the marks of moisture upon the inside are proof positive that the wearer perspired very freely, and could therefore, hardly be in the best of training." - -"But his wife--you said that she had ceased to love him." - -"This hat has not been brushed for weeks. When I see you, my dear Watson, with a week's accumulation of dust upon your hat, and when your wife allows you to go out in such a state, I shall fear that you also have been unfortunate enough to lose your wife's affection." - -"But he might be a bachelor." - -"Nay, he was bringing home the goose as a peace-offering to his wife. Remember the card upon the bird's leg." - -"You have an answer to everything. But how on earth do you deduce that the gas is not laid on in his house?" - -"One tallow stain, or even two, might come by chance; but when I see no less than five, I think that there can be little doubt that the individual must be brought into frequent contact with burning tallow--walks upstairs at night probably with his hat in one hand and a guttering candle in the other. Anyhow, he never got tallow-stains from a gas-jet. Are you satisfied?" - -"Well, it is very ingenious," said I, laughing; "but since, as you said just now, there has been no crime committed, and no harm done save the loss of a goose, all this seems to be rather a waste of energy." - -Sherlock Holmes had opened his mouth to reply, when the door flew open, and Peterson, the commissionaire, rushed into the apartment with flushed cheeks and the face of a man who is dazed with astonishment. - -"The goose, Mr. Holmes! The goose, sir!" he gasped. - -"Eh? What of it, then? Has it returned to life and flapped off through the kitchen window?" Holmes twisted himself round upon the sofa to get a fairer view of the man's excited face. - -"See here, sir! See what my wife found in its crop!" He held out his hand and displayed upon the centre of the palm a brilliantly scintillating blue stone, rather smaller than a bean in size, but of such purity and radiance that it twinkled like an electric point in the dark hollow of his hand. - -Sherlock Holmes sat up with a whistle. "By Jove, Peterson!" said he, "this is treasure trove indeed. I suppose you know what you have got?" - -"A diamond, sir? A precious stone. It cuts into glass as though it were putty." - -"It's more than a precious stone. It is the precious stone." - -"Not the Countess of Morcar's blue carbuncle!" I ejaculated. - -"Precisely so. I ought to know its size and shape, seeing that I have read the advertisement about it in The Times every day lately. It is absolutely unique, and its value can only be conjectured, but the reward offered of $1000 is certainly not within a twentieth part of the market price." - -"A thousand pounds! Great Lord of mercy!" The commissionaire plumped down into a chair and stared from one to the other of us. - -"That is the reward, and I have reason to know that there are sentimental considerations in the background which would induce the Countess to part with half her fortune if she could but recover the gem." - -"It was lost, if I remember aright, at the Hotel Cosmopolitan," I remarked. - -"Precisely so, on December 22nd, just five days ago. John Horner, a plumber, was accused of having abstracted it from the lady's jewel-case. The evidence against him was so strong that the case has been referred to the Assizes. I have some account of the matter here, I believe." He rummaged amid his newspapers, glancing over the dates, until at last he smoothed one out, doubled it over, and read the following paragraph: - -"Hotel Cosmopolitan Jewel Robbery. John Horner, 26, plumber, was brought up upon the charge of having upon the 22nd inst., abstracted from the jewel-case of the Countess of Morcar the valuable gem known as the blue carbuncle. James Ryder, upper-attendant at the hotel, gave his evidence to the effect that he had shown Horner up to the dressing-room of the Countess of Morcar upon the day of the robbery in order that he might solder the second bar of the grate, which was loose. He had remained with Horner some little time, but had finally been called away. On returning, he found that Horner had disappeared, that the bureau had been forced open, and that the small morocco casket in which, as it afterwards transpired, the Countess was accustomed to keep her jewel, was lying empty upon the dressing-table. Ryder instantly gave the alarm, and Horner was arrested the same evening; but the stone could not be found either upon his person or in his rooms. Catherine Cusack, maid to the Countess, deposed to having heard Ryder's cry of dismay on discovering the robbery, and to having rushed into the room, where she found matters as described by the last witness. Inspector Bradstreet, B division, gave evidence as to the arrest of Horner, who struggled frantically, and protested his innocence in the strongest terms. Evidence of a previous conviction for robbery having been given against the prisoner, the magistrate refused to deal summarily with the offence, but referred it to the Assizes. Horner, who had shown signs of intense emotion during the proceedings, fainted away at the conclusion and was carried out of court." - -"Hum! So much for the police-court," said Holmes thoughtfully, tossing aside the paper. "The question for us now to solve is the sequence of events leading from a rifled jewel-case at one end to the crop of a goose in Tottenham Court Road at the other. You see, Watson, our little deductions have suddenly assumed a much more important and less innocent aspect. Here is the stone; the stone came from the goose, and the goose came from Mr. Henry Baker, the gentleman with the bad hat and all the other characteristics with which I have bored you. So now we must set ourselves very seriously to finding this gentleman and ascertaining what part he has played in this little mystery. To do this, we must try the simplest means first, and these lie undoubtedly in an advertisement in all the evening papers. If this fail, I shall have recourse to other methods." - -"What will you say?" - -"Give me a pencil and that slip of paper. Now, then: 'Found at the corner of Goodge Street, a goose and a black felt hat. Mr. Henry Baker can have the same by applying at 6:30 this evening at 221B, Baker Street.' That is clear and concise." - -"Very. But will he see it?" - -"Well, he is sure to keep an eye on the papers, since, to a poor man, the loss was a heavy one. He was clearly so scared by his mischance in breaking the window and by the approach of Peterson that he thought of nothing but flight, but since then he must have bitterly regretted the impulse which caused him to drop his bird. Then, again, the introduction of his name will cause him to see it, for everyone who knows him will direct his attention to it. Here you are, Peterson, run down to the advertising agency and have this put in the evening papers." - -"In which, sir?" - -"Oh, in the Globe, Star, Pall Mall, St. James's, Evening News, Standard, Echo, and any others that occur to you." - -"Very well, sir. And this stone?" - -"Ah, yes, I shall keep the stone. Thank you. And, I say, Peterson, just buy a goose on your way back and leave it here with me, for we must have one to give to this gentleman in place of the one which your family is now devouring." - -When the commissionaire had gone, Holmes took up the stone and held it against the light. "It's a bonny thing," said he. "Just see how it glints and sparkles. Of course it is a nucleus and focus of crime. Every good stone is. They are the devil's pet baits. In the larger and older jewels every facet may stand for a bloody deed. This stone is not yet twenty years old. It was found in the banks of the Amoy River in southern China and is remarkable in having every characteristic of the carbuncle, save that it is blue in shade instead of ruby red. In spite of its youth, it has already a sinister history. There have been two murders, a vitriol-throwing, a suicide, and several robberies brought about for the sake of this forty-grain weight of crystallised charcoal. Who would think that so pretty a toy would be a purveyor to the gallows and the prison? I'll lock it up in my strong box now and drop a line to the Countess to say that we have it." - -"Do you think that this man Horner is innocent?" - -"I cannot tell." - -"Well, then, do you imagine that this other one, Henry Baker, had anything to do with the matter?" - -"It is, I think, much more likely that Henry Baker is an absolutely innocent man, who had no idea that the bird which he was carrying was of considerably more value than if it were made of solid gold. That, however, I shall determine by a very simple test if we have an answer to our advertisement." - -"And you can do nothing until then?" - -"Nothing." - -"In that case I shall continue my professional round. But I shall come back in the evening at the hour you have mentioned, for I should like to see the solution of so tangled a business." - -"Very glad to see you. I dine at seven. There is a woodcock, I believe. By the way, in view of recent occurrences, perhaps I ought to ask Mrs. Hudson to examine its crop." - -I had been delayed at a case, and it was a little after half-past six when I found myself in Baker Street once more. As I approached the house I saw a tall man in a Scotch bonnet with a coat which was buttoned up to his chin waiting outside in the bright semicircle which was thrown from the fanlight. Just as I arrived the door was opened, and we were shown up together to Holmes' room. - -"Mr. Henry Baker, I believe," said he, rising from his armchair and greeting his visitor with the easy air of geniality which he could so readily assume. "Pray take this chair by the fire, Mr. Baker. It is a cold night, and I observe that your circulation is more adapted for summer than for winter. Ah, Watson, you have just come at the right time. Is that your hat, Mr. Baker?" - -"Yes, sir, that is undoubtedly my hat." - -He was a large man with rounded shoulders, a massive head, and a broad, intelligent face, sloping down to a pointed beard of grizzled brown. A touch of red in nose and cheeks, with a slight tremor of his extended hand, recalled Holmes' surmise as to his habits. His rusty black frock-coat was buttoned right up in front, with the collar turned up, and his lank wrists protruded from his sleeves without a sign of cuff or shirt. He spoke in a slow staccato fashion, choosing his words with care, and gave the impression generally of a man of learning and letters who had had ill-usage at the hands of fortune. - -"We have retained these things for some days," said Holmes, "because we expected to see an advertisement from you giving your address. I am at a loss to know now why you did not advertise." - -Our visitor gave a rather shamefaced laugh. "Shillings have not been so plentiful with me as they once were," he remarked. "I had no doubt that the gang of roughs who assaulted me had carried off both my hat and the bird. I did not care to spend more money in a hopeless attempt at recovering them." - -"Very naturally. By the way, about the bird, we were compelled to eat it." - -"To eat it!" Our visitor half rose from his chair in his excitement. - -"Yes, it would have been of no use to anyone had we not done so. But I presume that this other goose upon the sideboard, which is about the same weight and perfectly fresh, will answer your purpose equally well?" - -"Oh, certainly, certainly," answered Mr. Baker with a sigh of relief. - -"Of course, we still have the feathers, legs, crop, and so on of your own bird, so if you wish--" - -The man burst into a hearty laugh. "They might be useful to me as relics of my adventure," said he, "but beyond that I can hardly see what use the disjecta membra of my late acquaintance are going to be to me. No, sir, I think that, with your permission, I will confine my attentions to the excellent bird which I perceive upon the sideboard." - -Sherlock Holmes glanced sharply across at me with a slight shrug of his shoulders. - -"There is your hat, then, and there your bird," said he. "By the way, would it bore you to tell me where you got the other one from? I am somewhat of a fowl fancier, and I have seldom seen a better grown goose." - -"Certainly, sir," said Baker, who had risen and tucked his newly gained property under his arm. "There are a few of us who frequent the Alpha Inn, near the Museum--we are to be found in the Museum itself during the day, you understand. This year our good host, Windigate by name, instituted a goose club, by which, on consideration of some few pence every week, we were each to receive a bird at Christmas. My pence were duly paid, and the rest is familiar to you. I am much indebted to you, sir, for a Scotch bonnet is fitted neither to my years nor my gravity." With a comical pomposity of manner he bowed solemnly to both of us and strode off upon his way. - -"So much for Mr. Henry Baker," said Holmes when he had closed the door behind him. "It is quite certain that he knows nothing whatever about the matter. Are you hungry, Watson?" - -"Not particularly." - -"Then I suggest that we turn our dinner into a supper and follow up this clue while it is still hot." - -"By all means." - -It was a bitter night, so we drew on our ulsters and wrapped cravats about our throats. Outside, the stars were shining coldly in a cloudless sky, and the breath of the passers-by blew out into smoke like so many pistol shots. Our footfalls rang out crisply and loudly as we swung through the doctors' quarter, Wimpole Street, Harley Street, and so through Wigmore Street into Oxford Street. In a quarter of an hour we were in Bloomsbury at the Alpha Inn, which is a small public-house at the corner of one of the streets which runs down into Holborn. Holmes pushed open the door of the private bar and ordered two glasses of beer from the ruddy-faced, white-aproned landlord. - -"Your beer should be excellent if it is as good as your geese," said he. - -"My geese!" The man seemed surprised. - -"Yes. I was speaking only half an hour ago to Mr. Henry Baker, who was a member of your goose club." - -"Ah! yes, I see. But you see, sir, them's not our geese." - -"Indeed! Whose, then?" - -"Well, I got the two dozen from a salesman in Covent Garden." - -"Indeed? I know some of them. Which was it?" - -"Breckinridge is his name." - -"Ah! I don't know him. Well, here's your good health landlord, and prosperity to your house. Good-night." - -"Now for Mr. Breckinridge," he continued, buttoning up his coat as we came out into the frosty air. "Remember, Watson that though we have so homely a thing as a goose at one end of this chain, we have at the other a man who will certainly get seven years' penal servitude unless we can establish his innocence. It is possible that our inquiry may but confirm his guilt; but, in any case, we have a line of investigation which has been missed by the police, and which a singular chance has placed in our hands. Let us follow it out to the bitter end. Faces to the south, then, and quick march!" - -We passed across Holborn, down Endell Street, and so through a zigzag of slums to Covent Garden Market. One of the largest stalls bore the name of Breckinridge upon it, and the proprietor a horsey-looking man, with a sharp face and trim side-whiskers was helping a boy to put up the shutters. - -"Good-evening. It's a cold night," said Holmes. - -The salesman nodded and shot a questioning glance at my companion. - -"Sold out of geese, I see," continued Holmes, pointing at the bare slabs of marble. - -"Let you have five hundred to-morrow morning." - -"That's no good." - -"Well, there are some on the stall with the gas-flare." - -"Ah, but I was recommended to you." - -"Who by?" - -"The landlord of the Alpha." - -"Oh, yes; I sent him a couple of dozen." - -"Fine birds they were, too. Now where did you get them from?" - -To my surprise the question provoked a burst of anger from the salesman. - -"Now, then, mister," said he, with his head cocked and his arms akimbo, "what are you driving at? Let's have it straight, now." - -"It is straight enough. I should like to know who sold you the geese which you supplied to the Alpha." - -"Well then, I shan't tell you. So now!" - -"Oh, it is a matter of no importance; but I don't know why you should be so warm over such a trifle." - -"Warm! You'd be as warm, maybe, if you were as pestered as I am. When I pay good money for a good article there should be an end of the business; but it's 'Where are the geese?' and 'Who did you sell the geese to?' and 'What will you take for the geese?' One would think they were the only geese in the world, to hear the fuss that is made over them." - -"Well, I have no connection with any other people who have been making inquiries," said Holmes carelessly. "If you won't tell us the bet is off, that is all. But I'm always ready to back my opinion on a matter of fowls, and I have a fiver on it that the bird I ate is country bred." - -"Well, then, you've lost your fiver, for it's town bred," snapped the salesman. - -"It's nothing of the kind." - -"I say it is." - -"I don't believe it." - -"D'you think you know more about fowls than I, who have handled them ever since I was a nipper? I tell you, all those birds that went to the Alpha were town bred." - -"You'll never persuade me to believe that." - -"Will you bet, then?" - -"It's merely taking your money, for I know that I am right. But I'll have a sovereign on with you, just to teach you not to be obstinate." - -The salesman chuckled grimly. "Bring me the books, Bill," said he. - -The small boy brought round a small thin volume and a great greasy-backed one, laying them out together beneath the hanging lamp. - -"Now then, Mr. Cocksure," said the salesman, "I thought that I was out of geese, but before I finish you'll find that there is still one left in my shop. You see this little book?" - -"Well?" - -"That's the list of the folk from whom I buy. D'you see? Well, then, here on this page are the country folk, and the numbers after their names are where their accounts are in the big ledger. Now, then! You see this other page in red ink? Well, that is a list of my town suppliers. Now, look at that third name. Just read it out to me." - -"Mrs. Oakshott, 117, Brixton Road--249," read Holmes. - -"Quite so. Now turn that up in the ledger." - -Holmes turned to the page indicated. "Here you are, 'Mrs. Oakshott, 117, Brixton Road, egg and poultry supplier.' " - -"Now, then, what's the last entry?" - -" 'December 22nd. Twenty-four geese at 7s. 6d.' " - -"Quite so. There you are. And underneath?" - -" 'Sold to Mr. Windigate of the Alpha, at 12s.' " - -"What have you to say now?" - -Sherlock Holmes looked deeply chagrined. He drew a sovereign from his pocket and threw it down upon the slab, turning away with the air of a man whose disgust is too deep for words. A few yards off he stopped under a lamp-post and laughed in the hearty, noiseless fashion which was peculiar to him. - -"When you see a man with whiskers of that cut and the 'Pink 'un' protruding out of his pocket, you can always draw him by a bet," said he. "I daresay that if I had put $100 down in front of him, that man would not have given me such complete information as was drawn from him by the idea that he was doing me on a wager. Well, Watson, we are, I fancy, nearing the end of our quest, and the only point which remains to be determined is whether we should go on to this Mrs. Oakshott to-night, or whether we should reserve it for to-morrow. It is clear from what that surly fellow said that there are others besides ourselves who are anxious about the matter, and I should--" - -His remarks were suddenly cut short by a loud hubbub which broke out from the stall which we had just left. Turning round we saw a little rat-faced fellow standing in the centre of the circle of yellow light which was thrown by the swinging lamp, while Breckinridge, the salesman, framed in the door of his stall, was shaking his fists fiercely at the cringing figure. - -"I've had enough of you and your geese," he shouted. "I wish you were all at the devil together. If you come pestering me any more with your silly talk I'll set the dog at you. You bring Mrs. Oakshott here and I'll answer her, but what have you to do with it? Did I buy the geese off you?" - -"No; but one of them was mine all the same," whined the little man. - -"Well, then, ask Mrs. Oakshott for it." - -"She told me to ask you." - -"Well, you can ask the King of Proosia, for all I care. I've had enough of it. Get out of this!" He rushed fiercely forward, and the inquirer flitted away into the darkness. - -"Ha! this may save us a visit to Brixton Road," whispered Holmes. "Come with me, and we will see what is to be made of this fellow." Striding through the scattered knots of people who lounged round the flaring stalls, my companion speedily overtook the little man and touched him upon the shoulder. He sprang round, and I could see in the gas-light that every vestige of colour had been driven from his face. - -"Who are you, then? What do you want?" he asked in a quavering voice. - -"You will excuse me," said Holmes blandly, "but I could not help overhearing the questions which you put to the salesman just now. I think that I could be of assistance to you." - -"You? Who are you? How could you know anything of the matter?" - -"My name is Sherlock Holmes. It is my business to know what other people don't know." - -"But you can know nothing of this?" - -"Excuse me, I know everything of it. You are endeavouring to trace some geese which were sold by Mrs. Oakshott, of Brixton Road, to a salesman named Breckinridge, by him in turn to Mr. Windigate, of the Alpha, and by him to his club, of which Mr. Henry Baker is a member." - -"Oh, sir, you are the very man whom I have longed to meet," cried the little fellow with outstretched hands and quivering fingers. "I can hardly explain to you how interested I am in this matter." - -Sherlock Holmes hailed a four-wheeler which was passing. "In that case we had better discuss it in a cosy room rather than in this wind-swept market-place," said he. "But pray tell me, before we go farther, who it is that I have the pleasure of assisting." - -The man hesitated for an instant. "My name is John Robinson," he answered with a sidelong glance. - -"No, no; the real name," said Holmes sweetly. "It is always awkward doing business with an alias." - -A flush sprang to the white cheeks of the stranger. "Well then," said he, "my real name is James Ryder." - -"Precisely so. Head attendant at the Hotel Cosmopolitan. Pray step into the cab, and I shall soon be able to tell you everything which you would wish to know." - -The little man stood glancing from one to the other of us with half-frightened, half-hopeful eyes, as one who is not sure whether he is on the verge of a windfall or of a catastrophe. Then he stepped into the cab, and in half an hour we were back in the sitting-room at Baker Street. Nothing had been said during our drive, but the high, thin breathing of our new companion, and the claspings and unclaspings of his hands, spoke of the nervous tension within him. - -"Here we are!" said Holmes cheerily as we filed into the room. "The fire looks very seasonable in this weather. You look cold, Mr. Ryder. Pray take the basket-chair. I will just put on my slippers before we settle this little matter of yours. Now, then! You want to know what became of those geese?" - -"Yes, sir." - -"Or rather, I fancy, of that goose. It was one bird, I imagine in which you were interested--white, with a black bar across the tail." - -Ryder quivered with emotion. "Oh, sir," he cried, "can you tell me where it went to?" - -"It came here." - -"Here?" - -"Yes, and a most remarkable bird it proved. I don't wonder that you should take an interest in it. It laid an egg after it was dead--the bonniest, brightest little blue egg that ever was seen. I have it here in my museum." - -Our visitor staggered to his feet and clutched the mantelpiece with his right hand. Holmes unlocked his strong-box and held up the blue carbuncle, which shone out like a star, with a cold, brilliant, many-pointed radiance. Ryder stood glaring with a drawn face, uncertain whether to claim or to disown it. - -"The game's up, Ryder," said Holmes quietly. "Hold up, man, or you'll be into the fire! Give him an arm back into his chair, Watson. He's not got blood enough to go in for felony with impunity. Give him a dash of brandy. So! Now he looks a little more human. What a shrimp it is, to be sure!" - -For a moment he had staggered and nearly fallen, but the brandy brought a tinge of colour into his cheeks, and he sat staring with frightened eyes at his accuser. - -"I have almost every link in my hands, and all the proofs which I could possibly need, so there is little which you need tell me. Still, that little may as well be cleared up to make the case complete. You had heard, Ryder, of this blue stone of the Countess of Morcar's?" - -"It was Catherine Cusack who told me of it," said he in a crackling voice. - -"I see--her ladyship's waiting-maid. Well, the temptation of sudden wealth so easily acquired was too much for you, as it has been for better men before you; but you were not very scrupulous in the means you used. It seems to me, Ryder, that there is the making of a very pretty villain in you. You knew that this man Horner, the plumber, had been concerned in some such matter before, and that suspicion would rest the more readily upon him. What did you do, then? You made some small job in my lady's room--you and your confederate Cusack--and you managed that he should be the man sent for. Then, when he had left, you rifled the jewel-case, raised the alarm, and had this unfortunate man arrested. You then--" - -Ryder threw himself down suddenly upon the rug and clutched at my companion's knees. "For God's sake, have mercy!" he shrieked. "Think of my father! Of my mother! It would break their hearts. I never went wrong before! I never will again. I swear it. I'll swear it on a Bible. Oh, don't bring it into court! For Christ's sake, don't!" - -"Get back into your chair!" said Holmes sternly. "It is very well to cringe and crawl now, but you thought little enough of this poor Horner in the dock for a crime of which he knew nothing." - -"I will fly, Mr. Holmes. I will leave the country, sir. Then the charge against him will break down." - -"Hum! We will talk about that. And now let us hear a true account of the next act. How came the stone into the goose, and how came the goose into the open market? Tell us the truth, for there lies your only hope of safety." - -Ryder passed his tongue over his parched lips. "I will tell you it just as it happened, sir," said he. "When Horner had been arrested, it seemed to me that it would be best for me to get away with the stone at once, for I did not know at what moment the police might not take it into their heads to search me and my room. There was no place about the hotel where it would be safe. I went out, as if on some commission, and I made for my sister's house. She had married a man named Oakshott, and lived in Brixton Road, where she fattened fowls for the market. All the way there every man I met seemed to me to be a policeman or a detective; and, for all that it was a cold night, the sweat was pouring down my face before I came to the Brixton Road. My sister asked me what was the matter, and why I was so pale; but I told her that I had been upset by the jewel robbery at the hotel. Then I went into the back yard and smoked a pipe and wondered what it would be best to do. - -"I had a friend once called Maudsley, who went to the bad, and has just been serving his time in Pentonville. One day he had met me, and fell into talk about the ways of thieves, and how they could get rid of what they stole. I knew that he would be true to me, for I knew one or two things about him; so I made up my mind to go right on to Kilburn, where he lived, and take him into my confidence. He would show me how to turn the stone into money. But how to get to him in safety? I thought of the agonies I had gone through in coming from the hotel. I might at any moment be seized and searched, and there would be the stone in my waistcoat pocket. I was leaning against the wall at the time and looking at the geese which were waddling about round my feet, and suddenly an idea came into my head which showed me how I could beat the best detective that ever lived. - -"My sister had told me some weeks before that I might have the pick of her geese for a Christmas present, and I knew that she was always as good as her word. I would take my goose now, and in it I would carry my stone to Kilburn. There was a little shed in the yard, and behind this I drove one of the birds--a fine big one, white, with a barred tail. I caught it, and prying its bill open, I thrust the stone down its throat as far as my finger could reach. The bird gave a gulp, and I felt the stone pass along its gullet and down into its crop. But the creature flapped and struggled, and out came my sister to know what was the matter. As I turned to speak to her the brute broke loose and fluttered off among the others. - -" 'Whatever were you doing with that bird, Jem?' says she. - -" 'Well,' said I, 'you said you'd give me one for Christmas, and I was feeling which was the fattest.' - -" 'Oh,' says she, 'we've set yours aside for you--Jem's bird, we call it. It's the big white one over yonder. There's twenty-six of them, which makes one for you, and one for us, and two dozen for the market.' - -" 'Thank you, Maggie,' says I; 'but if it is all the same to you, I'd rather have that one I was handling just now.' - -" 'The other is a good three pound heavier,' said she, 'and we fattened it expressly for you.' - -" 'Never mind. I'll have the other, and I'll take it now,' said I. - -" 'Oh, just as you like,' said she, a little huffed. 'Which is it you want, then?' - -" 'That white one with the barred tail, right in the middle of the flock.' - -" 'Oh, very well. Kill it and take it with you.' - -"Well, I did what she said, Mr. Holmes, and I carried the bird all the way to Kilburn. I told my pal what I had done, for he was a man that it was easy to tell a thing like that to. He laughed until he choked, and we got a knife and opened the goose. My heart turned to water, for there was no sign of the stone, and I knew that some terrible mistake had occurred. I left the bird, rushed back to my sister's, and hurried into the back yard. There was not a bird to be seen there. - -" 'Where are they all, Maggie?' I cried. - -" 'Gone to the dealer's, Jem.' - -" 'Which dealer's?' - -" 'Breckinridge, of Covent Garden.' - -" 'But was there another with a barred tail?' I asked, 'the same as the one I chose?' - -" 'Yes, Jem; there were two barred-tailed ones, and I could never tell them apart.' - -"Well, then, of course I saw it all, and I ran off as hard as my feet would carry me to this man Breckinridge; but he had sold the lot at once, and not one word would he tell me as to where they had gone. You heard him yourselves to-night. Well, he has always answered me like that. My sister thinks that I am going mad. Sometimes I think that I am myself. And now--and now I am myself a branded thief, without ever having touched the wealth for which I sold my character. God help me! God help me!" He burst into convulsive sobbing, with his face buried in his hands. - -There was a long silence, broken only by his heavy breathing and by the measured tapping of Sherlock Holmes' finger-tips upon the edge of the table. Then my friend rose and threw open the door. - -"Get out!" said he. - -"What, sir! Oh, Heaven bless you!" - -"No more words. Get out!" - -And no more words were needed. There was a rush, a clatter upon the stairs, the bang of a door, and the crisp rattle of running footfalls from the street. - -"After all, Watson," said Holmes, reaching up his hand for his clay pipe, "I am not retained by the police to supply their deficiencies. If Horner were in danger it would be another thing; but this fellow will not appear against him, and the case must collapse. I suppose that I am commuting a felony, but it is just possible that I am saving a soul. This fellow will not go wrong again; he is too terribly frightened. Send him to gaol now, and you make him a gaol-bird for life. Besides, it is the season of forgiveness. Chance has put in our way a most singular and whimsical problem, and its solution is its own reward. If you will have the goodness to touch the bell, Doctor, we will begin another investigation, in which, also a bird will be the chief feature." - -VIII. THE ADVENTURE OF THE SPECKLED BAND - - -On glancing over my notes of the seventy odd cases in which I have during the last eight years studied the methods of my friend Sherlock Holmes, I find many tragic, some comic, a large number merely strange, but none commonplace; for, working as he did rather for the love of his art than for the acquirement of wealth, he refused to associate himself with any investigation which did not tend towards the unusual, and even the fantastic. Of all these varied cases, however, I cannot recall any which presented more singular features than that which was associated with the well-known Surrey family of the Roylotts of Stoke Moran. The events in question occurred in the early days of my association with Holmes, when we were sharing rooms as bachelors in Baker Street. It is possible that I might have placed them upon record before, but a promise of secrecy was made at the time, from which I have only been freed during the last month by the untimely death of the lady to whom the pledge was given. It is perhaps as well that the facts should now come to light, for I have reasons to know that there are widespread rumours as to the death of Dr. Grimesby Roylott which tend to make the matter even more terrible than the truth. - -It was early in April in the year '83 that I woke one morning to find Sherlock Holmes standing, fully dressed, by the side of my bed. He was a late riser, as a rule, and as the clock on the mantelpiece showed me that it was only a quarter-past seven, I blinked up at him in some surprise, and perhaps just a little resentment, for I was myself regular in my habits. - -"Very sorry to knock you up, Watson," said he, "but it's the common lot this morning. Mrs. Hudson has been knocked up, she retorted upon me, and I on you." - -"What is it, then--a fire?" - -"No; a client. It seems that a young lady has arrived in a considerable state of excitement, who insists upon seeing me. She is waiting now in the sitting-room. Now, when young ladies wander about the metropolis at this hour of the morning, and knock sleepy people up out of their beds, I presume that it is something very pressing which they have to communicate. Should it prove to be an interesting case, you would, I am sure, wish to follow it from the outset. I thought, at any rate, that I should call you and give you the chance." - -"My dear fellow, I would not miss it for anything." - -I had no keener pleasure than in following Holmes in his professional investigations, and in admiring the rapid deductions, as swift as intuitions, and yet always founded on a logical basis with which he unravelled the problems which were submitted to him. I rapidly threw on my clothes and was ready in a few minutes to accompany my friend down to the sitting-room. A lady dressed in black and heavily veiled, who had been sitting in the window, rose as we entered. - -"Good-morning, madam," said Holmes cheerily. "My name is Sherlock Holmes. This is my intimate friend and associate, Dr. Watson, before whom you can speak as freely as before myself. Ha! I am glad to see that Mrs. Hudson has had the good sense to light the fire. Pray draw up to it, and I shall order you a cup of hot coffee, for I observe that you are shivering." - -"It is not cold which makes me shiver," said the woman in a low voice, changing her seat as requested. - -"What, then?" - -"It is fear, Mr. Holmes. It is terror." She raised her veil as she spoke, and we could see that she was indeed in a pitiable state of agitation, her face all drawn and grey, with restless frightened eyes, like those of some hunted animal. Her features and figure were those of a woman of thirty, but her hair was shot with premature grey, and her expression was weary and haggard. Sherlock Holmes ran her over with one of his quick, all-comprehensive glances. - -"You must not fear," said he soothingly, bending forward and patting her forearm. "We shall soon set matters right, I have no doubt. You have come in by train this morning, I see." - -"You know me, then?" - -"No, but I observe the second half of a return ticket in the palm of your left glove. You must have started early, and yet you had a good drive in a dog-cart, along heavy roads, before you reached the station." - -The lady gave a violent start and stared in bewilderment at my companion. - -"There is no mystery, my dear madam," said he, smiling. "The left arm of your jacket is spattered with mud in no less than seven places. The marks are perfectly fresh. There is no vehicle save a dog-cart which throws up mud in that way, and then only when you sit on the left-hand side of the driver." - -"Whatever your reasons may be, you are perfectly correct," said she. "I started from home before six, reached Leatherhead at twenty past, and came in by the first train to Waterloo. Sir, I can stand this strain no longer; I shall go mad if it continues. I have no one to turn to--none, save only one, who cares for me, and he, poor fellow, can be of little aid. I have heard of you, Mr. Holmes; I have heard of you from Mrs. Farintosh, whom you helped in the hour of her sore need. It was from her that I had your address. Oh, sir, do you not think that you could help me, too, and at least throw a little light through the dense darkness which surrounds me? At present it is out of my power to reward you for your services, but in a month or six weeks I shall be married, with the control of my own income, and then at least you shall not find me ungrateful." - -Holmes turned to his desk and, unlocking it, drew out a small case-book, which he consulted. - -"Farintosh," said he. "Ah yes, I recall the case; it was concerned with an opal tiara. I think it was before your time, Watson. I can only say, madam, that I shall be happy to devote the same care to your case as I did to that of your friend. As to reward, my profession is its own reward; but you are at liberty to defray whatever expenses I may be put to, at the time which suits you best. And now I beg that you will lay before us everything that may help us in forming an opinion upon the matter." - -"Alas!" replied our visitor, "the very horror of my situation lies in the fact that my fears are so vague, and my suspicions depend so entirely upon small points, which might seem trivial to another, that even he to whom of all others I have a right to look for help and advice looks upon all that I tell him about it as the fancies of a nervous woman. He does not say so, but I can read it from his soothing answers and averted eyes. But I have heard, Mr. Holmes, that you can see deeply into the manifold wickedness of the human heart. You may advise me how to walk amid the dangers which encompass me." - -"I am all attention, madam." - -"My name is Helen Stoner, and I am living with my stepfather, who is the last survivor of one of the oldest Saxon families in England, the Roylotts of Stoke Moran, on the western border of Surrey." - -Holmes nodded his head. "The name is familiar to me," said he. - - - -"I have very little difficulty in finding what I want," said I, "for the facts are quite recent, and the matter struck me as remarkable. I feared to refer them to you, however, as I knew that you had an inquiry on hand and that you disliked the intrusion of other matters." - -"Oh, you mean the little problem of the Grosvenor Square furniture van. That is quite cleared up now--though, indeed, it was obvious from the first. Pray give me the results of your newspaper selections." - -"Here is the first notice which I can find. It is in the personal column of the Morning Post, and dates, as you see, some weeks back: 'A marriage has been arranged,' it says, 'and will, if rumour is correct, very shortly take place, between Lord Robert St. Simon, second son of the Duke of Balmoral, and Miss Hatty Doran, the only daughter of Aloysius Doran. Esq., of San Francisco, Cal., U.S.A.' That is all." - -"Terse and to the point," remarked Holmes, stretching his long, thin legs towards the fire. - -"There was a paragraph amplifying this in one of the society papers of the same week. Ah, here it is: 'There will soon be a call for protection in the marriage market, for the present free-trade principle appears to tell heavily against our home product. One by one the management of the noble houses of Great Britain is passing into the hands of our fair cousins from across the Atlantic. An important addition has been made during the last week to the list of the prizes which have been borne away by these charming invaders. Lord St. Simon, who has shown himself for over twenty years proof against the little god's arrows, has now definitely announced his approaching marriage with Miss Hatty Doran, the fascinating daughter of a California millionaire. Miss Doran, whose graceful figure and striking face attracted much attention at the Westbury House festivities, is an only child, and it is currently reported that her dowry will run to considerably over the six figures, with expectancies for the future. As it is an open secret that the Duke of Balmoral has been compelled to sell his pictures within the last few years, and as Lord St. Simon has no property of his own save the small estate of Birchmoor, it is obvious that the Californian heiress is not the only gainer by an alliance which will enable her to make the easy and common transition from a Republican lady to a British peeress.' " - -"Anything else?" asked Holmes, yawning. - -"Oh, yes; plenty. Then there is another note in the Morning Post to say that the marriage would be an absolutely quiet one, that it would be at St. George's, Hanover Square, that only half a dozen intimate friends would be invited, and that the party would return to the furnished house at Lancaster Gate which has been taken by Mr. Aloysius Doran. Two days later--that is, on Wednesday last--there is a curt announcement that the wedding had taken place, and that the honeymoon would be passed at Lord Backwater's place, near Petersfield. Those are all the notices which appeared before the disappearance of the bride." - -"Before the what?" asked Holmes with a start. - -"The vanishing of the lady." - -"When did she vanish, then?" - -"At the wedding breakfast." - -"Indeed. This is more interesting than it promised to be; quite dramatic, in fact." - -"Yes; it struck me as being a little out of the common." - -"They often vanish before the ceremony, and occasionally during the honeymoon; but I cannot call to mind anything quite so prompt as this. Pray let me have the details." - -"I warn you that they are very incomplete." - -"Perhaps we may make them less so." - -"Such as they are, they are set forth in a single article of a morning paper of yesterday, which I will read to you. It is headed, 'Singular Occurrence at a Fashionable Wedding': - -" 'The family of Lord Robert St. Simon has been thrown into the greatest consternation by the strange and painful episodes which have taken place in connection with his wedding. The ceremony, as shortly announced in the papers of yesterday, occurred on the previous morning; but it is only now that it has been possible to confirm the strange rumours which have been so persistently floating about. In spite of the attempts of the friends to hush the matter up, so much public attention has now been drawn to it that no good purpose can be served by affecting to disregard what is a common subject for conversation. - -" 'The ceremony, which was performed at St. George's, Hanover Square, was a very quiet one, no one being present save the father of the bride, Mr. Aloysius Doran, the Duchess of Balmoral, Lord Backwater, Lord Eustace and Lady Clara St. Simon (the younger brother and sister of the bridegroom), and Lady Alicia Whittington. The whole party proceeded afterwards to the house of Mr. Aloysius Doran, at Lancaster Gate, where breakfast had been prepared. It appears that some little trouble was caused by a woman, whose name has not been ascertained, who endeavoured to force her way into the house after the bridal party, alleging that she had some claim upon Lord St. Simon. It was only after a painful and prolonged scene that she was ejected by the butler and the footman. The bride, who had fortunately entered the house before this unpleasant interruption, had sat down to breakfast with the rest, when she complained of a sudden indisposition and retired to her room. Her prolonged absence having caused some comment, her father followed her, but learned from her maid that she had only come up to her chamber for an instant, caught up an ulster and bonnet, and hurried down to the passage. One of the footmen declared that he had seen a lady leave the house thus apparelled, but had refused to credit that it was his mistress, believing her to be with the company. On ascertaining that his daughter had disappeared, Mr. Aloysius Doran, in conjunction with the bridegroom, instantly put themselves in communication with the police, and very energetic inquiries are being made, which will probably result in a speedy clearing up of this very singular business. Up to a late hour last night, however, nothing had transpired as to the whereabouts of the missing lady. There are rumours of foul play in the matter, and it is said that the police have caused the arrest of the woman who had caused the original disturbance, in the belief that, from jealousy or some other motive, she may have been concerned in the strange disappearance of the bride.' " - -"And is that all?" - -"Only one little item in another of the morning papers, but it is a suggestive one." - -"And it is--" - -"That Miss Flora Millar, the lady who had caused the disturbance, has actually been arrested. It appears that she was formerly a danseuse at the Allegro, and that she has known the bridegroom for some years. There are no further particulars, and the whole case is in your hands now--so far as it has been set forth in the public press." - -"And an exceedingly interesting case it appears to be. I would not have missed it for worlds. But there is a ring at the bell, Watson, and as the clock makes it a few minutes after four, I have no doubt that this will prove to be our noble client. Do not dream of going, Watson, for I very much prefer having a witness, if only as a check to my own memory." - -"Lord Robert St. Simon," announced our page-boy, throwing open the door. A gentleman entered, with a pleasant, cultured face, high-nosed and pale, with something perhaps of petulance about the mouth, and with the steady, well-opened eye of a man whose pleasant lot it had ever been to command and to be obeyed. His manner was brisk, and yet his general appearance gave an undue impression of age, for he had a slight forward stoop and a little bend of the knees as he walked. His hair, too, as he swept off his very curly-brimmed hat, was grizzled round the edges and thin upon the top. As to his dress, it was careful to the verge of foppishness, with high collar, black frock-coat, white waistcoat, yellow gloves, patent-leather shoes, and light-coloured gaiters. He advanced slowly into the room, turning his head from left to right, and swinging in his right hand the cord which held his golden eyeglasses. - -"Good-day, Lord St. Simon," said Holmes, rising and bowing. "Pray take the basket-chair. This is my friend and colleague, Dr. Watson. Draw up a little to the fire, and we will talk this matter over." - -"A most painful matter to me, as you can most readily imagine, Mr. Holmes. I have been cut to the quick. I understand that you have already managed several delicate cases of this sort, sir, though I presume that they were hardly from the same class of society." - -"No, I am descending." - -"I beg pardon." - -"My last client of the sort was a king." - -"Oh, really! I had no idea. And which king?" - -"The King of Scandinavia." - -"What! Had he lost his wife?" - -"You can understand," said Holmes suavely, "that I extend to the affairs of my other clients the same secrecy which I promise to you in yours." - -"Of course! Very right! very right! I'm sure I beg pardon. As to my own case, I am ready to give you any information which may assist you in forming an opinion." - -"Thank you. I have already learned all that is in the public prints, nothing more. I presume that I may take it as correct--this article, for example, as to the disappearance of the bride." - -Lord St. Simon glanced over it. "Yes, it is correct, as far as it goes." - -"But it needs a great deal of supplementing before anyone could offer an opinion. I think that I may arrive at my facts most directly by questioning you." - -"Pray do so." - -"When did you first meet Miss Hatty Doran?" - -"In San Francisco, a year ago." - -"You were travelling in the States?" - -"Yes." - -"Did you become engaged then?" - -"No." - -"But you were on a friendly footing?" - -"I was amused by her society, and she could see that I was amused." - -"Her father is very rich?" - -"He is said to be the richest man on the Pacific slope." - -"And how did he make his money?" - -"In mining. He had nothing a few years ago. Then he struck gold, invested it, and came up by leaps and bounds." - -"Now, what is your own impression as to the young lady's--your wife's character?" - -The nobleman swung his glasses a little faster and stared down into the fire. "You see, Mr. Holmes," said he, "my wife was twenty before her father became a rich man. During that time she ran free in a mining camp and wandered through woods or mountains, so that her education has come from Nature rather than from the schoolmaster. She is what we call in England a tomboy, with a strong nature, wild and free, unfettered by any sort of traditions. She is impetuous--volcanic, I was about to say. She is swift in making up her mind and fearless in carrying out her resolutions. On the other hand, I would not have given her the name which I have the honour to bear"--he gave a little stately cough--"had I not thought her to be at bottom a noble woman. I believe that she is capable of heroic self-sacrifice and that anything dishonourable would be repugnant to her." - -"Have you her photograph?" - -"I brought this with me." He opened a locket and showed us the full face of a very lovely woman. It was not a photograph but an ivory miniature, and the artist had brought out the full effect of the lustrous black hair, the large dark eyes, and the exquisite mouth. Holmes gazed long and earnestly at it. Then he closed the locket and handed it back to Lord St. Simon. - -"The young lady came to London, then, and you renewed your acquaintance?" - -"Yes, her father brought her over for this last London season. I met her several times, became engaged to her, and have now married her." - -"She brought, I understand, a considerable dowry?" - -"A fair dowry. Not more than is usual in my family." - -"And this, of course, remains to you, since the marriage is a fait accompli?" - -"I really have made no inquiries on the subject." - -"Very naturally not. Did you see Miss Doran on the day before the wedding?" - -"Yes." - -"Was she in good spirits?" - -"Never better. She kept talking of what we should do in our future lives." - -"Indeed! That is very interesting. And on the morning of the wedding?" - -"She was as bright as possible--at least until after the ceremony." - -"And did you observe any change in her then?" - -"Well, to tell the truth, I saw then the first signs that I had ever seen that her temper was just a little sharp. The incident however, was too trivial to relate and can have no possible bearing upon the case." - -"Pray let us have it, for all that." - -"Oh, it is childish. She dropped her bouquet as we went towards the vestry. She was passing the front pew at the time, and it fell over into the pew. There was a moment's delay, but the gentleman in the pew handed it up to her again, and it did not appear to be the worse for the fall. Yet when I spoke to her of the matter, she answered me abruptly; and in the carriage, on our way home, she seemed absurdly agitated over this trifling cause." - -"Indeed! You say that there was a gentleman in the pew. Some of the general public were present, then?" - -"Oh, yes. It is impossible to exclude them when the church is open." - -"This gentleman was not one of your wife's friends?" - -"No, no; I call him a gentleman by courtesy, but he was quite a common-looking person. I hardly noticed his appearance. But really I think that we are wandering rather far from the point." - -"Lady St. Simon, then, returned from the wedding in a less cheerful frame of mind than she had gone to it. What did she do on re-entering her father's house?" - -"I saw her in conversation with her maid." - -"And who is her maid?" - -"Alice is her name. She is an American and came from California with her." - -"A confidential servant?" - -"A little too much so. It seemed to me that her mistress allowed her to take great liberties. Still, of course, in America they look upon these things in a different way." - -"How long did she speak to this Alice?" - -"Oh, a few minutes. I had something else to think of." - -"You did not overhear what they said?" - -"Lady St. Simon said something about 'jumping a claim.' She was accustomed to use slang of the kind. I have no idea what she meant." - -"American slang is very expressive sometimes. And what did your wife do when she finished speaking to her maid?" - -"She walked into the breakfast-room." - -"On your arm?" - -"No, alone. She was very independent in little matters like that. Then, after we had sat down for ten minutes or so, she rose hurriedly, muttered some words of apology, and left the room. She never came back." - -"But this maid, Alice, as I understand, deposes that she went to her room, covered her bride's dress with a long ulster, put on a bonnet, and went out." - -"Quite so. And she was afterwards seen walking into Hyde Park in company with Flora Millar, a woman who is now in custody, and who had already made a disturbance at Mr. Doran's house that morning." - -"Ah, yes. I should like a few particulars as to this young lady, and your relations to her." - -Lord St. Simon shrugged his shoulders and raised his eyebrows. "We have been on a friendly footing for some years--I may say on a very friendly footing. She used to be at the Allegro. I have not treated her ungenerously, and she had no just cause of complaint against me, but you know what women are, Mr. Holmes. Flora was a dear little thing, but exceedingly hot-headed and devotedly attached to me. She wrote me dreadful letters when she heard that I was about to be married, and, to tell the truth, the reason why I had the marriage celebrated so quietly was that I feared lest there might be a scandal in the church. She came to Mr. Doran's door just after we returned, and she endeavoured to push her way in, uttering very abusive expressions towards my wife, and even threatening her, but I had foreseen the possibility of something of the sort, and I had two police fellows there in private clothes, who soon pushed her out again. She was quiet when she saw that there was no good in making a row." - -"Did your wife hear all this?" - -"No, thank goodness, she did not." - -"And she was seen walking with this very woman afterwards?" - -"Yes. That is what Mr. Lestrade, of Scotland Yard, looks upon as so serious. It is thought that Flora decoyed my wife out and laid some terrible trap for her." - -"Well, it is a possible supposition." - -"You think so, too?" - -"I did not say a probable one. But you do not yourself look upon this as likely?" - -"I do not think Flora would hurt a fly." - -"Still, jealousy is a strange transformer of characters. Pray what is your own theory as to what took place?" - -"Well, really, I came to seek a theory, not to propound one. I have given you all the facts. Since you ask me, however, I may say that it has occurred to me as possible that the excitement of this affair, the consciousness that she had made so immense a social stride, had the effect of causing some little nervous disturbance in my wife." - -"In short, that she had become suddenly deranged?" - -"Well, really, when I consider that she has turned her back--I will not say upon me, but upon so much that many have aspired to without success--I can hardly explain it in any other fashion." - -"Well, certainly that is also a conceivable hypothesis," said Holmes, smiling. "And now, Lord St. Simon, I think that I have nearly all my data. May I ask whether you were seated at the breakfast-table so that you could see out of the window?" - -"We could see the other side of the road and the Park." - -"Quite so. Then I do not think that I need to detain you longer. I shall communicate with you." - -"Should you be fortunate enough to solve this problem," said our client, rising. - -"I have solved it." - -"Eh? What was that?" - -"I say that I have solved it." - -"Where, then, is my wife?" - -"That is a detail which I shall speedily supply." - -Lord St. Simon shook his head. "I am afraid that it will take wiser heads than yours or mine," he remarked, and bowing in a stately, old-fashioned manner he departed. - -"It is very good of Lord St. Simon to honour my head by putting it on a level with his own," said Sherlock Holmes, laughing. "I think that I shall have a whisky and soda and a cigar after all this cross-questioning. I had formed my conclusions as to the case before our client came into the room." - -"My dear Holmes!" - -"I have notes of several similar cases, though none, as I remarked before, which were quite as prompt. My whole examination served to turn my conjecture into a certainty. Circumstantial evidence is occasionally very convincing, as when you find a trout in the milk, to quote Thoreau's example." - -"But I have heard all that you have heard." - -"Without, however, the knowledge of pre-existing cases which serves me so well. There was a parallel instance in Aberdeen some years back, and something on very much the same lines at Munich the year after the Franco-Prussian War. It is one of these cases--but, hullo, here is Lestrade! Good-afternoon, Lestrade! You will find an extra tumbler upon the sideboard, and there are cigars in the box." - -The official detective was attired in a pea-jacket and cravat, which gave him a decidedly nautical appearance, and he carried a black canvas bag in his hand. With a short greeting he seated himself and lit the cigar which had been offered to him. - -"What's up, then?" asked Holmes with a twinkle in his eye. "You look dissatisfied." - -"And I feel dissatisfied. It is this infernal St. Simon marriage case. I can make neither head nor tail of the business." - -"Really! You surprise me." - -"Who ever heard of such a mixed affair? Every clue seems to slip through my fingers. I have been at work upon it all day." - -"And very wet it seems to have made you," said Holmes laying his hand upon the arm of the pea-jacket. - -"Yes, I have been dragging the Serpentine." - -"In heaven's name, what for?" - -"In search of the body of Lady St. Simon." - -Sherlock Holmes leaned back in his chair and laughed heartily. - -"Have you dragged the basin of Trafalgar Square fountain?" he asked. - -"Why? What do you mean?" - -"Because you have just as good a chance of finding this lady in the one as in the other." - -Lestrade shot an angry glance at my companion. "I suppose you know all about it," he snarled. - -"Well, I have only just heard the facts, but my mind is made up." - -"Oh, indeed! Then you think that the Serpentine plays no part in the matter?" - -"I think it very unlikely." - -"Then perhaps you will kindly explain how it is that we found this in it?" He opened his bag as he spoke, and tumbled onto the floor a wedding-dress of watered silk, a pair of white satin shoes and a bride's wreath and veil, all discoloured and soaked in water. "There," said he, putting a new wedding-ring upon the top of the pile. "There is a little nut for you to crack, Master Holmes." - -"Oh, indeed!" said my friend, blowing blue rings into the air. "You dragged them from the Serpentine?" - -"No. They were found floating near the margin by a park-keeper. They have been identified as her clothes, and it seemed to me that if the clothes were there the body would not be far off." - -"By the same brilliant reasoning, every man's body is to be found in the neighbourhood of his wardrobe. And pray what did you hope to arrive at through this?" - -"At some evidence implicating Flora Millar in the disappearance." - -"I am afraid that you will find it difficult." - -"Are you, indeed, now?" cried Lestrade with some bitterness. "I am afraid, Holmes, that you are not very practical with your deductions and your inferences. You have made two blunders in as many minutes. This dress does implicate Miss Flora Millar." - -"And how?" - -"In the dress is a pocket. In the pocket is a card-case. In the card-case is a note. And here is the very note." He slapped it down upon the table in front of him. "Listen to this: 'You will see me when all is ready. Come at once. F. H. M.' Now my theory all along has been that Lady St. Simon was decoyed away by Flora Millar, and that she, with confederates, no doubt, was responsible for her disappearance. Here, signed with her initials, is the very note which was no doubt quietly slipped into her hand at the door and which lured her within their reach." - -"Very good, Lestrade," said Holmes, laughing. "You really are very fine indeed. Let me see it." He took up the paper in a listless way, but his attention instantly became riveted, and he gave a little cry of satisfaction. "This is indeed important," said he. - -"Ha! you find it so?" - -"Extremely so. I congratulate you warmly." - -Lestrade rose in his triumph and bent his head to look. "Why," he shrieked, "you're looking at the wrong side!" - -"On the contrary, this is the right side." - -"The right side? You're mad! Here is the note written in pencil over here." - -"And over here is what appears to be the fragment of a hotel bill, which interests me deeply." - -"There's nothing in it. I looked at it before," said Lestrade. " 'Oct. 4th, rooms 8s., breakfast 2s. 6d., cocktail 1s., lunch 2s. 6d., glass sherry, 8d.' I see nothing in that." - -"Very likely not. It is most important, all the same. As to the note, it is important also, or at least the initials are, so I congratulate you again." - -"I've wasted time enough," said Lestrade, rising. "I believe in hard work and not in sitting by the fire spinning fine theories. Good-day, Mr. Holmes, and we shall see which gets to the bottom of the matter first." He gathered up the garments, thrust them into the bag, and made for the door. - -"Just one hint to you, Lestrade," drawled Holmes before his rival vanished; "I will tell you the true solution of the matter. Lady St. Simon is a myth. There is not, and there never has been, any such person." - -Lestrade looked sadly at my companion. Then he turned to me, tapped his forehead three times, shook his head solemnly, and hurried away. - -He had hardly shut the door behind him when Holmes rose to put on his overcoat. "There is something in what the fellow says about outdoor work," he remarked, "so I think, Watson, that I must leave you to your papers for a little." - -It was after five o'clock when Sherlock Holmes left me, but I had no time to be lonely, for within an hour there arrived a confectioner's man with a very large flat box. This he unpacked with the help of a youth whom he had brought with him, and presently, to my very great astonishment, a quite epicurean little cold supper began to be laid out upon our humble lodging-house mahogany. There were a couple of brace of cold woodcock, a pheasant, a pate de foie gras pie with a group of ancient and cobwebby bottles. Having laid out all these luxuries, my two visitors vanished away, like the genii of the Arabian Nights, with no explanation save that the things had been paid for and were ordered to this address. - -Just before nine o'clock Sherlock Holmes stepped briskly into the room. His features were gravely set, but there was a light in his eye which made me think that he had not been disappointed in his conclusions. - -"They have laid the supper, then," he said, rubbing his hands. - -"You seem to expect company. They have laid for five." - -"Yes, I fancy we may have some company dropping in," said he. "I am surprised that Lord St. Simon has not already arrived. Ha! I fancy that I hear his step now upon the stairs." - -It was indeed our visitor of the afternoon who came bustling in, dangling his glasses more vigorously than ever, and with a very perturbed expression upon his aristocratic features. - - - -To conserve the patient's strength by preventing or diminishing the -severity of the spasms, he should be placed in a quiet room, and every -form of disturbance avoided. Sedatives, such as bromides, paraldehyde, -or opium, must be given in large doses. Chloral is perhaps the best, and -the patient should rarely have less than 150 grains in twenty-four -hours. When he is unable to swallow, it should be given by the rectum. -The administration of chloroform is of value in conserving the strength -of the patient, by abolishing the spasms, and enabling the attendants to -administer nourishment or drugs either through a stomach tube or by the -rectum. Extreme elevation of temperature is met by tepid sponging. It is -necessary to use the catheter if retention of urine occurs. - - -HYDROPHOBIA - -Hydrophobia is an acute infective disease following on the bite of a -rabid animal. It most commonly follows the bite or lick of a rabid dog -or cat. The virus appears to be communicated through the saliva of the -animal, and to show a marked affinity for nerve tissues; and the disease -is most likely to develop when the patient is infected on the face or -other uncovered part, or in a part richly endowed with nerves. - -A dog which has bitten a person should on no account be killed until its -condition has been proved one way or the other. Should rabies develop -and its destruction become necessary, the head and spinal cord should be -retained and forwarded, packed in ice, to a competent observer. Much -anxiety to the person bitten and to his friends would be avoided if -these rules were observed, because in many cases it will be shown that -the animal did not after all suffer from rabies, and that the patient -consequently runs no risk. If, on the other hand, rabies is proved to be -present, the patient should be submitted to the Pasteur treatment. - -_Clinical Features._--There is almost always a history of the patient -having been bitten or licked by an animal supposed to suffer from -rabies. The incubation period averages about forty days, but varies from -a fortnight to seven or eight months, and is shorter in young than in -old persons. The original wound has long since healed, and beyond a -slight itchiness or pain shooting along the nerves of the part, shows no -sign of disturbance. A few days of general malaise, with chills and -giddiness precede the onset of the acute manifestations, which affect -chiefly the muscles of deglutition and respiration. One of the earliest -signs is that the patient has periodically a sudden catch in his -breathing "resembling what often occurs when a person goes into a cold -bath." This is due to spasm of the diaphragm, and is frequently -accompanied by a loud-sounding hiccough, likened by the laity to the -barking of a dog. Difficulty in swallowing fluids may be the first -symptom. - -The spasms rapidly spread to all the muscles of deglutition and -respiration, so that the patient not only has the greatest difficulty in -swallowing, but has a constant sense of impending suffocation. To add to -his distress, a copious secretion of viscid saliva fills his mouth. Any -voluntary effort, as well as all forms of external stimuli, only serve -to aggravate the spasms which are always induced by the attempt to -swallow fluid, or even by the sound of running water. - -The temperature is raised; the pulse is small, rapid, and intermittent; -and the urine may contain sugar and albumen. - -The mind may remain clear to the end, or the patient may have delusions, -supposing himself to be surrounded by terrifying forms. There is always -extreme mental agitation and despair, and the sufferer is in constant -fear of his impending fate. Happily the inevitable issue is not long -delayed, death usually occurring in from two to four days from the -onset. The symptoms of the disease are so characteristic that there is -no difficulty in diagnosis. The only condition with which it is liable -to be confused is the variety of cephalic tetanus in which the muscles -of deglutition are specially involved--the so-called tetanus -hydrophobicus. - -_Prophylaxis._--The bite of an animal suspected of being rabid should be -cauterised at once by means of the actual or Paquelin cautery, or by a -strong chemical escharotic such as pure carbolic acid, after which -antiseptic dressings are applied. - -It is, however, to Pasteur's _preventive inoculation_ that we must look -for our best hope of averting the onset of symptoms. "It may now be -taken as established that a grave responsibility rests on those -concerned if a person bitten by a mad animal is not subjected to the -Pasteur treatment" (Muir and Ritchie). - -This method is based on the fact that the long incubation period of the -disease admits of the patient being inoculated with a modified virus -producing a mild attack, which protects him from the natural disease. - -_Treatment._--When the symptoms have once developed they can only be -palliated. The patient must be kept absolutely quiet and free from all -sources of irritation. The spasms may be diminished by means of chloral -and bromides, or by chloroform inhalation. - - -ANTHRAX - -Anthrax is a comparatively rare disease, communicable to man from -certain of the lower animals, such as sheep, oxen, horses, deer, and -other herbivora. In animals it is characterised by symptoms of acute -general poisoning, and, from the fact that it produces a marked -enlargement of the spleen, is known in veterinary surgery as "splenic -fever." - -The _bacillus anthracis_ (Fig. 27), the largest of the known pathogenic -bacteria, occurs in groups or in chains made up of numerous bacilli, -each bacillus measuring from 6 to 8 u in length. The organisms are found -in enormous numbers throughout the bodies of animals that have died of -anthrax, and are readily recognised and cultivated. Sporulation only -takes place outside the body, probably because free oxygen is necessary -to the process. In the spore-free condition, the organisms are readily -destroyed by ordinary germicides, and by the gastric juice. The spores, -on the other hand, have a high degree of resistance. Not only do they -remain viable in the dry state for long periods, even up to a year, but -they survive boiling for five minutes, and must be subjected to dry heat -at 140 o C. for several hours before they are destroyed. - -[Illustration: FIG. 27.--Bacillus of Anthrax in section of skin, from a -case of malignant pustule; shows vesicle containing bacilli. x 400 diam. -Gram's stain.] - -_Clinical Varieties of Anthrax._--In man, anthrax may manifest itself in -one of three clinical forms. - -It may be transmitted by means of spores or bacilli directly from a -diseased animal to those who, by their occupation or otherwise, are -brought into contact with it--for example, shepherds, butchers, -veterinary surgeons, or hide-porters. Infection may occur on the face by -the use of a shaving-brush contaminated by spores. The path of infection -is usually through an abrasion of the skin, and the primary -manifestations are local, constituting what is known as _the malignant -pustule_. - -In other cases the disease is contracted through the inhalation of the -dried spores into the respiratory passages. This occurs oftenest in -those who work amongst wool, fur, and rags, and a form of acute -pneumonia of great virulence ensues. This affection is known as -_wool-sorter's disease_, and is almost universally fatal. - -There is reason to believe that infection may also take place by means -of spores ingested into the alimentary canal in meat or milk derived -from diseased animals, or in infected water. - - -become associated with branches from the musculo-cutaneous is followed -by a loss of sensibility on the radial side of the hand and thumb. Wounds -on the dorsal surface of the wrist and forearm are often followed by -loss of sensibility over a larger area, because the musculo-cutaneous -nerve is divided as well, and some of the fibres of the lower lateral -cutaneous branch of the radial. - -[Illustration: FIG. 91.--To illustrate the Loss of Sensation produced by -Division of the Median Nerve. The area of complete cutaneous -insensibility is shaded black. The parts insensitive to light touch and -to intermediate degrees of temperature are enclosed within the dotted -line. - -(After Head and Sherren.)] - -#The Median Nerve# is most frequently injured in wounds made by broken -glass in the region of the wrist. It may also be injured in fractures of -the lower end of the humerus, in fractures of both bones of the forearm, -and as a result of pressure by splints. After _division at the elbow_, -there is impairment of mobility which affects the thumb, and to a less -extent the index finger: the terminal phalanx of the thumb cannot be -flexed owing to the paralysis of the flexor pollicis longus, and the -index can only be flexed at its metacarpo-phalangeal joint by the -interosseous muscles attached to it. Pronation of the forearm is feeble, -and is completed by the weight of the hand. After _division at the -wrist_, the abductor-opponens group of muscles and the two lateral -lumbricals only are affected; the abduction of the thumb can be feebly -imitated by the short extensor and the long abductor (ext. ossis -metacarpi pollicis), while opposition may be simulated by contraction of -the long flexor and the short abductor of the thumb; the paralysis of -the two medial lumbricals produces no symptoms that can be recognised. -It is important to remember that when the median nerve is divided at the -wrist, deep touch can be appreciated over the whole of the area -supplied by the nerve; the injury, therefore, is liable to be over -looked. If, however, the tendons are divided as well as the nerve, there -is insensibility to deep touch. The areas of epicritic and of -protopathic insensibility are illustrated in Fig. 91. The division of -the nerve at the elbow, or even at the axilla, does not increase the -extent of the loss of epicritic or protopathic sensibility, but usually -affects deep sensibility. - -[Illustration: FIG. 92.--To illustrate Loss of Sensation produced by -complete Division of Ulnar Nerve. Loss of all forms of cutaneous -sensibility is represented by the shaded area. The parts insensitive to -light touch and to intermediate degrees of heat and cold are enclosed -within the dotted line. - -(Head and Sherren.)] - -#The Ulnar Nerve.#--The most common injury of this nerve is its division -in transverse accidental wounds just above the wrist. In the arm it may -be contused, along with the radial, in crutch paralysis; in the region -of the elbow it may be injured in fractures or dislocations, or it may -be accidentally divided in the operation for excising the elbow-joint. - - -same class as himself and possessed the same breeding and -traditions, Bolkonski would soon have discovered his weak, human, -unheroic sides; but as it was, Speranski's strange and logical turn of -mind inspired him with respect all the more because he did not quite -understand him. Moreover, Speranski, either because he appreciated the -other's capacity or because he considered it necessary to win him to -his side, showed off his dispassionate calm reasonableness before -Prince Andrew and flattered him with that subtle flattery which goes -hand in hand with self-assurance and consists in a tacit assumption -that one's companion is the only man besides oneself capable of -understanding the folly of the rest of mankind and the -reasonableness and profundity of one's own ideas. - -During their long conversation on Wednesday evening, Speranski -more than once remarked: "We regard everything that is above the -common level of rooted custom..." or, with a smile: "But we want the -wolves to be fed and the sheep to be safe..." or: "They cannot -understand this..." and all in a way that seemed to say: "We, you -and I, understand what they are and who we are." - -This first long conversation with Speranski only strengthened in -Prince Andrew the feeling he had experienced toward him at their first -meeting. He saw in him a remarkable, clear-thinking man of vast -intellect who by his energy and persistence had attained power, -which he was using solely for the welfare of Russia. In Prince -Andrew's eyes Speranski was the man he would himself have wished to -be--one who explained all the facts of life reasonably, considered -important only what was rational, and was capable of applying the -standard of reason to everything. Everything seemed so simple and -clear in Speranski's exposition that Prince Andrew involuntarily -agreed with him about everything. If he replied and argued, it was -only because he wished to maintain his independence and not submit -to Speranski's opinions entirely. Everything was right and -everything was as it should be: only one thing disconcerted Prince -Andrew. This was Speranski's cold, mirrorlike look, which did not -allow one to penetrate to his soul, and his delicate white hands, -which Prince Andrew involuntarily watched as one does watch the -hands of those who possess power. This mirrorlike gaze and those -delicate hands irritated Prince Andrew, he knew not why. He was -unpleasantly struck, too, by the excessive contempt for others that he -observed in Speranski, and by the diversity of lines of argument he -used to support his opinions. He made use of every kind of mental -device, except analogy, and passed too boldly, it seemed to Prince -Andrew, from one to another. Now he would take up the position of a -practical man and condemn dreamers; now that of a satirist, and -laugh ironically at his opponents; now grow severely logical, or -suddenly rise to the realm of metaphysics. (This last resource was one -he very frequently employed.) He would transfer a question to -metaphysical heights, pass on to definitions of space, time, and -thought, and, having deduced the refutation he needed, would again -descend to the level of the original discussion. - -In general the trait of Speranski's mentality which struck Prince -Andrew most was his absolute and unshakable belief in the power and -authority of reason. It was evident that the thought could never occur -to him which to Prince Andrew seemed so natural, namely, that it is -after all impossible to express all one thinks; and that he had -never felt the doubt, "Is not all I think and believe nonsense?" And -it was just this peculiarity of Speranski's mind that particularly -attracted Prince Andrew. - -During the first period of their acquaintance Bolkonski felt a -passionate admiration for him similar to that which he had once felt -for Bonaparte. The fact that Speranski was the son of a village -priest, and that stupid people might meanly despise him on account -of his humble origin (as in fact many did), caused Prince Andrew to -cherish his sentiment for him the more, and unconsciously to -strengthen it. - -On that first evening Bolkonski spent with him, having mentioned the -Commission for the Revision of the Code of Laws, Speranski told him -sarcastically that the Commission had existed for a hundred and -fifty years, had cost millions, and had done nothing except that -Rosenkampf had stuck labels on the corresponding paragraphs of the -different codes. - -"And that is all the state has for the millions it has spent," -said he. "We want to give the Senate new juridical powers, but we have -no laws. That is why it is a sin for men like you, Prince, not to -serve in these times!" - -Prince Andrew said that for that work an education in -jurisprudence was needed which he did not possess. - -"But nobody possesses it, so what would you have? It is a vicious -circle from which we must break a way out." - -A week later Prince Andrew was a member of the Committee on Army -Regulations and--what he had not at all expected--was chairman of a -section of the committee for the revision of the laws. At -Speranski's request he took the first part of the Civil Code that -was being drawn up and, with the aid of the Code Napoleon and the -Institutes of Justinian, he worked at formulating the section on -Personal Rights. - - - - - -CHAPTER VII - - -Nearly two years before this, in 1808, Pierre on returning to -Petersburg after visiting his estates had involuntarily found -himself in a leading position among the Petersburg Freemasons. He -arranged dining and funeral lodge meetings, enrolled new members, -and busied himself uniting various lodges and acquiring authentic -charters. He gave money for the erection of temples and supplemented -as far as he could the collection of alms, in regard to which the -majority of members were stingy and irregular. He supported almost -singlehanded a poorhouse the order had founded in Petersburg. - -His life meanwhile continued as before, with the same infatuations -and dissipations. He liked to dine and drink well, and though he -considered it immoral and humiliating could not resist the temptations -of the bachelor circles in which he moved. - -Amid the turmoil of his activities and distractions, however, Pierre -at the end of a year began to feel that the more firmly he tried to -rest upon it, the more Masonic ground on which he stood gave way under -him. At the same time he felt that the deeper the ground sank under -him the closer bound he involuntarily became to the order. When he had -joined the Freemasons he had experienced the feeling of one who -confidently steps onto the smooth surface of a bog. When he put his -foot down it sank in. To make quite sure of the firmness the ground, -he put his other foot down and sank deeper still, became stuck in -it, and involuntarily waded knee-deep in the bog. - -Joseph Alexeevich was not in Petersburg--he had of late stood -aside from the affairs of the Petersburg lodges, and lived almost -entirely in Moscow. All the members of the lodges were men Pierre knew -in ordinary life, and it was difficult for him to regard them merely -as Brothers in Freemasonry and not as Prince B. or Ivan Vasilevich D., -whom he knew in society mostly as weak and insignificant men. Under -the Masonic aprons and insignia he saw the uniforms and decorations at -which they aimed in ordinary life. Often after collecting alms, and -reckoning up twenty to thirty rubles received for the most part in -promises from a dozen members, of whom half were as well able to pay -as himself, Pierre remembered the Masonic vow in which each Brother -promised to devote all his belongings to his neighbor, and doubts on -which he tried not to dwell arose in his soul. - -He divided the Brothers he knew into four categories. In the first -he put those who did not take an active part in the affairs of the -lodges or in human affairs, but were exclusively occupied with the -mystical science of the order: with questions of the threefold -designation of God, the three primordial elements--sulphur, mercury, -and salt--or the meaning of the square and all the various figures -of the temple of Solomon. Pierre respected this class of Brothers to -which the elder ones chiefly belonged, including, Pierre thought, -Joseph Alexeevich himself, but he did not share their interests. His -heart was not in the mystical aspect of Freemasonry. - -In the second category Pierre reckoned himself and others like -him, seeking and vacillating, who had not yet found in Freemasonry a -straight and comprehensible path, but hoped to do so. - -In the third category he included those Brothers (the majority) -who saw nothing in Freemasonry but the external forms and -ceremonies, and prized the strict performance of these forms without -troubling about their purport or significance. Such were Willarski and -even the Grand Master of the principal lodge. - -Finally, to the fourth category also a great many Brothers belonged, -particularly those who had lately joined. These according to -Pierre's observations were men who had no belief in anything, nor -desire for anything, but joined the Freemasons merely to associate -with the wealthy young Brothers who were influential through their -connections or rank, and of whom there were very many in the lodge. - -Pierre began to feel dissatisfied with what he was doing. -Freemasonry, at any rate as he saw it here, sometimes seemed to him -based merely on externals. He did not think of doubting Freemasonry -itself, but suspected that Russian Masonry had taken a wrong path -and deviated from its original principles. And so toward the end of -the year he went abroad to be initiated into the higher secrets of the -order. - -In the summer of 1809 Pierre returned to Petersburg. Our -Freemasons knew from correspondence with those abroad that Bezukhov -had obtained the confidence of many highly placed persons, had been -initiated into many mysteries, had been raised to a higher grade, -and was bringing back with him much that might conduce to the -advantage of the Masonic cause in Russia. The Petersburg Freemasons -all came to see him, tried to ingratiate themselves with him, and it -seemed to them all that he was preparing something for them and -concealing it. - -A solemn meeting of the lodge of the second degree was convened, -at which Pierre promised to communicate to the Petersburg Brothers -what he had to deliver to them from the highest leaders of their -order. The meeting was a full one. After the usual ceremonies Pierre -rose and began his address. - -"Dear Brothers," he began, blushing and stammering, with a written -speech in his hand, "it is not sufficient to observe our mysteries -in the seclusion of our lodge--we must act--act! We are drowsing, -but we must act." Pierre raised his notebook and began to read. - -"For the dissemination of pure truth and to secure the triumph of -virtue," he read, "we must cleanse men from prejudice, diffuse -principles in harmony with the spirit of the times, undertake the -education of the young, unite ourselves in indissoluble bonds with the -wisest men, boldly yet prudently overcome superstitions, infidelity, -and folly, and form of those devoted to us a body linked together by -unity of purpose and possessed of authority and power. - -"To attain this end we must secure a preponderance of virtue over -vice and must endeavor to secure that the honest man may, even in this -world, receive a lasting reward for his virtue. But in these great -endeavors we are gravely hampered by the political institutions of -today. What is to be done in these circumstances? To favor -revolutions, overthrow everything, repel force by force?... No! We are -very far from that. Every violent reform deserves censure, for it -quite fails to remedy evil while men remain what they are, and also -because wisdom needs no violence. - -"The whole plan of our order should be based on the idea of -preparing men of firmness and virtue bound together by unity of -conviction--aiming at the punishment of vice and folly, and -patronizing talent and virtue: raising worthy men from the dust and -attaching them to our Brotherhood. Only then will our order have the -power unobtrusively to bind the hands of the protectors of disorder -and to control them without their being aware of it. In a word, we -must found a form of government holding universal sway, which should -be diffused over the whole world without destroying the bonds of -citizenship, and beside which all other governments can continue in -their customary course and do everything except what impedes the great -aim of our order, which is to obtain for virtue the victory over vice. -This aim was that of Christianity itself. It taught men to be wise and -good and for their own benefit to follow the example and instruction -of the best and wisest men. - -"At that time, when everything was plunged in darkness, preaching -alone was of course sufficient. The novelty of Truth endowed her -with special strength, but now we need much more powerful methods. -It is now necessary that man, governed by his senses, should find in -virtue a charm palpable to those senses. It is impossible to eradicate -the passions; but we must strive to direct them to a noble aim, and it -is therefore necessary that everyone should be able to satisfy his -passions within the limits of virtue. Our order should provide means -to that end. - -"As soon as we have a certain number of worthy men in every state, -each of them again training two others and all being closely united, -everything will be possible for our order, which has already in secret -accomplished much for the welfare of mankind." - -This speech not only made a strong impression, but created -excitement in the lodge. The majority of the Brothers, seeing in it -dangerous designs of Illuminism,* met it with a coldness that -surprised Pierre. The Grand Master began answering him, and Pierre -began developing his views with more and more warmth. It was long -since there had been so stormy a meeting. Parties were formed, some -accusing Pierre of Illuminism, others supporting him. At that -meeting he was struck for the first time by the endless variety of -men's minds, which prevents a truth from ever presenting itself -identically to two persons. Even those members who seemed to be on his -side understood him in their own way with limitations and -alterations he could not agree to, as what he always wanted most was -to convey his thought to others just as he himself understood it. - - -*The Illuminati sought to substitute republican for monarchical -institutions. - - -At the end of the meeting the Grand Master with irony and ill-will -reproved Bezukhov for his vehemence and said it was not love of virtue -alone, but also a love of strife that had moved him in the dispute. -Pierre did not answer him and asked briefly whether his proposal would -be accepted. He was told that it would not, and without waiting for -the usual formalities he left the lodge and went home. - - - - - -CHAPTER VIII - - -Again Pierre was overtaken by the depression he so dreaded. For -three days after the delivery of his speech at the lodge he lay on a -sofa at home receiving no one and going nowhere. - -It was just then that he received a letter from his wife, who -implored him to see her, telling him how grieved she was about him and -how she wished to devote her whole life to him. - -At the end of the letter she informed him that in a few days she -would return to Petersburg from abroad. - -Following this letter one of the Masonic Brothers whom Pierre -respected less than the others forced his way in to see him and, -turning the conversation upon Pierre's matrimonial affairs, by way -of fraternal advice expressed the opinion that his severity to his -wife was wrong and that he was neglecting one of the first rules of -Freemasonry by not forgiving the penitent. - -At the same time his mother-in-law, Prince Vasili's wife, sent to -him imploring him to come if only for a few minutes to discuss a -most important matter. Pierre saw that there was a conspiracy -against him and that they wanted to reunite him with his wife, and -in the mood he then was, this was not even unpleasant to him. -Nothing mattered to him. Nothing in life seemed to him of much -importance, and under the influence of the depression that possessed -him he valued neither his liberty nor his resolution to punish his -wife. - -"No one is right and no one is to blame; so she too is not to -blame," he thought. - -If he did not at once give his consent to a reunion with his wife, -it was only because in his state of depression he did not feel able to -take any step. Had his wife come to him, he would not have turned -her away. Compared to what preoccupied him, was it not a matter of -indifference whether he lived with his wife or not? - -Without replying either to his wife or his mother-in-law, Pierre -late one night prepared for a journey and started for Moscow to see -Joseph Alexeevich. This is what he noted in his diary: - - -Moscow, 17th November - -I have just returned from my benefactor, and hasten to write down -what I have experienced. Joseph Alexeevich is living poorly and has -for three years been suffering from a painful disease of the -bladder. No one has ever heard him utter a groan or a word of -complaint. From morning till late at night, except when he eats his -very plain food, he is working at science. He received me graciously -and made me sit down on the bed on which he lay. I made the sign of -the Knights of the East and of Jerusalem, and he responded in the same -manner, asking me with a mild smile what I had learned and gained in -the Prussian and Scottish lodges. I told him everything as best I -could, and told him what I had proposed to our Petersburg lodge, of -the bad reception I had encountered, and of my rupture with the -Brothers. Joseph Alexeevich, having remained silent and thoughtful for -a good while, told me his view of the matter, which at once lit up for -me my whole past and the future path I should follow. He surprised -me by asking whether I remembered the threefold aim of the order: -(1) The preservation and study of the mystery. (2) The purification -and reformation of oneself for its reception, and (3) The -improvement of the human race by striving for such purification. Which -is the principal aim of these three? Certainly self-reformation and -self-purification. Only to this aim can we always strive independently -of circumstances. But at the same time just this aim demands the -greatest efforts of us; and so, led astray by pride, losing sight of -this aim, we occupy ourselves either with the mystery which in our -impurity we are unworthy to receive, or seek the reformation of the -human race while ourselves setting an example of baseness and -profligacy. Illuminism is not a pure doctrine, just because it is -attracted by social activity and puffed up by pride. On this ground -Joseph Alexeevich condemned my speech and my whole activity, and in -the depth of my soul I agreed with him. Talking of my family affairs -he said to me, "the chief duty of a true Mason, as I have told you, -lies in perfecting himself. We often think that by removing all the -difficulties of our life we shall more quickly reach our aim, but on -the contrary, my dear sir, it is only in the midst of worldly cares -that we can attain our three chief aims: (1) Self-knowledge--for man -can only know himself by comparison, (2) Self-perfecting, which can -only be attained by conflict, and (3) The attainment of the chief -virtue--love of death. Only the vicissitudes of life can show us its -vanity and develop our innate love of death or of rebirth to a new -life." These words are all the more remarkable because, in spite of -his great physical sufferings, Joseph Alexeevich is never weary of -life though he loves death, for which--in spite of the purity and -loftiness of his inner man--he does not yet feel himself -sufficiently prepared. My benefactor then explained to me fully the -meaning of the Great Square of creation and pointed out to me that the -numbers three and seven are the basis of everything. He advised me not -to avoid intercourse with the Petersburg Brothers, but to take up only -second-grade posts in the lodge, to try, while diverting the -Brothers from pride, to turn them toward the true path -self-knowledge and self-perfecting. Besides this he advised me for -myself personally above all to keep a watch over myself, and to that -end he gave me a notebook, the one I am now writing in and in which -I will in future note down all my actions. - - -Petersburg, 23rd November - -I am again living with my wife. My mother-in-law came to me in tears -and said that Helene was here and that she implored me to hear her; -that she was innocent and unhappy at my desertion, and much more. I -knew that if I once let myself see her I should not have strength to -go on refusing what she wanted. In my perplexity I did not know -whose aid and advice to seek. Had my benefactor been here he would -have told me what to do. I went to my room and reread Joseph -Alexeevich's letters and recalled my conversations with him, and -deduced from it all that I ought not to refuse a suppliant, and -ought to reach a helping hand to everyone--especially to one so -closely bound to me--and that I must bear my cross. But if I forgive -her for the sake of doing right, then let union with her have only a -spiritual aim. That is what I decided, and what I wrote to Joseph -Alexeevich. I told my wife that I begged her to forget the past, to -forgive me whatever wrong I may have done her, and that I had -nothing to forgive. It gave me joy to tell her this. She need not know -how hard it was for me to see her again. I have settled on the upper -floor of this big house and am experiencing a happy feeling of -regeneration. - - - - - -CHAPTER IX - - -At that time, as always happens, the highest society that met at -court and at the grand balls was divided into several circles, each -with its own particular tone. The largest of these was the French -circle of the Napoleonic alliance, the circle of Count Rumyantsev -and Caulaincourt. In this group Helene, as soon as she had settled -in Petersburg with her husband, took a very prominent place. She was -visited by the members of the French embassy and by many belonging -to that circle and noted for their intellect and polished manners. - -Helene had been at Erfurt during the famous meeting of the -Emperors and had brought from there these connections with the -Napoleonic notabilities. At Erfurt her success had been brilliant. -Napoleon himself had noticed her in the theater and said of her: -"C'est un superbe animal."* Her success as a beautiful and elegant -woman did not surprise Pierre, for she had become even handsomer -than before. What did surprise him was that during these last two -years his wife had succeeded in gaining the reputation "d' une femme -charmante, aussi spirituelle que belle."*[2] The distinguished -Prince de Ligne wrote her eight-page letters. Bilibin saved up his -epigrams to produce them in Countess Bezukhova's presence. To be -received in the Countess Bezukhova's salon was regarded as a diploma -of intellect. Young men read books before attending Helene's evenings, -to have something to say in her salon, and secretaries of the embassy, -and even ambassadors, confided diplomatic secrets to her, so that in a -way Helene was a power. Pierre, who knew she was very stupid, -sometimes attended, with a strange feeling of perplexity and fear, her -evenings and dinner parties, where politics, poetry, and philosophy -were discussed. At these parties his feelings were like those of a -conjuror who always expects his trick to be found out at any moment. -But whether because stupidity was just what was needed to run such a -salon, or because those who were deceived found pleasure in the -deception, at any rate it remained unexposed and Helene Bezukhova's -reputation as a lovely and clever woman became so firmly established -that she could say the emptiest and stupidest things and everybody -would go into raptures over every word of hers and look for a profound -meaning in it of which she herself had no conception. - - -*"That's a superb animal." - -*[2] "Of a charming woman, as witty as she is lovely." - - -Pierre was just the husband needed for a brilliant society woman. He -was that absent-minded crank, a grand seigneur husband who was in no -one's way, and far from spoiling the high tone and general -impression of the drawing room, he served, by the contrast he -presented to her, as an advantageous background to his elegant and -tactful wife. Pierre during the last two years, as a result of his -continual absorption in abstract interests and his sincere contempt -for all else, had acquired in his wife's circle, which did not -interest him, that air of unconcern, indifference, and benevolence -toward all, which cannot be acquired artificially and therefore -inspires involuntary respect. He entered his wife's drawing room as -one enters a theater, was acquainted with everybody, equally pleased -to see everyone, and equally indifferent to them all. Sometimes he -joined in a conversation which interested him and, regardless of -whether any "gentlemen of the embassy" were present or not, -lispingly expressed his views, which were sometimes not at all in -accord with the accepted tone of the moment. But the general opinion -concerning the queer husband of "the most distinguished woman in -Petersburg" was so well established that no one took his freaks -seriously. - -Among the many young men who frequented her house every day, Boris -Drubetskoy, who had already achieved great success in the service, was -the most intimate friend of the Bezukhov household since Helene's -return from Erfurt. Helene spoke of him as "mon page" and treated -him like a child. Her smile for him was the same as for everybody, but -sometimes that smile made Pierre uncomfortable. Toward him Boris -behaved with a particularly dignified and sad deference. This shade of -deference also disturbed Pierre. He had suffered so painfully three -years before from the mortification to which his wife had subjected -him that he now protected himself from the danger of its repetition, -first by not being a husband to his wife, and secondly by not allowing -himself to suspect. - -"No, now that she has become a bluestocking she has finally -renounced her former infatuations," he told himself. "There has -never been an instance of a bluestocking being carried away by affairs -of the heart"--a statement which, though gathered from an unknown -source, he believed implicitly. Yet strange to say Boris' presence -in his wife's drawing room (and he was almost always there) had a -physical effect upon Pierre; it constricted his limbs and destroyed -the unconsciousness and freedom of his movements. - -"What a strange antipathy," thought Pierre, "yet I used to like -him very much." - -In the eyes of the world Pierre was a great gentleman, the rather -blind and absurd husband of a distinguished wife, a clever crank who -did nothing but harmed nobody and was a first-rate, good-natured -fellow. But a complex and difficult process of internal development -was taking place all this time in Pierre's soul, revealing much to him -and causing him many spiritual doubts and joys. - - - - - -CHAPTER X - - -Pierre went on with his diary, and this is what he wrote in it -during that time: - - -24th November - -Got up at eight, read the Scriptures, then went to my duties. [By -Joseph Alexeevich's advice Pierre had entered the service of the state -and served on one of the committees.] Returned home for dinner and -dined alone--the countess had many visitors I do not like. I ate and -drank moderately and after dinner copied out some passages for the -Brothers. In the evening I went down to the countess and told a -funny story about B., and only remembered that I ought not to have -done so when everybody laughed loudly at it. - -I am going to bed with a happy and tranquil mind. Great God, help me -to walk in Thy paths, (1) to conquer anger by calmness and -deliberation, (2) to vanquish lust by self-restraint and repulsion, -(3) to withdraw from worldliness, but not avoid (a) the service of the -state, (b) family duties, (c) relations with my friends, and the -management of my affairs. - - -27th November - -I got up late. On waking I lay long in bed yielding to sloth. O God, -help and strengthen me that I may walk in Thy ways! Read the -Scriptures, but without proper feeling. Brother Urusov came and we -talked about worldly vanities. He told me of the Emperor's new -projects. I began to criticize them, but remembered my rules and my -benefactor's words--that a true Freemason should be a zealous worker -for the state when his aid is required and a quiet onlooker when not -called on to assist. My tongue is my enemy. Brothers G. V. and O. -visited me and we had a preliminary talk about the reception of a -new Brother. They laid on me the duty of Rhetor. I feel myself weak -and unworthy. Then our talk turned to the interpretation of the -seven pillars and steps of the Temple, the seven sciences, the seven -virtues, the seven vices, and the seven gifts of the Holy Spirit. -Brother O. was very eloquent. In the evening the admission took place. -The new decoration of the Premises contributed much to the -magnificence of the spectacle. It was Boris Drubetskoy who was -admitted. I nominated him and was the Rhetor. A strange feeling -agitated me all the time I was alone with him in the dark chamber. I -caught myself harboring a feeling of hatred toward him which I -vainly tried to overcome. That is why I should really like to save him -from evil and lead him into the path of truth, but evil thoughts of -him did not leave me. It seemed to me that his object in entering -the Brotherhood was merely to be intimate and in favor with members of -our lodge. Apart from the fact that he had asked me several times -whether N. and S. were members of our lodge (a question to which I -could not reply) and that according to my observation he is -incapable of feeling respect for our holy order and is too preoccupied -and satisfied with the outer man to desire spiritual improvement, I -had no cause to doubt him, but he seemed to me insincere, and all -the time I stood alone with him in the dark temple it seemed to me -that he was smiling contemptuously at my words, and I wished really to -stab his bare breast with the sword I held to it. I could not be -eloquent, nor could I frankly mention my doubts to the Brothers and to -the Grand Master. Great Architect of Nature, help me to find the -true path out of the labyrinth of lies! - - - After this, three pages were left blank in the diary, and then -the following was written: - - -I have had a long and instructive talk alone with Brother V., who -advised me to hold fast by brother A. Though I am unworthy, much was -revealed to me. Adonai is the name of the creator of the world. Elohim -is the name of the ruler of all. The third name is the name -unutterable which means the All. Talks with Brother V. strengthen, -refresh, and support me in the path of virtue. In his presence doubt -has no place. The distinction between the poor teachings of mundane -science and our sacred all-embracing teaching is clear to me. Human -sciences dissect everything to comprehend it, and kill everything to -examine it. In the holy science of our order all is one, all is -known in its entirety and life. The Trinity--the three elements of -matter--are sulphur, mercury, and salt. Sulphur is of an oily and -fiery nature; in combination with salt by its fiery nature it -arouses a desire in the latter by means of which it attracts -mercury, seizes it, holds it, and in combination produces other -bodies. Mercury is a fluid, volatile, spiritual essence. Christ, the -Holy Spirit, Him!... - - -3rd December - -Awoke late, read the Scriptures but was apathetic. Afterwards went -and paced up and down the large hall. I wished to meditate, but -instead my imagination pictured an occurrence of four years ago, -when Dolokhov, meeting me in Moscow after our duel, said he hoped I -was enjoying perfect peace of mind in spite of my wife's absence. At -the time I gave him no answer. Now I recalled every detail of that -meeting and in my mind gave him the most malevolent and bitter -replies. I recollected myself and drove away that thought only when -I found myself glowing with anger, but I did not sufficiently -repent. Afterwards Boris Drubetskoy came and began relating various -adventures. His coming vexed me from the first, and I said something -disagreeable to him. He replied. I flared up and said much that was -unpleasant and even rude to him. He became silent, and I recollected -myself only when it was too late. My God, I cannot get on with him -at all. The cause of this is my egotism. I set myself above him and so -become much worse than he, for he is lenient to my rudeness while I on -the contrary nourish contempt for him. O God, grant that in his -presence I may rather see my own vileness, and behave so that he too -may benefit. After dinner I fell asleep and as I was drowsing off I -clearly heard a voice saying in my left ear, "Thy day!" - -I dreamed that I was walking in the dark and was suddenly surrounded -by dogs, but I went on undismayed. Suddenly a smallish dog seized my -left thigh with its teeth and would not let go. I began to throttle it -with my hands. Scarcely had I torn it off before another, a bigger -one, began biting me. I lifted it up, but the higher I lifted it the -bigger and heavier it grew. And suddenly Brother A. came and, taking -my arm, led me to a building to enter which we had to pass along a -narrow plank. I stepped on it, but it bent and gave way and I began to -clamber up a fence which I could scarcely reach with my hands. After -much effort I dragged myself up, so that my leg hung down on one -side and my body on the other. I looked round and saw Brother A. -standing on the fence and pointing me to a broad avenue and garden, -and in the garden was a large and beautiful building. I woke up. O -Lord, great Architect of Nature, help me to tear from myself these -dogs--my passions especially the last, which unites in itself the -strength of all the former ones, and aid me to enter that temple of -virtue to a vision of which I attained in my dream. - - -7th December - -I dreamed that Joseph Alexeevich was sitting in my house, and that I -was very glad and wished to entertain him. It seemed as if I chattered -incessantly with other people and suddenly remembered that this -could not please him, and I wished to come close to him and embrace -him. But as soon as I drew near I saw that his face had changed and -grown young, and he was quietly telling me something about the -teaching of our order, but so softly that I could not hear it. Then it -seemed that we all left the room and something strange happened. We -were sitting or lying on the floor. He was telling me something, and I -wished to show him my sensibility, and not listening to what he was -saying I began picturing to myself the condition of my inner man and -the grace of God sanctifying me. And tears came into my eyes, and I -was glad he noticed this. But he looked at me with vexation and jumped -up, breaking off his remarks. I felt abashed and asked whether what he -had been saying did not concern me; but he did not reply, gave me a -kind look, and then we suddenly found ourselves in my bedroom where -there is a double bed. He lay down on the edge of it and I burned with -longing to caress him and lie down too. And he said, "Tell me -frankly what is your chief temptation? Do you know it? I think you -know it already." Abashed by this question, I replied that sloth was -my chief temptation. He shook his head incredulously; and even more -abashed, I said that though I was living with my wife as he advised, I -was not living with her as her husband. To this he replied that one -should not deprive a wife of one's embraces and gave me to -understand that that was my duty. But I replied that I should be -ashamed to do it, and suddenly everything vanished. And I awoke and -found in my mind the text from the Gospel: "The life was the light -of men. And the light shineth in darkness; and the darkness -comprehended it not." Joseph Alexeevich's face had looked young and -bright. That day I received a letter from my benefactor in which he -wrote about "conjugal duties." - - -9th December - -I had a dream from which I awoke with a throbbing heart. I saw -that I was in Moscow in my house, in the big sitting room, and -Joseph Alexeevich came in from the drawing room. I seemed to know at -once that the process of regeneration had already taken place in -him, and I rushed to meet him. I embraced him and kissed his hands, -and he said, "Hast thou noticed that my face is different?" I looked -at him, still holding him in my arms, and saw that his face was young, -but that he had no hair on his head and his features were quite -changed. And I said, "I should have known you had I met you by -chance," and I thought to myself, "Am I telling the truth?" And -suddenly I saw him lying like a dead body; then he gradually recovered -and went with me into my study carrying a large book of sheets of -drawing paper; I said, "I drew that," and he answered by bowing his -head. I opened the book, and on all the pages there were excellent -drawings. And in my dream I knew that these drawings represented the -love adventures of the soul with its beloved. And on its pages I saw a -beautiful representation of a maiden in transparent garments and -with a transparent body, flying up to the clouds. And I seemed to know -that this maiden was nothing else than a representation of the Song of -Songs. And looking at those drawings I dreamed I felt that I was doing -wrong, but could not tear myself away from them. Lord, help me! My -God, if Thy forsaking me is Thy doing, Thy will be done; but if I am -myself the cause, teach me what I should do! I shall perish of my -debauchery if Thou utterly desertest me! - - - - - -CHAPTER XI - - -The Rostovs' monetary affairs had not improved during the two -years they had spent in the country. - -Though Nicholas Rostov had kept firmly to his resolution and was -still serving modestly in an obscure regiment, spending -comparatively little, the way of life at Otradnoe--Mitenka's -management of affairs, in particular--was such that the debts -inevitably increased every year. The only resource obviously -presenting itself to the old count was to apply for an official -post, so he had come to Petersburg to look for one and also, as he -said, to let the lassies enjoy themselves for the last time. - -Soon after their arrival in Petersburg Berg proposed to Vera and was -accepted. - -Though in Moscow the Rostovs belonged to the best society without -themselves giving it a thought, yet in Petersburg their circle of -acquaintances was a mixed and indefinite one. In Petersburg they -were provincials, and the very people they had entertained in Moscow -without inquiring to what set they belonged, here looked down on them. - -The Rostovs lived in the same hospitable way in Petersburg as in -Moscow, and the most diverse people met at their suppers. Country -neighbors from Otradnoe, impoverished old squires and their daughters, -Peronskaya a maid of honor, Pierre Bezukhov, and the son of their -district postmaster who had obtained a post in Petersburg. Among the -men who very soon became frequent visitors at the Rostovs' house in -Petersburg were Boris, Pierre whom the count had met in the street and -dragged home with him, and Berg who spent whole days at the Rostovs' -and paid the eldest daughter, Countess Vera, the attentions a young -man pays when he intends to propose. - -Not in vain had Berg shown everybody his right hand wounded at -Austerlitz and held a perfectly unnecessary sword in his left. He -narrated that episode so persistently and with so important an air -that everyone believed in the merit and usefulness of his deed, and he -had obtained two decorations for Austerlitz. - -In the Finnish war he also managed to distinguish himself. He had -picked up the scrap of a grenade that had killed an aide-de-camp -standing near the commander in chief and had taken it to his -commander. Just as he had done after Austerlitz, he related this -occurrence at such length and so insistently that everyone again -believed it had been necessary to do this, and he received two -decorations for the Finnish war also. In 1809 he was a captain in -the Guards, wore medals, and held some special lucrative posts in -Petersburg. - -Though some skeptics smiled when told of Berg's merits, it could not -be denied that he was a painstaking and brave officer, on excellent -terms with his superiors, and a moral young man with a brilliant -career before him and an assured position in society. - -Four years before, meeting a German comrade in the stalls of a -Moscow theater, Berg had pointed out Vera Rostova to him and had -said in German, "das soll mein Weib werden,"* and from that moment had -made up his mind to marry her. Now in Petersburg, having considered -the Rostovs' position and his own, he decided that the time had come -to propose. - - -*"That girl shall be my wife." - - -Berg's proposal was at first received with a perplexity that was not -flattering to him. At first it seemed strange that the son of an -obscure Livonian gentleman should propose marriage to a Countess -Rostova; but Berg's chief characteristic was such a naive and good -natured egotism that the Rostovs involuntarily came to think it -would be a good thing, since he himself was so firmly convinced that -it was good, indeed excellent. Moreover, the Rostovs' affairs were -seriously embarrassed, as the suitor could not but know; and above -all, Vera was twenty-four, had been taken out everywhere, and though -she was certainly good-looking and sensible, no one up to now had -proposed to her. So they gave their consent. - -"You see," said Berg to his comrade, whom he called "friend" only -because he knew that everyone has friends, "you see, I have considered -it all, and should not marry if I had not thought it all out or if -it were in any way unsuitable. But on the contrary, my papa and -mamma are now provided for--I have arranged that rent for them in -the Baltic Provinces--and I can live in Petersburg on my pay, and with -her fortune and my good management we can get along nicely. I am not -marrying for money--I consider that dishonorable--but a wife should -bring her share and a husband his. I have my position in the -service, she has connections and some means. In our times that is -worth something, isn't it? But above all, she is a handsome, estimable -girl, and she loves me..." - -Berg blushed and smiled. - -"And I love her, because her character is sensible and very good. -Now the other sister, though they are the same family, is quite -different--an unpleasant character and has not the same -intelligence. She is so... you know?... Unpleasant... But my -fiancee!... Well, you will be coming," he was going to say, "to dine," -but changed his mind and said "to take tea with us," and quickly -doubling up his tongue he blew a small round ring of tobacco smoke, -perfectly embodying his dream of happiness. - -After the first feeling of perplexity aroused in the parents by -Berg's proposal, the holiday tone of joyousness usual at such times -took possession of the family, but the rejoicing was external and -insincere. In the family's feeling toward this wedding a certain -awkwardness and constraint was evident, as if they were ashamed of not -having loved Vera sufficiently and of being so ready to get her off -their hands. The old count felt this most. He would probably have been -unable to state the cause of his embarrassment, but it resulted from -the state of his affairs. He did not know at all how much he had, what -his debts amounted to, or what dowry he could give Vera. When his -daughters were born he had assigned to each of them, for her dowry, an -estate with three hundred serfs; but one of these estates had -already been sold, and the other was mortgaged and the interest so -much in arrears that it would have to be sold, so that it was -impossible to give it to Vera. Nor had he any money. - -Berg had already been engaged a month, and only a week remained -before the wedding, but the count had not yet decided in his own -mind the question of the dowry, nor spoken to his wife about it. At -one time the count thought of giving her the Ryazan estate or of -selling a forest, at another time of borrowing money on a note of -hand. A few days before the wedding Berg entered the count's study -early one morning and, with a pleasant smile, respectfully asked his -future father-in-law to let him know what Vera's dowry would be. The -count was so disconcerted by this long-foreseen inquiry that without -consideration he gave the first reply that came into his head. "I like -your being businesslike about it.... I like it. You shall be -satisfied...." - -And patting Berg on the shoulder he got up, wishing to end the -conversation. But Berg, smiling pleasantly, explained that if he did -not know for certain how much Vera would have and did not receive at -least part of the dowry in advance, he would have to break matters -off. - -"Because, consider, Count--if I allowed myself to marry now -without having definite means to maintain my wife, I should be -acting badly...." - -The conversation ended by the count, who wished to be generous and -to avoid further importunity, saying that he would give a note of hand -for eighty thousand rubles. Berg smiled meekly, kissed the count on -the shoulder, and said that he was very grateful, but that it was -impossible for him to arrange his new life without receiving thirty -thousand in ready money. "Or at least twenty thousand, Count," he -added, "and then a note of hand for only sixty thousand." - -"Yes, yes, all right!" said the count hurriedly. "Only excuse me, my - -dear fellow, I'll give you twenty thousand and a note of hand for -eighty thousand as well. Yes, yes! Kiss me." - - - - - -CHAPTER XII - - -Natasha was sixteen and it was the year 1809, the very year to which -she had counted on her fingers with Boris after they had kissed four -years ago. Since then she had not seen him. Before Sonya and her -mother, if Boris happened to be mentioned, she spoke quite freely of -that episode as of some childish, long-forgotten matter that was not -worth mentioning. But in the secret depths of her soul the question -whether her engagement to Boris was a jest or an important, binding -promise tormented her. - -Since Boris left Moscow in 1805 to join the army he had had not seen -the Rostovs. He had been in Moscow several times, and had passed -near Otradnoe, but had never been to see them. - -Sometimes it occurred to Natasha that he not wish to see her, and -this conjecture was confirmed by the sad tone in which her elders -spoke of him. - -"Nowadays old friends are not remembered," the countess would say -when Boris was mentioned. - -Anna Mikhaylovna also had of late visited them less frequently, -seemed to hold herself with particular dignity, and always spoke -rapturously and gratefully of the merits of her son and the -brilliant career on which he had entered. When the Rostovs came to -Petersburg Boris called on them. - -He drove to their house in some agitation. The memory of Natasha was -his most poetic recollection. But he went with the firm intention of -letting her and her parents feel that the childish relations between -himself and Natasha could not be binding either on her or on him. He -had a brilliant position in society thanks to his intimacy with -Countess Bezukhova, a brilliant position in the service thanks to -the patronage of an important personage whose complete confidence he -enjoyed, and he was beginning to make plans for marrying one of the -richest heiresses in Petersburg, plans which might very easily be -realized. When he entered the Rostovs' drawing room Natasha was in her -own room. When she heard of his arrival she almost ran into the -drawing room, flushed and beaming with a more than cordial smile. - -Boris remembered Natasha in a short dress, with dark eyes shining -from under her curls and boisterous, childish laughter, as he had -known her four years before; and so he was taken aback when quite a -different Natasha entered, and his face expressed rapturous -astonishment. This expression on his face pleased Natasha. - -"Well, do you recognize your little madcap playmate?" asked the -countess. - -Boris kissed Natasha's hand and said that he was astonished at the -change in her. - -"How handsome you have grown!" - -"I should think so!" replied Natasha's laughing eyes. - -"And is Papa older?" she asked. - -Natasha sat down and, without joining in Boris' conversation with -the countess, silently and minutely studied her childhood's suitor. He -felt the weight of that resolute and affectionate scrutiny and glanced -at her occasionally. - -Boris' uniform, spurs, tie, and the way his hair was brushed were -all comme il faut and in the latest fashion. This Natasha noticed at -once. He sat rather sideways in the armchair next to the countess, -arranging with his right hand the cleanest of gloves that fitted his -left hand like a skin, and he spoke with a particularly refined -compression of his lips about the amusements of the highest Petersburg -society, recalling with mild irony old times in Moscow and Moscow -acquaintances. It was not accidentally, Natasha felt, that he alluded, -when speaking of the highest aristocracy, to an ambassador's ball he -had attended, and to invitations he had received from N.N. and S.S. - -All this time Natasha sat silent, glancing up at him from under -her brows. This gaze disturbed and confused Boris more and more. He -looked round more frequently toward her, and broke off in what he -was saying. He did not stay more than ten minutes, then rose and -took his leave. The same inquisitive, challenging, and rather -mocking eyes still looked at him. After his first visit Boris said -to himself that Natasha attracted him just as much as ever, but that -he must not yield to that feeling, because to marry her, a girl almost -without fortune, would mean ruin to his career, while to renew their -former relations without intending to marry her would be dishonorable. -Boris made up his mind to avoid meeting Natasha, but despite that -resolution he called again a few days later and began calling often -and spending whole days at the Rostovs'. It seemed to him that he -ought to have an explanation with Natasha and tell her that the old -times must be forgotten, that in spite of everything... she could -not be his wife, that he had no means, and they would never let her -marry him. But he failed to do so and felt awkward about entering on -such an explanation. From day to day he became more and more -entangled. It seemed to her mother and Sonya that Natasha was in -love with Boris as of old. She sang him his favorite songs, showed him -her album, making him write in it, did not allow him to allude to -the past, letting it be understood how was the present; and every -day he went away in a fog, without having said what he meant to, and -not knowing what he was doing or why he came, or how it would all end. -He left off visiting Helene and received reproachful notes from her -every day, and yet he continued to spend whole days with the Rostovs. - - - - - -CHAPTER XIII - - -One night when the old countess, in nightcap and dressing jacket, -without her false curls, and with her poor little knob of hair showing -under her white cotton cap, knelt sighing and groaning on a rug and -bowing to the ground in prayer, her door creaked and Natasha, also -in a dressing jacket with slippers on her bare feet and her hair in -curlpapers, ran in. The countess--her prayerful mood dispelled--looked -round and frowned. She was finishing her last prayer: "Can it be -that this couch will be my grave?" Natasha, flushed and eager, -seeing her mother in prayer, suddenly checked her rush, half sat down, -and unconsciously put out her tongue as if chiding herself. Seeing -that her mother was still praying she ran on tiptoe to the bed and, -rapidly slipping one little foot against the other, pushed off her -slippers and jumped onto the bed the countess had feared might -become her grave. This couch was high, with a feather bed and five -pillows each smaller than the one below. Natasha jumped on it, sank -into the feather bed, rolled over to the wall, and began snuggling -up the bedclothes as she settled down, raising her knees to her -chin, kicking out and laughing almost inaudibly, now covering -herself up head and all, and now peeping at her mother. The countess -finished her prayers and came to the bed with a stern face, but -seeing, that Natasha's head was covered, she smiled in her kind, -weak way. - -"Now then, now then!" said she. - -"Mamma, can we have a talk? Yes?" said Natasha. "Now, just one on -your throat and another... that'll do!" And seizing her mother round -the neck, she kissed her on the throat. In her behavior to her -mother Natasha seemed rough, but she was so sensitive and tactful that -however she clasped her mother she always managed to do it without -hurting her or making her feel uncomfortable or displeased. - -"Well, what is it tonight?" said the mother, having arranged her -pillows and waited until Natasha, after turning over a couple of -times, had settled down beside her under the quilt, spread out her -arms, and assumed a serious expression. - -These visits of Natasha's at night before the count returned from -his club were one of the greatest pleasures of both mother, and -daughter. - -"What is it tonight?--But I have to tell you..." - -Natasha put her hand on her mother's mouth. - -"About Boris... I know," she said seriously; "that's what I have -come about. Don't say it--I know. No, do tell me!" and she removed her -hand. "Tell me, Mamma! He's nice?" - -"Natasha, you are sixteen. At your age I was married. You say -Boris is nice. He is very nice, and I love him like a son. But what -then?... What are you thinking about? You have quite turned his -head, I can see that...." - -As she said this the countess looked round at her daughter. -Natasha was lying looking steadily straight before her at one of the -mahogany sphinxes carved on the corners of the bedstead, so that the -countess only saw her daughter's face in profile. That face struck her -by its peculiarly serious and concentrated expression. - -Natasha was listening and considering. - -"Well, what then?" said she. - -"You have quite turned his head, and why? What do you want of him? -You know you can't marry him." - -"Why not?" said Natasha, without changing her position. - -"Because he is young, because he is poor, because he is a -relation... and because you yourself don't love him." - -"How do you know?" - -"I know. It is not right, darling!" - - "But if I want to..." said Natasha. - -"Leave off talking nonsense," said the countess. - -"But if I want to..." - -"Natasha, I am in earnest..." - -Natasha did not let her finish. She drew the countess' large hand to -her, kissed it on the back and then on the palm, then again turned -it over and began kissing first one knuckle, then the space between -the knuckles, then the next knuckle, whispering, "January, February, -March, April, May. Speak, Mamma, why don't you say anything? Speak!" -said she, turning to her mother, who was tenderly gazing at her -daughter and in that contemplation seemed to have forgotten all she -had wished to say. - -"It won't do, my love! Not everyone will understand this -friendship dating from your childish days, and to see him so -intimate with you may injure you in the eyes of other young men who -visit us, and above all it torments him for nothing. He may already -have found a suitable and wealthy match, and now he's half crazy." - -"Crazy?" repeated Natasha. - -"I'll tell you some things about myself. I had a cousin..." - -"I know! Cyril Matveich... but he is old." - -"He was not always old. But this is what I'll do, Natasha, I'll have -a talk with Boris. He need not come so often...." - -"Why not, if he likes to?" - -"Because I know it will end in nothing...." - -"How can you know? No, Mamma, don't speak to him! What nonsense!" -said Natasha in the tone of one being deprived of her property. "Well, -I won't marry, but let him come if he enjoys it and I enjoy it." -Natasha smiled and looked at her mother. "Not to marry, but just -so," she added. - -"How so, my pet?" - -"Just so. There's no need for me to marry him. But... just so." - -"Just so, just so," repeated the countess, and shaking all over, she -went off into a good humored, unexpected, elderly laugh. - -"Don't laugh, stop!" cried Natasha. "You're shaking the whole bed! -You're awfully like me, just such another giggler.... Wait..." and she -seized the countess' hands and kissed a knuckle of the little -finger, saying, "June," and continued, kissing, "July, August," on the -other hand. "But, Mamma, is he very much in love? What do you think? -Was anybody ever so much in love with you? And he's very nice, very, -very nice. Only not quite my taste--he is so narrow, like the -dining-room clock.... Don't you understand? Narrow, you know--gray, -light gray..." - -"What rubbish you're talking!" said the countess. - -Natasha continued: "Don't you really understand? Nicholas would -understand.... Bezukhov, now, is blue, dark-blue and red, and he is -square." - -"You flirt with him too," said the countess, laughing. - -"No, he is a Freemason, I have found out. He is fine, dark-blue -and red.... How can I explain it to you?" - -"Little countess!" the count's voice called from behind the door. -"You're not asleep?" Natasha jumped up, snatched up her slippers, -and ran barefoot to her own room. - -It was a long time before she could sleep. She kept thinking that no -one could understand all that she understood and all there was in her. - -"Sonya?" she thought, glancing at that curled-up, sleeping little -kitten with her enormous plait of hair. "No, how could she? She's -virtuous. She fell in love with Nicholas and does not wish to know -anything more. Even Mamma does not understand. It is wonderful how -clever I am and how... charming she is," she went on, speaking of -herself in the third person, and imagining it was some very wise -man--the wisest and best of men--who was saying it of her. "There is -everything, everything in her," continued this man. "She is -unusually intelligent, charming... and then she is pretty, -uncommonly pretty, and agile--she swims and rides splendidly... and -her voice! One can really say it's a wonderful voice!" - -She hummed a scrap from her favorite opera by Cherubini, threw -herself on her bed, laughed at the pleasant thought that she would -immediately fall asleep, called Dunyasha the maid to put out the -candle, and before Dunyasha had left the room had already passed -into yet another happier world of dreams, where everything was as -light and beautiful as in reality, and even more so because it was -different. - - -Next day the countess called Boris aside and had a talk with him, -after which he ceased coming to the Rostovs'. - - - - - -CHAPTER XIV - - -On the thirty-first of December, New Year's Eve, 1809 --10 an old -grandee of Catherine's day was giving a ball and midnight supper. -The diplomatic corps and the Emperor himself were to be present. - -The grandee's well-known mansion on the English Quay glittered -with innumerable lights. Police were stationed at the brightly lit -entrance which was carpeted with red baize, and not only gendarmes but -dozens of police officers and even the police master himself stood -at the porch. Carriages kept driving away and fresh ones arriving, -with red-liveried footmen and footmen in plumed hats. From the -carriages emerged men wearing uniforms, stars, and ribbons, while -ladies in satin and ermine cautiously descended the carriage steps -which were let down for them with a clatter, and then walked hurriedly -and noiselessly over the baize at the entrance. - -Almost every time a new carriage drove up a whisper ran through -the crowd and caps were doffed. - -"The Emperor?... No, a minister.... prince... ambassador. Don't -you see the plumes?..." was whispered among the crowd. - -One person, better dressed than the rest, seemed to know everyone -and mentioned by name the greatest dignitaries of the day. - -A third of the visitors had already arrived, but the Rostovs, who -were to be present, were still hurrying to get dressed. - -There had been many discussions and preparations for this ball in -the Rostov family, many fears that the invitation would not arrive, -that the dresses would not be ready, or that something would not be -arranged as it should be. - -Marya Ignatevna Peronskaya, a thin and shallow maid of honor at -the court of the Dowager Empress, who was a friend and relation of the -countess and piloted the provincial Rostovs in Petersburg high -society, was to accompany them to the ball. - -They were to call for her at her house in the Taurida Gardens at ten -o'clock, but it was already five minutes to ten, and the girls were -not yet dressed. - -Natasha was going to her first grand ball. She had got up at eight -that morning and had been in a fever of excitement and activity all -day. All her powers since morning had been concentrated on ensuring -that they all--she herself, Mamma, and Sonya--should be as well -dressed as possible. Sonya and her mother put themselves entirely in -her hands. The countess was to wear a claret-colored velvet dress, and -the two girls white gauze over pink silk slips, with roses on their -bodices and their hair dressed a la grecque. - -Everything essential had already been done; feet, hands, necks, -and ears washed, perfumed, and powdered, as befits a ball; the -openwork silk stockings and white satin shoes with ribbons were -already on; the hairdressing was almost done. Sonya was finishing -dressing and so was the countess, but Natasha, who had bustled about -helping them all, was behindhand. She was still sitting before a -looking-glass with a dressing jacket thrown over her slender -shoulders. Sonya stood ready dressed in the middle of the room and, -pressing the head of a pin till it hurt her dainty finger, was -fixing on a last ribbon that squeaked as the pin went through it. - -"That's not the way, that's not the way, Sonya!" cried Natasha -turning her head and clutching with both hands at her hair which the -maid who was dressing it had not time to release. "That bow is not -right. Come here!" - -Sonya sat down and Natasha pinned the ribbon on differently. - -"Allow me, Miss! I can't do it like that," said the maid who was -holding Natasha's hair. - -"Oh, dear! Well then, wait. That's right, Sonya." - -"Aren't you ready? It is nearly ten," came the countess' voice. - -"Directly! Directly! And you, Mamma?" - -"I have only my cap to pin on." - -"Don't do it without me!" called Natasha. "You won't do it right." - -"But it's already ten." - -They had decided to be at the ball by half past ten, and Natasha had -still to get dressed and they had to call at the Taurida Gardens. - -When her hair was done, Natasha, in her short petticoat from under -which her dancing shoes showed, and in her mother's dressing jacket, -ran up to Sonya, scrutinized her, and then ran to her mother. -Turning her mother's head this way and that, she fastened on the cap -and, hurriedly kissing her gray hair, ran back to the maids who were -turning up the hem of her skirt. - -The cause of the delay was Natasha's skirt, which was too long. -Two maids were turning up the hem and hurriedly biting off the ends of -thread. A third with pins in her mouth was running about between the -countess and Sonya, and a fourth held the whole of the gossamer -garment up high on one uplifted hand. - -"Mavra, quicker, darling!" - -"Give me my thimble, Miss, from there..." - -"Whenever will you be ready?" asked the count coming to the door. -"Here is here is some scent. Peronskaya must be tired of waiting." - -"It's ready, Miss," said the maid, holding up the shortened gauze -dress with two fingers, and blowing and shaking something off it, as -if by this to express a consciousness of the airiness and purity of -what she held. - -Natasha began putting on the dress. - -"In a minute! In a minute! Don't come in, Papa!" she cried to her -father as he opened the door--speaking from under the filmy skirt -which still covered her whole face. - -Sonya slammed the door to. A minute later they let the count in. -He was wearing a blue swallow-tail coat, shoes and stockings, and -was perfumed and his hair pomaded. - -"Oh, Papa! how nice you look! Charming!" cried Natasha, as she stood -in the middle of the room smoothing out the folds of the gauze. - -"If you please, Miss! allow me," said the maid, who on her knees was -pulling the skirt straight and shifting the pins from one side of -her mouth to the other with her tongue. - -"Say what you like," exclaimed Sonya, in a despairing voice as she -looked at Natasha, "say what you like, it's still too long." - -Natasha stepped back to look at herself in the pier glass. The dress -was too long. - -"Really, madam, it is not at all too long," said Mavra, crawling -on her knees after her young lady. - -"Well, if it's too long we'll take it up... we'll tack it up in -one minute," said the resolute Dunyasha taking a needle that was stuck -on the front of her little shawl and, still kneeling on the floor, set -to work once more. - -At that moment, with soft steps, the countess came in shyly, in -her cap and velvet gown. - -"Oo-oo, my beauty!" exclaimed the count, "she looks better than -any of you!" - -He would have embraced her but, blushing, she stepped aside -fearing to be rumpled. - -"Mamma, your cap, more to this side," said Natasha. "I'll arrange -it," and she rushed forward so that the maids who were tacking up -her skirt could not move fast enough and a piece of gauze was torn -off. - -"Oh goodness! What has happened? Really it was not my fault!" - -"Never mind, I'll run it up, it won't show," said Dunyasha. - -"What a beauty--a very queen!" said the nurse as she came to the -door. "And Sonya! They are lovely!" - -At a quarter past ten they at last got into their carriages and -started. But they had still to call at the Taurida Gardens. - -Peronskaya was quite ready. In spite of her age and plainness she -had gone through the same process as the Rostovs, but with less -flurry--for to her it was a matter of routine. Her ugly old body was -washed, perfumed, and powdered in just the same way. She had washed -behind her ears just as carefully, and when she entered her drawing -room in her yellow dress, wearing her badge as maid of honor, her -old lady's maid was as full of rapturous admiration as the Rostovs' -servants had been. - -She praised the Rostovs' toilets. They praised her taste and toilet, -and at eleven o'clock, careful of their coiffures and dresses, they -settled themselves in their carriages and drove off. - - - - - -CHAPTER XV - - -Natasha had not had a moment free since early morning and had not -once had time to think of what lay before her. - -In the damp chill air and crowded closeness of the swaying carriage, -she for the first time vividly imagined what was in store for her -there at the ball, in those brightly lighted rooms--with music, -flowers, dances, the Emperor, and all the brilliant young people of -Petersburg. The prospect was so splendid that she hardly believed it -would come true, so out of keeping was it with the chill darkness -and closeness of the carriage. She understood all that awaited her -only when, after stepping over the red baize at the entrance, she -entered the hall, took off her fur cloak, and, beside Sonya and in -front of her mother, mounted the brightly illuminated stairs between -the flowers. Only then did she remember how she must behave at a ball, -and tried to assume the majestic air she considered indispensable -for a girl on such an occasion. But, fortunately for her, she felt her -eyes growing misty, she saw nothing clearly, her pulse beat a -hundred to the minute, and the blood throbbed at her heart. She -could not assume that pose, which would have made her ridiculous, -and she moved on almost fainting from excitement and trying with all -her might to conceal it. And this was the very attitude that became -her best. Before and behind them other visitors were entering, also -talking in low tones and wearing ball dresses. The mirrors on the -landing reflected ladies in white, pale-blue, and pink dresses, with -diamonds and pearls on their bare necks and arms. - -Natasha looked in the mirrors and could not distinguish her -reflection from the others. All was blended into one brilliant -procession. On entering the ballroom the regular hum of voices, -footsteps, and greetings deafened Natasha, and the light and glitter -dazzled her still more. The host and hostess, who had already been -standing at the door for half an hour repeating the same words to -the various arrivals, "Charme de vous voir,"* greeted the Rostovs -and Peronskaya in the same manner. - - -*"Delighted to see you." - - -The two girls in their white dresses, each with a rose in her -black hair, both curtsied in the same way, but the hostess' eye -involuntarily rested longer on the slim Natasha. She looked at her and -gave her alone a special smile in addition to her usual smile as -hostess. Looking at her she may have recalled the golden, -irrecoverable days of her own girlhood and her own first ball. The -host also followed Natasha with his eyes and asked the count which was -his daughter. - -"Charming!" said he, kissing the tips of his fingers. - -In the ballroom guests stood crowding at the entrance doors awaiting -the Emperor. The countess took up a position in one of the front -rows of that crowd. Natasha heard and felt that several people were -asking about her and looking at her. She realized that those -noticing her liked her, and this observation helped to calm her. - -"There are some like ourselves and some worse," she thought. - -Peronskaya was pointing out to the countess the most important -people at the ball. - -"That is the Dutch ambassador, do you see? That gray-haired man," -she said, indicating an old man with a profusion of silver-gray -curly hair, who was surrounded by ladies laughing at something he -said. - -"Ah, here she is, the Queen of Petersburg, Countess Bezukhova," said -Peronskaya, indicating Helene who had just entered. "How lovely! She -is quite equal to Marya Antonovna. See how the men, young and old, pay -court to her. Beautiful and clever... they say Prince--is quite mad -about her. But see, those two, though not good-looking, are even -more run after." - -She pointed to a lady who was crossing the room followed by a very -plain daughter. - -"She is a splendid match, a millionairess," said Peronskaya. "And -look, here come her suitors." - -"That is Bezukhova's brother, Anatole Kuragin," she said, indicating -a handsome officer of the Horse Guards who passed by them with head -erect, looking at something over the heads of the ladies. "He's -handsome, isn't he? I hear they will marry him to that rich girl. -But your cousin, Drubetskoy, is also very attentive to her. They say -she has millions. Oh yes, that's the French ambassador himself!" she -replied to the countess' inquiry about Caulaincourt. "Looks as if he -were a king! All the same, the French are charming, very charming. -No one more charming in society. Ah, here she is! Yes, she is still -the most beautiful of them all, our Marya Antonovna! And how simply -she is dressed! Lovely! And that stout one in spectacles is the -universal Freemason," she went on, indicating Pierre. "Put him -beside his wife and he looks a regular buffoon!" - -Pierre, swaying his stout body, advanced, making way through the -crowd and nodding to right and left as casually and good-naturedly -as if he were passing through a crowd at a fair. He pushed through, -evidently looking for someone. - -Natasha looked joyfully at the familiar face of Pierre, "the -buffoon," as Peronskaya had called him, and knew he was looking for -them, and for her in particular. He had promised to be at the ball and -introduce partners to her. - -But before he reached them Pierre stopped beside a very handsome, -dark man of middle height, and in a white uniform, who stood by a -window talking to a tall man wearing stars and a ribbon. Natasha at -once recognized the shorter and younger man in the white uniform: it -was Bolkonski, who seemed to her to have grown much younger, -happier, and better-looking. - -"There's someone else we know--Bolkonski, do you see, Mamma?" said -Natasha, pointing out Prince Andrew. "You remember, he stayed a -night with us at Otradnoe." - -"Oh, you know him?" said Peronskaya. "I can't bear him. Il fait a -present la pluie et le beau temps.* He's too proud for anything. -Takes after his father. And he's hand in glove with Speranski, writing -some project or other. Just look how he treats the ladies! There's one -talking to him and he has turned away," she said, pointing at him. -"I'd give it to him if he treated me as he does those ladies." - - -*"He is all the rage just now. - - - - - -CHAPTER XVI - - -Suddenly everybody stirred, began talking, and pressed forward and -then back, and between the two rows, which separated, the Emperor -entered to the sounds of music that had immediately struck up. -Behind him walked his host and hostess. He walked in rapidly, bowing -to right and left as if anxious to get the first moments of the -reception over. The band played the polonaise in vogue at that time on -account of the words that had been set to it, beginning: "Alexander, -Elisaveta, all our hearts you ravish quite..." The Emperor passed on -to the drawing room, the crowd made a rush for the doors, and -several persons with excited faces hurried there and back again. -Then the crowd hastily retired from the drawing-room door, at which -the Emperor reappeared talking to the hostess. A young man, looking -distraught, pounced down on the ladies, asking them to move aside. -Some ladies, with faces betraying complete forgetfulness of all the -rules of decorum, pushed forward to the detriment of their toilets. -The men began to choose partners and take their places for the -polonaise. - -Everyone moved back, and the Emperor came smiling out of the drawing -room leading his hostess by the hand but not keeping time to the -music. The host followed with Marya Antonovna Naryshkina; then came -ambassadors, ministers, and various generals, whom Peronskaya -diligently named. More than half the ladies already had partners and -were taking up, or preparing to take up, their positions for the -polonaise. Natasha felt that she would be left with her mother and -Sonya among a minority of women who crowded near the wall, not -having been invited to dance. She stood with her slender arms -hanging down, her scarcely defined bosom rising and falling regularly, -and with bated breath and glittering, frightened eyes gazed straight -before her, evidently prepared for the height of joy or misery. She -was not concerned about the Emperor or any of those great people -whom Peronskaya was pointing out--she had but one thought: "Is it -possible no one will ask me, that I shall not be among the first to -dance? Is it possible that not one of all these men will notice me? -They do not even seem to see me, or if they do they look as if they -were saying, 'Ah, she's not the one I'm after, so it's not worth -looking at her!' No, it's impossible," she thought. "They must know -how I long to dance, how splendidly I dance, and how they would -enjoy dancing with me." - -The strains of the polonaise, which had continued for a considerable -time, had begun to sound like a sad reminiscence to Natasha's ears. -She wanted to cry. Peronskaya had left them. The count was at the -other end of the room. She and the countess and Sonya were standing by -themselves as in the depths of a forest amid that crowd of -strangers, with no one interested in them and not wanted by anyone. -Prince Andrew with a lady passed by, evidently not recognizing them. -The handsome Anatole was smilingly talking to a partner on his arm and -looked at Natasha as one looks at a wall. Boris passed them twice -and each time turned away. Berg and his wife, who were not dancing, -came up to them. - -This family gathering seemed humiliating to Natasha--as if there -were nowhere else for the family to talk but here at the ball. She did -not listen to or look at Vera, who was telling her something about her -own green dress. - -At last the Emperor stopped beside his last partner (he had danced -with three) and the music ceased. A worried aide-de-camp ran up to the -Rostovs requesting them to stand farther back, though as it was they -were already close to the wall, and from the gallery resounded the -distinct, precise, enticingly rhythmical strains of a waltz. The -Emperor looked smilingly down the room. A minute passed but no one had -yet begun dancing. An aide-de-camp, the Master of Ceremonies, went -up to Countess Bezukhova and asked her to dance. She smilingly -raised her hand and laid it on his shoulder without looking at him. -The aide-de-camp, an adept in his art, grasping his partner firmly -round her waist, with confident deliberation started smoothly, gliding -first round the edge of the circle, then at the corner of the room -he caught Helene's left hand and turned her, the only sound audible, -apart from the ever-quickening music, being the rhythmic click of -the spurs on his rapid, agile feet, while at every third beat his -partner's velvet dress spread out and seemed to flash as she whirled -round. Natasha gazed at them and was ready to cry because it was not -she who was dancing that first turn of the waltz. - -Prince Andrew, in the white uniform of a cavalry colonel, wearing -stockings and dancing shoes, stood looking animated and bright in -the front row of the circle not far from the Rostovs. Baron Firhoff -was talking to him about the first sitting of the Council of State -to be held next day. Prince Andrew, as one closely connected with -Speranski and participating in the work of the legislative commission, -could give reliable information about that sitting, concerning which -various rumors were current. But not listening to what Firhoff was -saying, he was gazing now at the sovereign and now at the men -intending to dance who had not yet gathered courage to enter the -circle. - -Prince Andrew was watching these men abashed by the Emperor's -presence, and the women who were breathlessly longing to be asked to -dance. - -Pierre came up to him and caught him by the arm. - -"You always dance. I have a protegee, the young Rostova, here. Ask -her," he said. - -"Where is she?" asked Bolkonski. "Excuse me!" he added, turning to -the baron, "we will finish this conversation elsewhere--at a ball -one must dance." He stepped forward in the direction Pierre indicated. -The despairing, dejected expression of Natasha's face caught his -eye. He recognized her, guessed her feelings, saw that it was her -debut, remembered her conversation at the window, and with an -expression of pleasure on his face approached Countess Rostova. - -"Allow me to introduce you to my daughter," said the countess, -with heightened color. - -"I have the pleasure of being already acquainted, if the countess -remembers me," said Prince Andrew with a low and courteous bow quite -belying Peronskaya's remarks about his rudeness, and approaching -Natasha he held out his arm to grasp her waist before he had completed -his invitation. He asked her to waltz. That tremulous expression on -Natasha's face, prepared either for despair or rapture, suddenly -brightened into a happy, grateful, childlike smile. - -"I have long been waiting for you," that frightened happy little -girl seemed to say by the smile that replaced the threatened tears, as -she raised her hand to Prince Andrew's shoulder. They were the -second couple to enter the circle. Prince Andrew was one of the best -dancers of his day and Natasha danced exquisitely. Her little feet -in their white satin dancing shoes did their work swiftly, lightly, -and independently of herself, while her face beamed with ecstatic -happiness. Her slender bare arms and neck were not beautiful--compared -to Helene's her shoulders looked thin and her bosom undeveloped. But -Helene seemed, as it were, hardened by a varnish left by the thousands -of looks that had scanned her person, while Natasha was like a girl -exposed for the first time, who would have felt very much ashamed -had she not been assured that this was absolutely necessary. - -Prince Andrew liked dancing, and wishing to escape as quickly as -possible from the political and clever talk which everyone addressed -to him, wishing also to break up the circle of restraint he -disliked, caused by the Emperor's presence, he danced, and had -chosen Natasha because Pierre pointed her out to him and because she -was the first pretty girl who caught his eye; but scarcely had he -embraced that slender supple figure and felt her stirring so close -to him and smiling so near him than the wine of her charm rose to -his head, and he felt himself revived and rejuvenated when after -leaving her he stood breathing deeply and watching the other dancers. - - - - - -CHAPTER XVII - - -After Prince Andrew, Boris came up to ask Natasha for dance, and -then the aide-de-camp who had opened the ball, and several other young -men, so that, flushed and happy, and passing on her superfluous -partners to Sonya, she did not cease dancing all the evening. She -noticed and saw nothing of what occupied everyone else. Not only did -she fail to notice that the Emperor talked a long time with the French -ambassador, and how particularly gracious he was to a certain lady, or -that Prince So-and-so and So-and-so did and said this and that, and -that Helene had great success and was honored was by the special -attention of So-and-so, but she did not even see the Emperor, and only -noticed that he had gone because the ball became livelier after his -departure. For one of the merry cotillions before supper Prince Andrew -was again her partner. He reminded her of their first encounter in the -Otradnoe avenue, and how she had been unable to sleep that moonlight -night, and told her how he had involuntarily overheard her. Natasha -blushed at that recollection and tried to excuse herself, as if -there had been something to be ashamed of in what Prince Andrew had -overheard. - -Like all men who have grown up in society, Prince Andrew liked -meeting someone there not of the conventional society stamp. And -such was Natasha, with her surprise, her delight, her shyness, and -even her mistakes in speaking French. With her he behaved with special -care and tenderness, sitting beside her and talking of the simplest -and most unimportant matters; he admired her shy grace. In the -middle of the cotillion, having completed one of the figures, Natasha, -still out of breath, was returning to her seat when another dancer -chose her. She was tired and panting and evidently thought of -declining, but immediately put her hand gaily on the man's shoulder, -smiling at Prince Andrew. - -"I'd be glad to sit beside you and rest: I'm tired; but you see -how they keep asking me, and I'm glad of it, I'm happy and I love -everybody, and you and I understand it all," and much, much more was -said in her smile. When her partner left her Natasha ran across the -room to choose two ladies for the figure. - -"If she goes to her cousin first and then to another lady, she -will be my wife," said Prince Andrew to himself quite to his own -surprise, as he watched her. She did go first to her cousin. - -"What rubbish sometimes enters one's head!" thought Prince Andrew, -"but what is certain is that that girl is so charming, so original, -that she won't be dancing here a month before she will be -married.... Such as she are rare here," he thought, as Natasha, -readjusting a rose that was slipping on her bodice, settled herself -beside him. - -When the cotillion was over the old count in his blue coat came up -to the dancers. He invited Prince Andrew to come and see them, and -asked his daughter whether she was enjoying herself. Natasha did not -answer at once but only looked up with a smile that said -reproachfully: "How can you ask such a question?" - -"I have never enjoyed myself so much before!" she said, and Prince -Andrew noticed how her thin arms rose quickly as if to embrace her -father and instantly dropped again. Natasha was happier than she had -ever been in her life. She was at that height of bliss when one -becomes completely kind and good and does not believe in the -possibility of evil, unhappiness, or sorrow. - -At that ball Pierre for the first time felt humiliated by the -position his wife occupied in court circles. He was gloomy and -absent-minded. A deep furrow ran across his forehead, and standing -by a window he stared over his spectacles seeing no one. - -On her way to supper Natasha passed him. - -Pierre's gloomy, unhappy look struck her. She stopped in front of -him. She wished to help him, to bestow on him the superabundance of -her own happiness. - -"How delightful it is, Count!" said she. "Isn't it?" - -Pierre smiled absent-mindedly, evidently not grasping what she said. - -"Yes, I am very glad," he said. - -"How can people be dissatisfied with anything?" thought Natasha. -"Especially such a capital fellow as Bezukhov!" In Natasha's eyes -all the people at the ball alike were good, kind, and splendid people, -loving one another; none of them capable of injuring another--and so -they ought all to be happy. - - - - - -CHAPTER XVIII - - -Next day Prince Andrew thought of the ball, but his mind did not -dwell on it long. "Yes, it was a very brilliant ball," and then... -"Yes, that little Rostova is very charming. There's something fresh, -original, un-Petersburg-like about her that distinguishes her." That -was all he thought about yesterday's ball, and after his morning tea -he set to work. - -But either from fatigue or want of sleep he was ill-disposed for -work and could get nothing done. He kept criticizing his own work, -as he often did, and was glad when he heard someone coming. - -The visitor was Bitski, who served on various committees, frequented -all the societies in Petersburg, and a passionate devotee of the new -ideas and of Speranski, and a diligent Petersburg newsmonger--one of -those men who choose their opinions like their clothes according to -the fashion, but who for that very reason appear to be the warmest -partisans. Hardly had he got rid of his hat before he ran into -Prince Andrew's room with a preoccupied air and at once began talking. -He had just heard particulars of that morning's sitting of the Council -of State opened by the Emperor, and he spoke of it enthusiastically. -The Emperor's speech had been extraordinary. It had been a speech such -as only constitutional monarchs deliver. "The Sovereign plainly said -that the Council and Senate are estates of the realm, he said that the -government must rest not on authority but on secure bases. The Emperor -said that the fiscal system must be reorganized and the accounts -published," recounted Bitski, emphasizing certain words and opening -his eyes significantly. - -"Ah, yes! Today's events mark an epoch, the greatest epoch in our -history," he concluded. - -Prince Andrew listened to the account of the opening of the -Council of State, which he had so impatiently awaited and to which -he had attached such importance, and was surprised that this event, -now that it had taken place, did not affect him, and even seemed quite -insignificant. He listened with quiet irony to Bitski's enthusiastic -account of it. A very simple thought occurred to him: "What does it -matter to me or to Bitski what the Emperor was pleased to say at the -Council? Can all that make me any happier or better?" - -And this simple reflection suddenly destroyed all the interest -Prince Andrew had felt in the impending reforms. He was going to -dine that evening at Speranski's, "with only a few friends," as the -host had said when inviting him. The prospect of that dinner in the -intimate home circle of the man he so admired had greatly interested -Prince Andrew, especially as he had not yet seen Speranski in his -domestic surroundings, but now he felt disinclined to go to it. - -At the appointed hour, however, he entered the modest house -Speranski owned in the Taurida Gardens. In the parqueted dining room -this small house, remarkable for its extreme cleanliness (suggesting -that of a monastery), Prince Andrew, who was rather late, found the -friendly gathering of Speranski's intimate acquaintances already -assembled at five o'clock. There were no ladies present except -Speranski's little daughter (long-faced like her father) and her -governess. The other guests were Gervais, Magnitski, and Stolypin. -While still in the anteroom Prince Andrew heard loud voices and a -ringing staccato laugh--a laugh such as one hears on the stage. -Someone--it sounded like Speranski--was distinctly ejaculating -ha-ha-ha. Prince Andrew had never before heard Speranski's famous -laugh, and this ringing, high pitched laughter from a statesman made a -strange impression on him. - -He entered the dining room. The whole company were standing -between two windows at a small table laid with hors-d'oeuvres. -Speranski, wearing a gray swallow-tail coat with a star on the breast, -and evidently still the same waistcoat and high white stock he had -worn at the meeting of the Council of State, stood at the table with a -beaming countenance. His guests surrounded him. Magnitski, -addressing himself to Speranski, was relating an anecdote, and -Speranski was laughing in advance at what Magnitski was going to -say. When Prince Andrew entered the room Magnitski's words were -again crowned by laughter. Stolypin gave a deep bass guffaw as he -munched a piece of bread and cheese. Gervais laughed softly with a -hissing chuckle, and Speranski in a high-pitched staccato manner. - -Still laughing, Speranski held out his soft white hand to Prince -Andrew. - -"Very pleased to see you, Prince," he said. "One moment..." he -went on, turning to Magnitski and interrupting his story. "We have -agreed that this is a dinner for recreation, with not a word about -business!" and turning again to the narrator he began to laugh afresh. - -Prince Andrew looked at the laughing Speranski with astonishment, -regret, and disillusionment. It seemed to him that this was not -Speranski but someone else. Everything that had formerly appeared -mysterious and fascinating in Speranski suddenly became plain and -unattractive. - -At dinner the conversation did not cease for a moment and seemed -to consist of the contents of a book of funny anecdotes. Before -Magnitski had finished his story someone else was anxious to relate -something still funnier. Most of the anecdotes, if not relating to the -state service, related to people in the service. It seemed that in -this company the insignificance of those people was so definitely -accepted that the only possible attitude toward them was one of good -humored ridicule. Speranski related how at the Council that morning -a deaf dignitary, when asked his opinion, replied that he thought so -too. Gervais gave a long account of an official revision, remarkable -for the stupidity of everybody concerned. Stolypin, stuttering, -broke into the conversation and began excitedly talking of the -abuses that existed under the former order of things--threatening to -give a serious turn to the conversation. Magnitski starting quizzing -Stolypin about his vehemence. Gervais intervened with a joke, and -the talk reverted to its former lively tone. - -Evidently Speranski liked to rest after his labors and find -amusement in a circle of friends, and his guests, understanding his -wish, tried to enliven him and amuse themselves. But their gaiety -seemed to Prince Andrew mirthless and tiresome. Speranski's -high-pitched voice struck him unpleasantly, and the incessant laughter -grated on him like a false note. Prince Andrew did not laugh and -feared that he would be a damper on the spirits of the company, but no -one took any notice of his being out of harmony with the general mood. -They all seemed very gay. - -He tried several times to join in the conversation, but his -remarks were tossed aside each time like a cork thrown out of the -water, and he could not jest with them. - -There was nothing wrong or unseemly in what they said, it was -witty and might have been funny, but it lacked just that something -which is the salt of mirth, and they were not even aware that such a -thing existed. - -After dinner Speranski's daughter and her governess rose. He -patted the little girl with his white hand and kissed her. And that -gesture, too, seemed unnatural to Prince Andrew. - -The men remained at table over their port--English fashion. In the -midst of a conversation that was started about Napoleon's Spanish -affairs, which they all agreed in approving, Prince Andrew began to -express a contrary opinion. Speranski smiled and, with an evident wish -to prevent the conversation from taking an unpleasant course, told a -story that had no connection with the previous conversation. For a few -moments all were silent. - -Having sat some time at table, Speranski corked a bottle of wine -and, remarking, "Nowadays good wine rides in a carriage and pair," -passed it to the servant and got up. All rose and continuing to talk -loudly went into the drawing room. Two letters brought by a courier -were handed to Speranski and he took them to his study. As soon as -he had left the room the general merriment stopped and the guests -began to converse sensibly and quietly with one another. - -"Now for the recitation!" said Speranski on returning from his -study. "A wonderful talent!" he said to Prince Andrew, and Magnitski -immediately assumed a pose and began reciting some humorous verses -in French which he had composed about various well-known Petersburg -people. He was interrupted several times by applause. When the -verses were finished Prince Andrew went up to Speranski and took his -leave. - -"Where are you off to so early?" asked Speranski. - -"I promised to go to a reception." - -They said no more. Prince Andrew looked closely into those -mirrorlike, impenetrable eyes, and felt that it had been ridiculous of -him to have expected anything from Speranski and from any of his own -activities connected with him, or ever to have attributed importance -to what Speranski was doing. That precise, mirthless laughter rang -in Prince Andrew's ears long after he had left the house. - -When he reached home Prince Andrew began thinking of his life in -Petersburg during those last four months as if it were something -new. He recalled his exertions and solicitations, and the history of -his project of army reform, which had been accepted for -consideration and which they were trying to pass over in silence -simply because another, a very poor one, had already been prepared and -submitted to the Emperor. He thought of the meetings of a committee of -which Berg was a member. He remembered how carefully and at what -length everything relating to form and procedure was discussed at -those meetings, and how sedulously and promptly all that related to -the gist of the business was evaded. He recalled his labors on the -Legal Code, and how painstakingly he had translated the articles of -the Roman and French codes into Russian, and he felt ashamed of -himself. Then he vividly pictured to himself Bogucharovo, his -occupations in the country, his journey to Ryazan; he remembered the -peasants and Dron the village elder, and mentally applying to them the -Personal Rights he had divided into paragraphs, he felt astonished -that he could have spent so much time on such useless work. - - - - - -CHAPTER XIX - - -Next day Prince Andrew called at a few houses he had not visited -before, and among them at the Rostovs' with whom he had renewed -acquaintance at the ball. Apart from considerations of politeness -which demanded the call, he wanted to see that original, eager girl -who had left such a pleasant impression on his mind, in her own home. - -Natasha was one of the first to meet him. She was wearing a -dark-blue house dress in which Prince Andrew thought her even prettier -than in her ball dress. She and all the Rostov family welcomed him -as an old friend, simply and cordially. The whole family, whom he -had formerly judged severely, now seemed to him to consist of -excellent, simple, and kindly people. The old count's hospitality -and good nature, which struck one especially in Petersburg as a -pleasant surprise, were such that Prince Andrew could not refuse to -stay to dinner. "Yes," he thought, "they are capital people, who of -course have not the slightest idea what a treasure they possess in -Natasha; but they are kindly folk and form the best possible setting -for this strikingly poetic, charming girl, overflowing with life!" - -In Natasha Prince Andrew was conscious of a strange world completely -alien to him and brimful of joys unknown to him, a different world, -that in the Otradnoe avenue and at the window that moonlight night had -already begun to disconcert him. Now this world disconcerted him no -longer and was no longer alien to him, but he himself having entered -it found in it a new enjoyment. - -After dinner Natasha, at Prince Andrew's request, went to the -clavichord and began singing. Prince Andrew stood by a window -talking to the ladies and listened to her. In the midst of a phrase he -ceased speaking and suddenly felt tears choking him, a thing he had -thought impossible for him. He looked at Natasha as she sang, and -something new and joyful stirred in his soul. He felt happy and at the -same time sad. He had absolutely nothing to weep about yet he was -ready to weep. What about? His former love? The little princess? His -disillusionments?... His hopes for the future?... Yes and no. The -chief reason was a sudden, vivid sense of the terrible contrast -between something infinitely great and illimitable within him and that -limited and material something that he, and even she, was. This -contrast weighed on and yet cheered him while she sang. - -As soon as Natasha had finished she went up to him and asked how -he liked her voice. She asked this and then became confused, feeling -that she ought not to have asked it. He smiled, looking at her, and -said he liked her singing as he liked everything she did. - -Prince Andrew left the Rostovs' late in the evening. He went to -bed from habit, but soon realized that he could not sleep. Having -lit his candle he sat up in bed, then got up, then lay down again -not at all troubled by his sleeplessness: his soul was as fresh and -joyful as if he had stepped out of a stuffy room into God's own -fresh air. It did not enter his head that he was in love with Natasha; -he was not thinking about her, but only picturing her to himself, -and in consequence all life appeared in a new light. "Why do I strive, -why do I toil in this narrow, confined frame, when life, all life with -all its joys, is open to me?" said he to himself. And for the first -time for a very long while he began making happy plans for the future. -He decided that he must attend to his son's education by finding a -tutor and putting the boy in his charge, then he ought to retire -from the service and go abroad, and see England, Switzerland and -Italy. "I must use my freedom while I feel so much strength and -youth in me," he said to himself. "Pierre was right when he said one -must believe in the possibility of happiness in order to be happy, and -now I do believe in it. Let the dead bury their dead, but while one -has life one must live and be happy!" thought he. - - - - - -CHAPTER XX - - -One morning Colonel Berg, whom Pierre knew as he knew everybody in -Moscow and Petersburg, came to see him. Berg arrived in an -immaculate brand-new uniform, with his hair pomaded and brushed -forward over his temples as the Emperor Alexander wore his hair. - -"I have just been to see the countess, your wife. Unfortunately -she could not grant my request, but I hope, Count, I shall be more -fortunate with you," he said with a smile. - -"What is it you wish, Colonel? I am at your service." - -"I have now quite settled in my new rooms, Count" (Berg said this -with perfect conviction that this information could not but be -agreeable), "and so I wish to arrange just a small party for my own -and my wife's friends." (He smiled still more pleasantly.) "I wished -to ask the countess and you to do me the honor of coming to tea and to -supper." - -Only Countess Helene, considering the society of such people as -the Bergs beneath her, could be cruel enough to refuse such an -invitation. Berg explained so clearly why he wanted to collect at -his house a small but select company, and why this would give him -pleasure, and why though he grudged spending money on cards or -anything harmful, he was prepared to run into some expense for the -sake of good society--that Pierre could not refuse, and promised to -come. - -"But don't be late, Count, if I may venture to ask; about ten -minutes to eight, please. We shall make up a rubber. Our general is -coming. He is very good to me. We shall have supper, Count. So you -will do me the favor." - -Contrary to his habit of being late, Pierre on that day arrived at -the Bergs' house, not at ten but at fifteen minutes to eight. - -Having prepared everything necessary for the party, the Bergs were -ready for their guests' arrival. - -In their new, clean, and light study with its small busts and -pictures and new furniture sat Berg and his wife. Berg, closely -buttoned up in his new uniform, sat beside his wife explaining to -her that one always could and should be acquainted with people above -one, because only then does one get satisfaction from acquaintances. - -"You can get to know something, you can ask for something. See how I -managed from my first promotion." (Berg measured his life not by years -but by promotions.) "My comrades are still nobodies, while I am only -waiting for a vacancy to command a regiment, and have the happiness to -be your husband." (He rose and kissed Vera's hand, and on the way to -her straightened out a turned-up corner of the carpet.) "And how -have I obtained all this? Chiefly by knowing how to choose my -aquaintances. It goes without saying that one must be conscientious -and methodical." - -Berg smiled with a sense of his superiority over a weak woman, and -paused, reflecting that this dear wife of his was after all but a weak -woman who could not understand all that constitutes a man's dignity, -what it was ein Mann zu sein.* Vera at the same time smiling with a -sense of superiority over her good, conscientious husband, who all the -same understood life wrongly, as according to Vera all men did. -Berg, judging by his wife, thought all women weak and foolish. Vera, -judging only by her husband and generalizing from that observation, -supposed that all men, though they understand nothing and are -conceited and selfish, ascribe common sense to themselves alone. - - -*To be a man. - - -Berg rose and embraced his wife carefully, so as not to crush her -lace fichu for which he had paid a good price, kissing her straight on -the lips. - -"The only thing is, we mustn't have children too soon," he -continued, following an unconscious sequence of ideas. - -"Yes," answered Vera, "I don't at all want that. We must live for -society." - -"Princess Yusupova wore one exactly like this," said Berg, -pointing to the fichu with a happy and kindly smile. - -Just then Count Bezukhov was announced. Husband and wife glanced -at one another, both smiling with self-satisfaction, and each mentally -claiming the honor of this visit. - -"This is what what comes of knowing how to make acquaintances," -thought Berg. "This is what comes of knowing how to conduct oneself." - -"But please don't interrupt me when I am entertaining the guests," -said Vera, "because I know what interests each of them and what to say -to different people." - -Berg smiled again. - -"It can't be helped: men must sometimes have masculine -conversation," said he. - -They received Pierre in their small, new drawing-room, where it -was impossible to sit down anywhere without disturbing its symmetry, -neatness, and order; so it was quite comprehensible and not strange -that Berg, having generously offered to disturb the symmetry of an -armchair or of the sofa for his dear guest, but being apparently -painfully undecided on the matter himself, eventually left the visitor -to settle the question of selection. Pierre disturbed the symmetry -by moving a chair for himself, and Berg and Vera immediately began -their evening party, interrupting each other in their efforts to -entertain their guest. - -Vera, having decided in her own mind that Pierre ought to be -entertained with conversation about the French embassy, at once -began accordingly. Berg, having decided that masculine conversation -was required, interrupted his wife's remarks and touched on the -question of the war with Austria, and unconsciously jumped from the -general subject to personal considerations as to the proposals made -him to take part in the Austrian campaign and the reasons why he had -declined them. Though the conversation was very incoherent and Vera -was angry at the intrusion of the masculine element, both husband -and wife felt with satisfaction that, even if only one guest was -present, their evening had begun very well and was as like as two peas -to every other evening party with its talk, tea, and lighted candles. - -Before long Boris, Berg's old comrade, arrived. There was a shade of -condescension and patronage in his treatment of Berg and Vera. After -Boris came a lady with the colonel, then the general himself, then the -Rostovs, and the party became unquestionably exactly like all other -evening parties. Berg and Vera could not repress their smiles of -satisfaction at the sight of all this movement in their drawing -room, at the sound of the disconnected talk, the rustling of -dresses, and the bowing and scraping. Everything was just as everybody -always has it, especially so the general, who admired the apartment, -patted Berg on the shoulder, and with parental authority superintended -the setting out of the table for boston. The general sat down by Count -Ilya Rostov, who was next to himself the most important guest. The old -people sat with the old, the young with the young, and the hostess -at the tea table, on which stood exactly the same kind of cakes in a -silver cake basket as the Panins had at their party. Everything was -just as it was everywhere else. - - - - - -CHAPTER XXI - - -Pierre, as one of the principal guests, had to sit down to boston -with Count Rostov, the general, and the colonel. At the card table -he happened to be directly facing Natasha, and was struck by a curious -change that had come over her since the ball. She was silent, and -not only less pretty than at the ball, but only redeemed from -plainness by her look of gentle indifference to everything around. - -"What's the matter with her?" thought Pierre, glancing at her. She -was sitting by her sister at the tea table, and reluctantly, without -looking at him, made some reply to Boris who sat down beside her. -After playing out a whole suit and to his partner's delight taking -five tricks, Pierre, hearing greetings and the steps of someone who -had entered the room while he was picking up his tricks, glanced again -at Natasha. - -"What has happened to her?" he asked himself with still greater -surprise. - -Prince Andrew was standing before her, saying something to her -with a look of tender solicitude. She, having raised her head, was -looking up at him, flushed and evidently trying to master her rapid -breathing. And the bright glow of some inner fire that had been -suppressed was again alight in her. She was completely transformed and -from a plain girl had again become what she had been at the ball. - -Prince Andrew went up to Pierre, and the latter noticed a new and -youthful expression in his friend's face. - -Pierre changed places several times during the game, sitting now -with his back to Natasha and now facing her, but during the whole of -the six rubbers he watched her and his friend. - -"Something very important is happening between them," thought -Pierre, and a feeling that was both joyful and painful agitated him -and made him neglect the game. - -After six rubbers the general got up, saying that it was no use -playing like that, and Pierre was released. Natasha on one side was -talking with Sonya and Boris, and Vera with a subtle smile was -saying something to Prince Andrew. Pierre went up to his friend and, -asking whether they were talking secrets, sat down beside them. -Vera, having noticed Prince Andrew's attentions to Natasha, decided -that at a party, a real evening party, subtle allusions to the -tender passion were absolutely necessary and, seizing a moment when -Prince Andrew was alone, began a conversation with him about -feelings in general and about her sister. With so intellectual a guest -as she considered Prince Andrew to be, she felt that she had to employ -her diplomatic tact. - -When Pierre went up to them he noticed that Vera was being carried -away by her self-satisfied talk, but that Prince Andrew seemed -embarrassed, a thing that rarely happened with him. - -"What do you think?" Vera was saying with an arch smile. "You are so -discerning, Prince, and understand people's characters so well at a -glance. What do you think of Natalie? Could she be constant in her -attachments? Could she, like other women" (Vera meant herself), -"love a man once for all and remain true to him forever? That is -what I consider true love. What do you think, Prince?" - -"I know your sister too little," replied Prince Andrew, with a -sarcastic smile under which he wished to hide his embarrassment, "to -be able to solve so delicate a question, and then I have noticed -that the less attractive a woman is the more constant she is likely to -be," he added, and looked up Pierre who was just approaching them. - -"Yes, that is true, Prince. In our days," continued Vera--mentioning -"our days" as people of limited intelligence are fond of doing, -imagining that they have discovered and appraised the peculiarities of -"our days" and that human characteristics change with the times--"in -our days a girl has so much freedom that the pleasure of being courted -often stifles real feeling in her. And it must be confessed that -Natalie is very susceptible." This return to the subject of Natalie -caused Prince Andrew to knit his brows with discomfort: he was about -to rise, but Vera continued with a still more subtle smile: - -"I think no one has been more courted than she," she went on, "but -till quite lately she never cared seriously for anyone. Now you -know, Count," she said to Pierre, "even our dear cousin Boris, who, -between ourselves, was very far gone in the land of tenderness..." -(alluding to a map of love much in vogue at that time). - -Prince Andrew frowned and remained silent. - -"You are friendly with Boris, aren't you?" asked Vera. - -"Yes, I know him..." - -"I expect he has told you of his childish love for Natasha?" - -"Oh, there was childish love?" suddenly asked Prince Andrew, -blushing unexpectedly. - -"Yes, you know between cousins intimacy often leads to love. Le -cousinage est un dangereux voisinage.* Don't you think so?" - - -*"Cousinhood is a dangerous neighborhood." - - -"Oh, undoubtedly!" said Prince Andrew, and with sudden and unnatural -liveliness he began chaffing Pierre about the need to be very -careful with his fifty-year-old Moscow cousins, and in the midst of -these jesting remarks he rose, taking Pierre by the arm, and drew -him aside. - -"Well?" asked Pierre, seeing his friend's strange animation with -surprise, and noticing the glance he turned on Natasha as he rose. - -"I must... I must have a talk with you," said Prince Andrew. "You -know that pair of women's gloves?" (He referred to the Masonic -gloves given to a newly initiated Brother to present to the woman he -loved.) "I... but no, I will talk to you later on," and with a strange -light in his eyes and restlessness in his movements, Prince Andrew -approached Natasha and sat down beside her. Pierre saw how Prince -Andrew asked her something and how she flushed as she replied. - -But at that moment Berg came to Pierre and began insisting that he -should take part in an argument between the general and the colonel on -the affairs in Spain. - -Berg was satisfied and happy. The smile of pleasure never left his -face. The party was very successful and quite like other parties he -had seen. Everything was similar: the ladies' subtle talk, the -cards, the general raising his voice at the card table, and the -samovar and the tea cakes; only one thing was lacking that he had -always seen at the evening parties he wished to imitate. They had -not yet had a loud conversation among the men and a dispute about -something important and clever. Now the general had begun such a -discussion and so Berg drew Pierre to it. - - - - - -CHAPTER XXII - - -Next day, having been invited by the count, Prince Andrew dined with -the Rostovs and spent the rest of the day there. - -Everyone in the house realized for whose sake Prince Andrew came, -and without concealing it he tried to be with Natasha all day. Not -only in the soul of the frightened yet happy and enraptured Natasha, -but in the whole house, there was a feeling of awe at something -important that was bound to happen. The countess looked with sad and -sternly serious eyes at Prince Andrew when he talked to Natasha and -timidly started some artificial conversation about trifles as soon -as he looked her way. Sonya was afraid to leave Natasha and afraid -of being in the way when she was with them. Natasha grew pale, in a -panic of expectation, when she remained alone with him for a moment. -Prince Andrew surprised her by his timidity. She felt that he wanted -to say something to her but could not bring himself to do so. - -In the evening, when Prince Andrew had left, the countess went up to -Natasha and whispered: "Well, what?" - -"Mamma! For heaven's sake don't ask me anything now! One can't -talk about that," said Natasha. - -But all the same that night Natasha, now agitated and now -frightened, lay a long time in her mother's bed gazing straight -before her. She told her how he had complimented her, how he told -her he was going abroad, asked her where they were going to spend -the summer, and then how he had asked her about Boris. - -"But such a... such a... never happened to me before!" she said. -"Only I feel afraid in his presence. I am always afraid when I'm -with him. What does that mean? Does it mean that it's the real -thing? Yes? Mamma, are you asleep?" - -"No, my love; I am frightened myself," answered her mother. "Now -go!" - -"All the same I shan't sleep. What silliness, to sleep! Mummy! -Mummy! such a thing never happened to me before," she said, -surprised and alarmed at the feeling she was aware of in herself. "And -could we ever have thought!..." - -It seemed to Natasha that even at the time she first saw Prince -Andrew at Otradnoe she had fallen in love with him. It was as if she -feared this strange, unexpected happiness of meeting again the very -man she had then chosen (she was firmly convinced she had done so) and -of finding him, as it seemed, not indifferent to her. - -"And it had to happen that he should come specially to Petersburg -while we are here. And it had to happen that we should meet at that -ball. It is fate. Clearly it is fate that everything led up to this! -Already then, directly I saw him I felt something peculiar." - -"What else did he say to you? What are those verses? Read them..." -said her mother, thoughtfully, referring to some verses Prince -Andrew had written in Natasha's album. - -"Mamma, one need not be ashamed of his being a widower?" - -"Don't, Natasha! Pray to God. 'Marriages are made in heaven,'" -said her mother. - -"Darling Mummy, how I love you! How happy I am!" cried Natasha, -shedding tears of joy and excitement and embracing her mother. - -At that very time Prince Andrew was sitting with Pierre and -telling him of his love for Natasha and his firm resolve to make her -his wife. - -That day Countess Helene had a reception at her house. The French -ambassador was there, and a foreign prince of the blood who had of -late become a frequent visitor of hers, and many brilliant ladies -and gentlemen. Pierre, who had come downstairs, walked through the -rooms and struck everyone by his preoccupied, absent-minded, and -morose air. - -Since the ball he had felt the approach of a fit of nervous -depression and had made desperate efforts to combat it. Since the -intimacy of his wife with the royal prince, Pierre had unexpectedly -been made a gentleman of the bedchamber, and from that time he had -begun to feel oppressed and ashamed in court society, and dark -thoughts of the vanity of all things human came to him oftener than -before. At the same time the feeling he had noticed between his -protegee Natasha and Prince Andrew accentuated his gloom by the -contrast between his own position and his friend's. He tried equally -to avoid thinking about his wife, and about Natasha and Prince Andrew; -and again everything seemed to him insignificant in comparison with -eternity; again the question: for what? presented itself; and he -forced himself to work day and night at Masonic labors, hoping to -drive away the evil spirit that threatened him. Toward midnight, after -he had left the countess' apartments, he was sitting upstairs in a -shabby dressing gown, copying out the original transaction of the -Scottish lodge of Freemasons at a table in his low room cloudy with -tobacco smoke, when someone came in. It was Prince Andrew. - -"Ah, it's you!" said Pierre with a preoccupied, dissatisfied air. -"And I, you see, am hard at it." He pointed to his manuscript book -with that air of escaping from the ills of life with which unhappy -people look at their work. - -Prince Andrew, with a beaming, ecstatic expression of renewed life -on his face, paused in front of Pierre and, not noticing his sad look, -smiled at him with the egotism of joy. - -"Well, dear heart," said he, "I wanted to tell you about it -yesterday and I have come to do so today. I never experienced anything -like it before. I am in love, my friend!" - -Suddenly Pierre heaved a deep sigh and dumped his heavy person -down on the sofa beside Prince Andrew. - -"With Natasha Rostova, yes?" said he. - -"Yes, yes! Who else should it be? I should never have believed it, -but the feeling is stronger than I. Yesterday I tormented myself and -suffered, but I would not exchange even that torment for anything in -the world, I have not lived till now. At last I live, but I can't live -without her! But can she love me?... I am too old for her.... Why -don't you speak?" - -"I? I? What did I tell you?" said Pierre suddenly, rising and -beginning to pace up and down the room. "I always thought it.... -That girl is such a treasure... she is a rare girl.... My dear friend, -I entreat you, don't philosophize, don't doubt, marry, marry, -marry.... And I am sure there will not be a happier man than you." - -"But what of her?" - -"She loves you." - -"Don't talk rubbish..." said Prince Andrew, smiling and looking into -Pierre's eyes. - -"She does, I know," Pierre cried fiercely. - -"But do listen," returned Prince Andrew, holding him by the arm. "Do -you know the condition I am in? I must talk about it to someone." - -"Well, go on, go on. I am very glad," said Pierre, and his face -really changed, his brow became smooth, and he listened gladly to -Prince Andrew. Prince Andrew seemed, and really was, quite a -different, quite a new man. Where was his spleen, his contempt for -life, his disillusionment? Pierre was the only person to whom he -made up his mind to speak openly; and to him he told all that was in -his soul. Now he boldly and lightly made plans for an extended future, -said he could not sacrifice his own happiness to his father's caprice, -and spoke of how he would either make his father consent to this -marriage and love her, or would do without his consent; then he -marveled at the feeling that had mastered him as at something strange, -apart from and independent of himself. - -"I should not have believed anyone who told me that I was capable of -such love," said Prince Andrew. "It is not at all the same feeling -that I knew in the past. The whole world is now for me divided into -two halves: one half is she, and there all is joy, hope, light: the -other half is everything where she is not, and there is all gloom -and darkness...." - -"Darkness and gloom," reiterated Pierre: "yes, yes, I understand -that." - -"I cannot help loving the light, it is not my fault. And I am very -happy! You understand me? I know you are glad for my sake." - -"Yes, yes," Pierre assented, looking at his friend with a touched -and sad expression in his eyes. The brighter Prince Andrew's lot -appeared to him, the gloomier seemed his own. - - - - - -CHAPTER XXIII - - -Prince Andrew needed his father's consent to his marriage, and to -obtain this he started for the country next day. - -His father received his son's communication with external composure, -but inward wrath. He could not comprehend how anyone could wish to -alter his life or introduce anything new into it, when his own life -was already ending. "If only they would let me end my days as I want -to," thought the old man, "then they might do as they please." With -his son, however, he employed the diplomacy he reserved for -important occasions and, adopting a quiet tone, discussed the whole -matter. - -In the first place the marriage was not a brilliant one as regards -birth, wealth, or rank. Secondly, Prince Andrew was no longer as young -as he had been and his health was poor (the old man laid special -stress on this), while she was very young. Thirdly, he had a son -whom it would be a pity to entrust to a chit of a girl. "Fourthly -and finally," the father said, looking ironically at his son, "I beg -you to put it off for a year: go abroad, take a cure, look out as -you wanted to for a German tutor for Prince Nicholas. Then if your -love or passion or obstinacy--as you please--is still as great, marry! -And that's my last word on it. Mind, the last..." concluded the -prince, in a tone which showed that nothing would make him alter his -decision. - -Prince Andrew saw clearly that the old man hoped that his -feelings, or his fiancee's, would not stand a year's test, or that -he (the old prince himself) would die before then, and he decided to -conform to his father's wish--to propose, and postpone the wedding for -a year. - -Three weeks after the last evening he had spent with the Rostovs, -Prince Andrew returned to Petersburg. - - -Next day after her talk with her mother Natasha expected Bolkonski -all day, but he did not come. On the second and third day it was the -same. Pierre did not come either and Natasha, not knowing that -Prince Andrew had gone to see his father, could not explain his -absence to herself. - -Three weeks passed in this way. Natasha had no desire to go out -anywhere and wandered from room to room like a shadow, idle and -listless; she wept secretly at night and did not go to her mother in -the evenings. She blushed continually and was irritable. It seemed -to her that everybody knew about her disappointment and was laughing -at her and pitying her. Strong as was her inward grief, this wound -to her vanity intensified her misery. - -Once she came to her mother, tried to say something, and suddenly -began to cry. Her tears were those of an offended child who does not -know why it is being punished. - -The countess began to soothe Natasha, who after first listening to -her mother's words, suddenly interrupted her: - -"Leave off, Mamma! I don't think, and don't want to think about -it! He just came and then left off, left off..." - -Her voice trembled, and she again nearly cried, but recovered and -went on quietly: - -"And I don't at all want to get married. And I am afraid of him; I -have now become quite calm, quite calm." - -The day after this conversation Natasha put on the old dress which -she knew had the peculiar property of conducing to cheerfulness in the -mornings, and that day she returned to the old way of life which she -had abandoned since the ball. Having finished her morning tea she went -to the ballroom, which she particularly liked for its loud -resonance, and began singing her solfeggio. When she had finished -her first exercise she stood still in the middle of the room and -sang a musical phrase that particularly pleased her. She listened -joyfully (as though she had not expected it) to the charm of the notes -reverberating, filling the whole empty ballroom, and slowly dying -away; and all at once she felt cheerful. "What's the good of making so -much of it? Things are nice as it is," she said to herself, and she -began walking up and down the room, not stepping simply on the -resounding parquet but treading with each step from the heel to the -toe (she had on a new and favorite pair of shoes) and listening to the -regular tap of the heel and creak of the toe as gladly as she had to -the sounds of her own voice. Passing a mirror she glanced into it. -"There, that's me!" the expression of her face seemed to say as she -caught sight of herself. "Well, and very nice too! I need nobody." - -A footman wanted to come in to clear away something in the room -but she would not let him, and having closed the door behind him -continued her walk. That morning she had returned to her favorite -mood--love of, and delight in, herself. "How charming that Natasha -is!" she said again, speaking as some third, collective, male -person. "Pretty, a good voice, young, and in nobody's way if only they -leave her in peace." But however much they left her in peace she could -not now be at peace, and immediately felt this. - -In the hall the porch door opened, and someone asked, "At home?" and -then footsteps were heard. Natasha was looking at the mirror, but -did not see herself. She listened to the sounds in the hall. When -she saw herself, her face was pale. It was he. She knew this for -certain, though she hardly heard his voice through the closed doors. - -Pale and agitated, Natasha ran into the drawing room. - -"Mamma! Bolkonski has come!" she said. "Mamma, it is awful, it is -unbearable! I don't want... to be tormented? What am I to do?..." - -Before the countess could answer, Prince Andrew entered the room -with an agitated and serious face. As soon as he saw Natasha his -face brightened. He kissed the countess' hand and Natasha's, and sat -down beside the sofa. - -"It is long since we had the pleasure..." began the countess, but -Prince Andrew interrupted her by answering her intended question, -obviously in haste to say what he had to. - -"I have not been to see all this time because I have been at my -father's. I had to talk over a very important matter with him. I -only got back last night," he said glancing at Natasha; "I want to -have a talk with you, Countess," he added after a moment's pause. - -The countess lowered her eyes, sighing deeply. - -"I am at your disposal," she murmured. - -Natasha knew that she ought to go away, but was unable to do so: -something gripped her throat, and regardless of manners she stared -straight at Prince Andrew with wide-open eyes. - -"At once? This instant!... No, it can't be!" she thought. - -Again he glanced at her, and that glance convinced her that she -was not mistaken. Yes, at once, that very instant, her fate would be -decided. - -"Go, Natasha! I will call you," said the countess in a whisper. - -Natasha glanced with frightened imploring eyes at Prince Andrew -and at her mother and went out. - -"I have come, Countess, to ask for your daughter's hand," said -Prince Andrew. - -The countess' face flushed hotly, but she said nothing. - -"Your offer..." she began at last sedately. He remained silent, -looking into her eyes. "Your offer..." (she grew confused) "is -agreeable to us, and I accept your offer. I am glad. And my husband... -I hope... but it will depend on her...." - -"I will speak to her when I have your consent.... Do you give it -to me?" said Prince Andrew. - -"Yes," replied the countess. She held out her hand to him, and -with a mixed feeling of estrangement and tenderness pressed her lips -to his forehead as he stooped to kiss her hand. She wished to love him -as a son, but felt that to her he was a stranger and a terrifying man. -"I am sure my husband will consent," said the countess, "but your -father..." - -"My father, to whom I have told my plans, has made it an express -condition of his consent that the wedding is not to take place for a -year. And I wished to tell you of that," said Prince Andrew. - -"It is true that Natasha is still young, but--so long as that?..." - -"It is unavoidable," said Prince Andrew with a sigh. - -"I will send her to you," said the countess, and left the room. - -"Lord have mercy upon us!" she repeated while seeking her daughter. - -Sonya said that Natasha was in her bedroom. Natasha was sitting on -the bed, pale and dry eyed, and was gazing at the icons and whispering -something as she rapidly crossed herself. Seeing her mother she jumped -up and flew to her. - -"Well, Mamma?... Well?..." - -"Go, go to him. He is asking for your hand," said the countess, -coldly it seemed to Natasha. "Go... go," said the mother, sadly and -reproachfully, with a deep sigh, as her daughter ran away. - -Natasha never remembered how she entered the drawing room. When -she came in and saw him she paused. "Is it possible that this stranger -has now become everything to me?" she asked herself, and immediately -answered, "Yes, everything! He alone is now dearer to me than -everything in the world." Prince Andrew came up to her with downcast -eyes. - -"I have loved you from the very first moment I saw you. May I hope?" - -He looked at her and was struck by the serious impassioned -expression of her face. Her face said: "Why ask? Why doubt what you -cannot but know? Why speak, when words cannot express what one feels?" - -She drew near to him and stopped. He took her hand and kissed it. - -"Do you love me?" - -"Yes, yes!" Natasha murmured as if in vexation. Then she sighed -loudly and, catching her breath more and more quickly, began to sob. - -"What is it? What's the matter?" - -"Oh, I am so happy!" she replied, smiled through her tears, bent -over closer to him, paused for an instant as if asking herself whether -she might, and then kissed him. - -Prince Andrew held her hands, looked into her eyes, and did not find -in his heart his former love for her. Something in him had suddenly -changed; there was no longer the former poetic and mystic charm of -desire, but there was pity for her feminine and childish weakness, -fear at her devotion and trustfulness, and an oppressive yet joyful -sense of the duty that now bound him to her forever. The present -feeling, though not so bright and poetic as the former, was stronger -and more serious. - -"Did your mother tell you that it cannot be for a year?" asked -Prince Andrew, still looking into her eyes. - -"Is it possible that I--the 'chit of a girl,' as everybody called -me," thought Natasha--"is it possible that I am now to be the wife and -the equal of this strange, dear, clever man whom even my father -looks up to? Can it be true? Can it be true that there can be no -more playing with life, that now I am grown up, that on me now lies -a responsibility for my every word and deed? Yes, but what did he -ask me?" - -"No," she replied, but she had not understood his question. - -"Forgive me!" he said. "But you are so young, and I have already -been through so much in life. I am afraid for you, you do not yet know -yourself." - -Natasha listened with concentrated attention, trying but failing -to take in the meaning of his words. - -"Hard as this year which delays my happiness will be," continued -Prince Andrew, "it will give you time to be sure of yourself. I ask -you to make me happy in a year, but you are free: our engagement shall -remain a secret, and should you find that you do not love me, or -should you come to love..." said Prince Andrew with an unnatural -smile. - -"Why do you say that?" Natasha interrupted him. "You know that -from the very day you first came to Otradnoe I have loved you," she -cried, quite convinced that she spoke the truth. - -"In a year you will learn to know yourself...." - -"A whole year!" Natasha repeated suddenly, only now realizing that -the marriage was to be postponed for a year. "But why a year? Why a -year?..." - -Prince Andrew began to explain to her the reasons for this delay. -Natasha did not hear him. - -"And can't it be helped?" she asked. Prince Andrew did not reply, -but his face expressed the impossibility of altering that decision. - -"It's awful! Oh, it's awful! awful!" Natasha suddenly cried, and -again burst into sobs. "I shall die, waiting a year: it's -impossible, it's awful!" She looked into her lover's face and saw in -it a look of commiseration and perplexity. - -"No, no! I'll do anything!" she said, suddenly checking her tears. -"I am so happy." - -The father and mother came into the room and gave the betrothed -couple their blessing. - -From that day Prince Andrew began to frequent the Rostovs' as -Natasha's affianced lover. - - - - - -CHAPTER XXIV - -No betrothal ceremony took place and Natasha's engagement to -Bolkonski was not announced; Prince Andrew insisted on that. He said -that as he was responsible for the delay he ought to bear the whole -burden of it; that he had given his word and bound himself forever, -but that he did not wish to bind Natasha and gave her perfect freedom. -If after six months she felt that she did not love him she would -have full right to reject him. Naturally neither Natasha nor her -parents wished to hear of this, but Prince Andrew was firm. He came -every day to the Rostovs', but did not behave to Natasha as an -affianced lover: he did not use the familiar thou, but said you to -her, and kissed only her hand. After their engagement, quite -different, intimate, and natural relations sprang up between them. -It was as if they had not known each other till now. Both liked to -recall how they had regarded each other when as yet they were -nothing to one another; they felt themselves now quite different -beings: then they were artificial, now natural and sincere. At first -the family felt some constraint in intercourse with Prince Andrew; -he seemed a man from another world, and for a long time Natasha -trained the family to get used to him, proudly assuring them all -that he only appeared to be different, but was really just like all of -them, and that she was not afraid of him and no one else ought to -be. After a few days they grew accustomed to him, and without -restraint in his presence pursued their usual way of life, in which he -took his part. He could talk about rural economy with the count, -fashions with the countess and Natasha, and about albums and fancywork -with Sonya. Sometimes the household both among themselves and in his -presence expressed their wonder at how it had all happened, and at the -evident omens there had been of it: Prince Andrew's coming to Otradnoe -and their coming to Petersburg, and the likeness between Natasha and -Prince Andrew which her nurse had noticed on his first visit, and -Andrew's encounter with Nicholas in 1805, and many other incidents -betokening that it had to be. - -In the house that poetic dullness and quiet reigned which always -accompanies the presence of a betrothed couple. Often when all sitting -together everyone kept silent. Sometimes the others would get up and -go away and the couple, left alone, still remained silent. They rarely -spoke of their future life. Prince Andrew was afraid and ashamed to -speak of it. Natasha shared this as she did all his feelings, which -she constantly divined. Once she began questioning him about his -son. Prince Andrew blushed, as he often did now--Natasha -particularly liked it in him--and said that his son would not live -with them. - -"Why not?" asked Natasha in a frightened tone. - -"I cannot take him away from his grandfather, and besides..." - -"How I should have loved him!" said Natasha, immediately guessing -his thought; "but I know you wish to avoid any pretext for finding -fault with us." - -Sometimes the old count would come up, kiss Prince Andrew, and ask -his advice about Petya's education or Nicholas' service. The old -countess sighed as she looked at them; Sonya was always getting -frightened lest she should be in the way and tried to find excuses for -leaving them alone, even when they did not wish it. When Prince Andrew -spoke (he could tell a story very well), Natasha listened to him -with pride; when she spoke she noticed with fear and joy that he gazed -attentively and scrutinizingly at her. She asked herself in -perplexity: "What does he look for in me? He is trying to discover -something by looking at me! What if what he seeks in me is not there?" -Sometimes she fell into one of the mad, merry moods characteristic -of her, and then she particularly loved to hear and see how Prince -Andrew laughed. He seldom laughed, but when he did he abandoned -himself entirely to his laughter, and after such a laugh she always -felt nearer to him. Natasha would have been completely happy if the -thought of the separation awaiting her and drawing near had not -terrified her, just as the mere thought of it made him turn pale and -cold. - -On the eve of his departure from Petersburg Prince Andrew brought -with him Pierre, who had not been to the Rostovs' once since the ball. -Pierre seemed disconcerted and embarrassed. He was talking to the -countess, and Natasha sat down beside a little chess table with Sonya, -thereby inviting Prince Andrew to come too. He did so. - -"You have known Bezukhov a long time?" he asked. "Do you like him?" - -"Yes, he's a dear, but very absurd." - -And as usual when speaking of Pierre, she began to tell anecdotes of -his absent-mindedness, some of which had even been invented about him. - -"Do you know I have entrusted him with our secret? I have known -him from childhood. He has a heart of gold. I beg you, Natalie," -Prince Andrew said with sudden seriousness--"I am going away and -heaven knows what may happen. You may cease to... all right, I know -I am not to say that. Only this, then: whatever may happen to you when -I am not here..." - -"What can happen?" - -"Whatever trouble may come," Prince Andrew continued, "I beg you, -Mademoiselle Sophie, whatever may happen, to turn to him alone for -advice and help! He is a most absent-minded and absurd fellow, but -he has a heart of gold." - -Neither her father, nor her mother, nor Sonya, nor Prince Andrew -himself could have foreseen how the separation from her lover would -act on Natasha. Flushed and agitated she went about the house all that -day, dry-eyed, occupied with most trivial matters as if not -understanding what awaited her. She did not even cry when, on taking -leave, he kissed her hand for the last time. "Don't go!" she said in a -tone that made him wonder whether he really ought not to stay and -which he remembered long afterwards. Nor did she cry when he was gone; -but for several days she sat in her room dry-eyed, taking no -interest in anything and only saying now and then, "Oh, why did he -go away?" - -But a fortnight after his departure, to the surprise of those around -her, she recovered from her mental sickness just as suddenly and -became her old self again, but with a change in her moral physiognomy, -as a child gets up after a long illness with a changed expression of -face. - - - - - -CHAPTER XXV - - -During that year after his son's departure, Prince Nicholas -Bolkonski's health and temper became much worse. He grew still more -irritable, and it was Princess Mary who generally bore the brunt of -his frequent fits of unprovoked anger. He seemed carefully to seek out -her tender spots so as to torture her mentally as harshly as possible. -Princess Mary had two passions and consequently two joys--her -nephew, little Nicholas, and religion--and these were the favorite -subjects of the prince's attacks and ridicule. Whatever was spoken -of he would bring round to the superstitiousness of old maids, or -the petting and spoiling of children. "You want to make him"--little -Nicholas--"into an old maid like yourself! A pity! Prince Andrew wants -a son and not an old maid," he would say. Or, turning to -Mademoiselle Bourienne, he would ask her in Princess Mary's presence -how she liked our village priests and icons and would joke about them. - -He continually hurt Princess Mary's feelings and tormented her, -but it cost her no effort to forgive him. Could he be to blame -toward her, or could her father, whom she knew loved her in spite of -it all, be unjust? And what is justice? The princess never thought -of that proud word "justice." All the complex laws of man centered for -her in one clear and simple law--the law of love and self-sacrifice -taught us by Him who lovingly suffered for mankind though He Himself -was God. What had she to do with the justice or injustice of other -people? She had to endure and love, and that she did. - -During the winter Prince Andrew had come to Bald Hills and had -been gay, gentle, and more affectionate than Princess Mary had known -him for a long time past. She felt that something had happened to him, -but he said nothing to her about his love. Before he left he had a -long talk with his father about something, and Princess Mary noticed -that before his departure they were dissatisfied with one another. - -Soon after Prince Andrew had gone, Princess Mary wrote to her friend -Julie Karagina in Petersburg, whom she had dreamed (as all girls -dream) of marrying to her brother, and who was at that time in -mourning for her own brother, killed in Turkey. - - -Sorrow, it seems, is our common lot, my dear, tender friend Julie. - -Your loss is so terrible that I can only explain it to myself as a -special providence of God who, loving you, wishes to try you and -your excellent mother. Oh, my friend! Religion, and religion alone, -can--I will not say comfort us--but save us from despair. Religion -alone can explain to us what without its help man cannot comprehend: -why, for what cause, kind and noble beings able to find happiness in -life--not merely harming no one but necessary to the happiness of -others--are called away to God, while cruel, useless, harmful persons, -or such as are a burden to themselves and to others, are left -living. The first death I saw, and one I shall never forget--that of -my dear sister-in-law--left that impression on me. Just as you ask -destiny why your splendid brother had to die, so I asked why that -angel Lise, who not only never wronged anyone, but in whose soul there -were never any unkind thoughts, had to die. And what do you think, -dear friend? Five years have passed since then, and already I, with my -petty understanding, begin to see clearly why she had to die, and in -what way that death was but an expression of the infinite goodness -of the Creator, whose every action, though generally -incomprehensible to us, is but a manifestation of His infinite love -for His creatures. Perhaps, I often think, she was too angelically -innocent to have the strength to perform all a mother's duties. As a -young wife she was irreproachable; perhaps she could not have been -so as a mother. As it is, not only has she left us, and particularly -Prince Andrew, with the purest regrets and memories, but probably -she will there receive a place I dare not hope for myself. But not -to speak of her alone, that early and terrible death has had the -most beneficent influence on me and on my brother in spite of all -our grief. Then, at the moment of our loss, these thoughts could not -occur to me; I should then have dismissed them with horror, but now -they are very clear and certain. I write all this to you, dear friend, -only to convince you of the Gospel truth which has become for me a -principle of life: not a single hair of our heads will fall without -His will. And His will is governed only by infinite love for us, and -so whatever befalls us is for our good. - -You ask whether we shall spend next winter in Moscow. In spite of my -wish to see you, I do not think so and do not want to do so. You -will be surprised to hear that the reason for this is Buonaparte! -The case is this: my father's health is growing noticeably worse, he -cannot stand any contradiction and is becoming irritable. This -irritability is, as you know, chiefly directed to political questions. -He cannot endure the notion that Buonaparte is negotiating on equal -terms with all the sovereigns of Europe and particularly with our own, -the grandson of the Great Catherine! As you know, I am quite -indifferent to politics, but from my father's remarks and his talks -with Michael Ivanovich I know all that goes on in the world and -especially about the honors conferred on Buonaparte, who only at -Bald Hills in the whole world, it seems, is not accepted as a great -man, still less as Emperor of France. And my father cannot stand this. -It seems to me that it is chiefly because of his political views -that my father is reluctant to speak of going to Moscow; for he -foresees the encounters that would result from his way of expressing -his views regardless of anybody. All the benefit he might derive -from a course of treatment he would lose as a result of the disputes -about Buonaparte which would be inevitable. In any case it will be -decided very shortly. - -Our family life goes on in the old way except for my brother -Andrew's absence. He, as I wrote you before, has changed very much -of late. After his sorrow he only this year quite recovered his -spirits. He has again become as I used to know him when a child: kind, -affectionate, with that heart of gold to which I know no equal. He has -realized, it seems to me, that life is not over for him. But -together with this mental change he has grown physically much -weaker. He has become thinner and more nervous. I am anxious about him -and glad he is taking this trip abroad which the doctors recommended -long ago. I hope it will cure him. You write that in Petersburg he -is spoken of as one of the most active, cultivated, and capable of the -young men. Forgive my vanity as a relation, but I never doubted it. -The good he has done to everybody here, from his peasants up to the -gentry, is incalculable. On his arrival in Petersburg he received only -his due. I always wonder at the way rumors fly from Petersburg to -Moscow, especially such false ones as that you write about--I mean the -report of my brother's betrothal to the little Rostova. I do not think -my brother will ever marry again, and certainly not her; and this is -why: first, I know that though he rarely speaks about the wife he -has lost, the grief of that loss has gone too deep in his heart for -him ever to decide to give her a successor and our little angel a -stepmother. Secondly because, as far as I know, that girl is not the -kind of girl who could please Prince Andrew. I do not think he would -choose her for a wife, and frankly I do not wish it. But I am -running on too long and am at the end of my second sheet. Good-by, -my dear friend. May God keep you in His holy and mighty care. My -dear friend, Mademoiselle Bourienne, sends you kisses. - -MARY - - - - - -CHAPTER XXVI - - -In the middle of the summer Princess Mary received an unexpected -letter from Prince Andrew in Switzerland in which he gave her -strange and surprising news. He informed her of his engagement to -Natasha Rostova. The whole letter breathed loving rapture for his -betrothed and tender and confiding affection for his sister. He -wrote that he had never loved as he did now and that only now did he -understand and know what life was. He asked his sister to forgive -him for not having told her of his resolve when he had last visited -Bald Hills, though he had spoken of it to his father. He had not -done so for fear Princess Mary should ask her father to give his -consent, irritating him and having to bear the brunt of his -displeasure without attaining her object. "Besides," he wrote, "the -matter was not then so definitely settled as it is now. My father then -insisted on a delay of a year and now already six months, half of that -period, have passed, and my resolution is firmer than ever. If the -doctors did not keep me here at the spas I should be back in Russia, -but as it is I have to postpone my return for three months. You know -me and my relations with Father. I want nothing from him. I have -been and always shall be independent; but to go against his will and -arouse his anger, now that he may perhaps remain with us such a -short time, would destroy half my happiness. I am now writing to him -about the same question, and beg you to choose a good moment to hand -him the letter and to let me know how he looks at the whole matter and -whether there is hope that he may consent to reduce the term by four -months." - -After long hesitations, doubts, and prayers, Princess Mary gave -the letter to her father. The next day the old prince said to her -quietly: - -"Write and tell your brother to wait till I am dead.... It won't -be long--I shall soon set him free." - -The princess was about to reply, but her father would not let her -speak and, raising his voice more and more, cried: - -"Marry, marry, my boy!... A good family!... Clever people, eh? Rich, -eh? Yes, a nice stepmother little Nicholas will have! Write and tell -him that he may marry tomorrow if he likes. She will be little -Nicholas' stepmother and I'll marry Bourienne!... Ha, ha, ha! He -mustn't be without a stepmother either! Only one thing, no more -women are wanted in my house--let him marry and live by himself. -Perhaps you will go and live with him too?" he added, turning to -Princess Mary. "Go in heavens name! Go out into the frost... the -frost... the frost! - -After this outburst the prince did not speak any more about the -matter. But repressed vexation at his son's poor-spirited behavior -found expression in his treatment of his daughter. To his former -pretexts for irony a fresh one was now added--allusions to stepmothers -and amiabilities to Mademoiselle Bourienne. - -"Why shouldn't I marry her?" he asked his daughter. "She'll make a -splendid princess!" - -And latterly, to her surprise and bewilderment, Princess Mary -noticed that her father was really associating more and more with -the Frenchwoman. She wrote to Prince Andrew about the reception of his -letter, but comforted him with hopes of reconciling their father to -the idea. - -Little Nicholas and his education, her brother Andrew, and -religion were Princess Mary's joys and consolations; but besides that, -since everyone must have personal hopes, Princess Mary in the -profoundest depths of her heart had a hidden dream and hope that -supplied the chief consolation of her life. This comforting dream -and hope were given her by God's folk--the half-witted and other -pilgrims who visited her without the prince's knowledge. The longer -she lived, the more experience and observation she had of life, the -greater was her wonder at the short-sightedness of men who seek -enjoyment and happiness here on earth: toiling, suffering, struggling, -and harming one another, to obtain that impossible, visionary, -sinful happiness. Prince Andrew had loved his wife, she died, but that -was not enough: he wanted to bind his happiness to another woman. -Her father objected to this because he wanted a more distinguished and -wealthier match for Andrew. And they all struggled and suffered and -tormented one another and injured their souls, their eternal souls, -for the attainment of benefits which endure but for an instant. Not -only do we know this ourselves, but Christ, the Son of God, came -down to earth and told us that this life is but for a moment and is -a probation; yet we cling to it and think to find happiness in it. -"How is it that no one realizes this?" thought Princess Mary. "No -one except these despised God's folk who, wallet on back, come to me -by the back door, afraid of being seen by the prince, not for fear -of ill-usage by him but for fear of causing him to sin. To leave -family, home, and all the cares of worldly welfare, in order without -clinging to anything to wander in hempen rags from place to place -under an assumed name, doing no one any harm but praying for all- -for those who drive one away as well as for those who protect one: -higher than that life and truth there is no life or truth!" - -There was one pilgrim, a quiet pockmarked little woman of fifty -called Theodosia, who for over thirty years had gone about barefoot -and worn heavy chains. Princess Mary was particularly fond of her. -Once, when in a room with a lamp dimly lit before the icon Theodosia -was talking of her life, the thought that Theodosia alone had found -the true path of life suddenly came to Princess Mary with such force -that she resolved to become a pilgrim herself. When Theodosia had gone -to sleep Princess Mary thought about this for a long time, and at last -made up her mind that, strange as it might seem, she must go on a -pilgrimage. She disclosed this thought to no one but to her confessor, -Father Akinfi, the monk, and he approved of her intention. Under guise -of a present for the pilgrims, Princess Mary prepared a pilgrim's -complete costume for herself: a coarse smock, bast shoes, a rough -coat, and a black kerchief. Often, approaching the chest of drawers -containing this secret treasure, Princess Mary paused, uncertain -whether the time had not already come to put her project into -execution. - -Often, listening to the pilgrims' tales, she was so stimulated by -their simple speech, mechanical to them but to her so full of deep -meaning, that several times she was on the point of abandoning -everything and running away from home. In imagination she already -pictured herself by Theodosia's side, dressed in coarse rags, -walking with a staff, a wallet on her back, along the dusty road, -directing her wanderings from one saint's shrine to another, free from -envy, earthly love, or desire, and reaching at last the place where -there is no more sorrow or sighing, but eternal joy and bliss. - -"I shall come to a place and pray there, and before having time to -get used to it or getting to love it, I shall go farther. I will go on -till my legs fail, and I'll lie down and die somewhere, and shall at -last reach that eternal, quiet haven, where there is neither sorrow -nor sighing..." thought Princess Mary. - -But afterwards, when she saw her father and especially little Koko -(Nicholas), her resolve weakened. She wept quietly, and felt that -she was a sinner who loved her father and little nephew more than God. - - - - - -BOOK SEVEN: 1810 --11 - - - - - -CHAPTER I - - -The Bible legend tells us that the absence of labor--idleness--was a -condition of the first man's blessedness before the Fall. Fallen man -has retained a love of idleness, but the curse weighs on the race -not only because we have to seek our bread in the sweat of our -brows, but because our moral nature is such that we cannot be both -idle and at ease. An inner voice tells us we are in the wrong if we -are idle. If man could find a state in which he felt that though -idle he was fulfilling his duty, he would have found one of the -conditions of man's primitive blessedness. And such a state of -obligatory and irreproachable idleness is the lot of a whole class- -the military. The chief attraction of military service has consisted -and will consist in this compulsory and irreproachable idleness. - -Nicholas Rostov experienced this blissful condition to the full -when, after 1807, he continued to serve in the Pavlograd regiment, -in which he already commanded the squadron he had taken over from -Denisov. - -Rostov had become a bluff, good-natured fellow, whom his Moscow -acquaintances would have considered rather bad form, but who was liked -and respected by his comrades, subordinates, and superiors, and was -well contented with his life. Of late, in 1809, he found in letters -from home more frequent complaints from his mother that their -affairs were falling into greater and greater disorder, and that it -was time for him to come back to gladden and comfort his old parents. - -Reading these letters, Nicholas felt a dread of their wanting to -take him away from surroundings in which, protected from all the -entanglements of life, he was living so calmly and quietly. He felt -that sooner or later he would have to re-enter that whirlpool of life, -with its embarrassments and affairs to be straightened out, its -accounts with stewards, quarrels, and intrigues, its ties, society, -and with Sonya's love and his promise to her. It was all dreadfully -difficult and complicated; and he replied to his mother in cold, -formal letters in French, beginning: "My dear Mamma," and ending: -"Your obedient son," which said nothing of when he would return. In -1810 he received letters from his parents, in which they told him of -Natasha's engagement to Bolkonski, and that the wedding would be in -a year's time because the old prince made difficulties. This letter -grieved and mortified Nicholas. In the first place he was sorry that -Natasha, for whom he cared more than for anyone else in the family, -should be lost to the home; and secondly, from his hussar point of -view, he regretted not to have been there to show that fellow -Bolkonski that connection with him was no such great honor after -all, and that if he loved Natasha he might dispense with permission -from his dotard father. For a moment he hesitated whether he should -not apply for leave in order to see Natasha before she was married, -but then came the maneuvers, and considerations about Sonya and -about the confusion of their affairs, and Nicholas again put it off. -But in the spring of that year, he received a letter from his -mother, written without his father's knowledge, and that letter -persuaded him to return. She wrote that if he did not come and take -matters in hand, their whole property would be sold by auction and -they would all have to go begging. The count was so weak, and -trusted Mitenka so much, and was so good-natured, that everybody -took advantage of him and things were going from bad to worse. "For -God's sake, I implore you, come at once if you do not wish to make -me and the whole family wretched," wrote the countess. - -This letter touched Nicholas. He had that common sense of a -matter-of-fact man which showed him what he ought to do. - -The right thing now was, if not to retire from the service, at any -rate to go home on leave. Why he had to go he did not know; but -after his after-dinner nap he gave orders to saddle Mars, an extremely -vicious gray stallion that had not been ridden for a long time, and -when he returned with the horse all in a lather, he informed Lavrushka -(Denisov's servant who had remained with him) and his comrades who -turned up in the evening that he was applying for leave and was -going home. Difficult and strange as it was for him to reflect that he -would go away without having heard from the staff--and this interested -him extremely--whether he was promoted to a captaincy or would receive -the Order of St. Anne for the last maneuvers; strange as it was to -think that he would go away without having sold his three roans to the -Polish Count Golukhovski, who was bargaining for the horses Rostov had -betted he would sell for two thousand rubles; incomprehensible as it -seemed that the ball the hussars were giving in honor of the Polish -Mademoiselle Przazdziecka (out of rivalry to the Uhlans who had -given one in honor of their Polish Mademoiselle Borzozowska) would -take place without him--he knew he must go away from this good, bright -world to somewhere where everything was stupid and confused. A week -later he obtained his leave. His hussar comrades--not only those of -his own regiment, but the whole brigade--gave Rostov a dinner to which -the subscription was fifteen rubles a head, and at which there were -two bands and two choirs of singers. Rostov danced the Trepak with -Major Basov; the tipsy officers tossed, embraced, and dropped -Rostov; the soldiers of the third squadron tossed him too, and shouted -"hurrah!" and then they put him in his sleigh and escorted him as -far as the first post station. - -During the first half of the journey--from Kremenchug to Kiev--all -Rostov's thoughts, as is usual in such cases, were behind him, with -the squadron; but when he had gone more than halfway he began to -forget his three roans and Dozhoyveyko, his quartermaster, and to -wonder anxiously how things would be at Otradnoe and what he would -find there. Thoughts of home grew stronger the nearer he approached -it--far stronger, as though this feeling of his was subject to the law -by which the force of attraction is in inverse proportion to the -square of the distance. At the last post station before Otradnoe he -gave the driver a three-ruble tip, and on arriving he ran -breathlessly, like a boy, up the steps of his home. - -After the rapture of meeting, and after that odd feeling of -unsatisfied expectation--the feeling that "everything is just the -same, so why did I hurry?"--Nicholas began to settle down in his old -home world. His father and mother were much the same, only a little -older. What was new in them was a certain uneasiness and occasional -discord, which there used not to be, and which, as Nicholas soon found -out, was due to the bad state of their affairs. Sonya was nearly -twenty; she had stopped growing prettier and promised nothing more -than she was already, but that was enough. She exhaled happiness and -love from the time Nicholas returned, and the faithful, unalterable -love of this girl had a gladdening effect on him. Petya and Natasha -surprised Nicholas most. Petya was a big handsome boy of thirteen, -merry, witty, and mischievous, with a voice that was already breaking. -As for Natasha, for a long while Nicholas wondered and laughed -whenever he looked at her. - -"You're not the same at all," he said. - -"How? Am I uglier?" - -"On the contrary, but what dignity? A princess!" he whispered to -her. - -"Yes, yes, yes!" cried Natasha, joyfully. - -She told him about her romance with Prince Andrew and of his visit -to Otradnoe and showed him his last letter. - -"Well, are you glad?" Natasha asked. "I am so tranquil and happy -now." - -"Very glad," answered Nicholas. "He is an excellent fellow.... And -are you very much in love?" - -"How shall I put it?" replied Natasha. "I was in love with Boris, -with my teacher, and with Denisov, but this is quite different. I feel -at peace and settled. I know that no better man than he exists, and -I am calm and contented now. Not at all as before." - -Nicholas expressed his disapproval of the postponement of the -marriage for a year; but Natasha attacked her brother with -exasperation, proving to him that it could not be otherwise, and -that it would be a bad thing to enter a family against the father's -will, and that she herself wished it so. - -"You don't at all understand," she said. - -Nicholas was silent and agreed with her. - -Her brother often wondered as he looked at her. She did not seem -at all like a girl in love and parted from her affianced husband. -She was even-tempered and calm and quite as cheerful as of old. This -amazed Nicholas and even made him regard Bolkonski's courtship -skeptically. He could not believe that her fate was sealed, especially -as he had not seen her with Prince Andrew. It always seemed to him -that there was something not quite right about this intended marriage. - -"Why this delay? Why no betrothal?" he thought. Once, when he had -touched on this topic with his mother, he discovered, to his -surprise and somewhat to his satisfaction, that in the depth of her -soul she too had doubts about this marriage. - -"You see he writes," said she, showing her son a letter of Prince -Andrew's, with that latent grudge a mother always has in regard to a -daughter's future married happiness, "he writes that he won't come -before December. What can be keeping him? Illness, probably! His -health is very delicate. Don't tell Natasha. And don't attach -importance to her being so bright: that's because she's living through -the last days of her girlhood, but I know what she is like every -time we receive a letter from him! However, God grant that -everything turns out well!" (She always ended with these words.) "He -is an excellent man!" - - - - - -CHAPTER II - - -After reaching home Nicholas was at first serious and even dull. -He was worried by the impending necessity of interfering in the stupid -business matters for which his mother had called him home. To throw -off this burden as quickly as possible, on the third day after his -arrival he went, angry and scowling and without answering questions as -to where he was going, to Mitenka's lodge and demanded an account of -everything. But what an account of everything might be Nicholas knew -even less than the frightened and bewildered Mitenka. The conversation -and the examination of the accounts with Mitenka did not last long. -The village elder, a peasant delegate, and the village clerk, who were -waiting in the passage, heard with fear and delight first the young -count's voice roaring and snapping and rising louder and louder, and -then words of abuse, dreadful words, ejaculated one after the other. - -"Robber!... Ungrateful wretch!... I'll hack the dog to pieces! I'm -not my father!... Robbing us!..." and so on. - -Then with no less fear and delight they saw how the young count, red -in the face and with bloodshot eyes, dragged Mitenka out by the scruff -of the neck and applied his foot and knee to his behind with great -agility at convenient moments between the words, shouting, "Be off! -Never let me see your face here again, you villain!" - -Mitenka flew headlong down the six steps and ran away into the -shrubbery. (This shrubbery was a well-known haven of refuge for -culprits at Otradnoe. Mitenka himself, returning tipsy from the -town, used to hide there, and many of the residents at Otradnoe, -hiding from Mitenka, knew of its protective qualities.) - -Mitenka's wife and sisters-in-law thrust their heads and -frightened faces out of the door of a room where a bright samovar -was boiling and where the steward's high bedstead stood with its -patchwork quilt. - -The young count paid no heed to them, but, breathing hard, passed by -with resolute strides and went into the house. - -The countess, who heard at once from the maids what had happened -at the lodge, was calmed by the thought that now their affairs would -certainly improve, but on the other hand felt anxious as to the effect -this excitement might have on her son. She went several times to his -door on tiptoe and listened, as he lighted one pipe after another. - -Next day the old count called his son aside and, with an embarrassed -smile, said to him: - -"But you know, my dear boy, it's a pity you got excited! Mitenka has -told me all about it." - -"I knew," thought Nicholas, "that I should never understand anything -in this crazy world." - -"You were angry that he had not entered those 700 rubles. But they -were carried forward--and you did not look at the other page." - -"Papa, he is a blackguard and a thief! I know he is! And what I have -done, I have done; but, if you like, I won't speak to him again." - -"No, my dear boy" (the count, too, felt embarrassed. He knew he -had mismanaged his wife's property and was to blame toward his -children, but he did not know how to remedy it). "No, I beg you to -attend to the business. I am old. I..." - -"No, Papa. Forgive me if I have caused you unpleasantness. I -understand it all less than you do." - -"Devil take all these peasants, and money matters, and carryings -forward from page to page," he thought. "I used to understand what a -'corner' and the stakes at cards meant, but carrying forward to -another page I don't understand at all," said he to himself, and after -that he did not meddle in business affairs. But once the countess -called her son and informed him that she had a promissory note from -Anna Mikhaylovna for two thousand rubles, and asked him what he -thought of doing with it. - -"This," answered Nicholas. "You say it rests with me. Well, I -don't like Anna Mikhaylovna and I don't like Boris, but they were -our friends and poor. Well then, this!" and he tore up the note, and -by so doing caused the old countess to weep tears of joy. After -that, young Rostov took no further part in any business affairs, but -devoted himself with passionate enthusiasm to what was to him a new -pursuit--the chase--for which his father kept a large establishment. - - - - - -CHAPTER III - - -The weather was already growing wintry and morning frosts -congealed an earth saturated by autumn rains. The verdure had -thickened and its bright green stood out sharply against the -brownish strips of winter rye trodden down by the cattle, and -against the pale-yellow stubble of the spring buckwheat. The wooded -ravines and the copses, which at the end of August had still been -green islands amid black fields and stubble, had become golden and -bright-red islands amid the green winter rye. The hares had already -half changed their summer coats, the fox cubs were beginning to -scatter, and the young wolves were bigger than dogs. It was the best -time of the year for the chase. The hounds of that ardent young -sportsman Rostov had not merely reached hard winter condition, but -were so jaded that at a meeting of the huntsmen it was decided to give -them a three days' rest and then, on the sixteenth of September, to go -on a distant expedition, starting from the oak grove where there was -an undisturbed litter of wolf cubs. - -All that day the hounds remained at home. It was frosty and the -air was sharp, but toward evening the sky became overcast and it began -to thaw. On the fifteenth, when young Rostov, in his dressing gown, -looked out of the window, he saw it was an unsurpassable morning for -hunting: it was as if the sky were melting and sinking to the earth -without any wind. The only motion in the air was that of the dripping, -microscopic particles of drizzling mist. The bare twigs in the -garden were hung with transparent drops which fell on the freshly -fallen leaves. The earth in the kitchen garden looked wet and black -and glistened like poppy seed and at a short distance merged into -the dull, moist veil of mist. Nicholas went out into the wet and muddy -porch. There was a smell of decaying leaves and of dog. Milka, a -black-spotted, broad-haunched bitch with prominent black eyes, got -up on seeing her master, stretched her hind legs, lay down like a -hare, and then suddenly jumped up and licked him right on his nose and -mustache. Another borzoi, a dog, catching sight of his master from the -garden path, arched his back and, rushing headlong toward the porch -with lifted tail, began rubbing himself against his legs. - -"O-hoy!" came at that moment, that inimitable huntsman's call -which unites the deepest bass with the shrillest tenor, and round -the corner came Daniel the head huntsman and head kennelman, a gray, -wrinkled old man with hair cut straight over his forehead, Ukrainian -fashion, a long bent whip in his hand, and that look of independence -and scorn of everything that is only seen in huntsmen. He doffed his -Circassian cap to his master and looked at him scornfully. This -scorn was not offensive to his master. Nicholas knew that this Daniel, -disdainful of everybody and who considered himself above them, was all -the same his serf and huntsman. - -"Daniel!" Nicholas said timidly, conscious at the sight of the -weather, the hounds, and the huntsman that he was being carried away -by that irresistible passion for sport which makes a man forget all -his previous resolutions, as a lover forgets in the presence of his -mistress. - -"What orders, your excellency?" said the huntsman in his deep -bass, deep as a proto-deacon's and hoarse with hallooing--and two -flashing black eyes gazed from under his brows at his master, who -was silent. "Can you resist it?" those eyes seemed to be asking. - -"It's a good day, eh? For a hunt and a gallop, eh?" asked -Nicholas, scratching Milka behind the ears. - -Daniel did not answer, but winked instead. - -"I sent Uvarka at dawn to listen," his bass boomed out after a -minute's pause. "He says she's moved them into the Otradnoe enclosure. -They were howling there." (This meant that the she-wolf, about whom -they both knew, had moved with her cubs to the Otradnoe copse, a small -place a mile and a half from the house.) - -"We ought to go, don't you think so?" said Nicholas. "Come to me -with Uvarka." - -"As you please." - -"Then put off feeding them." - -"Yes, sir." - -Five minutes later Daniel and Uvarka were standing in Nicholas' -big study. Though Daniel was not a big man, to see him in a room was -like seeing a horse or a bear on the floor among the furniture and -surroundings of human life. Daniel himself felt this, and as usual -stood just inside the door, trying to speak softly and not move, for -fear of breaking something in the master's apartment, and he -hastened to say all that was necessary so as to get from under that -ceiling, out into the open under the sky once more. - -Having finished his inquiries and extorted from Daniel an opinion -that the hounds were fit (Daniel himself wished to go hunting), -Nicholas ordered the horses to be saddled. But just as Daniel was -about to go Natasha came in with rapid steps, not having done up her -hair or finished dressing and with her old nurse's big shawl wrapped -round her. Petya ran in at the same time. - -"You are going?" asked Natasha. "I knew you would! Sonya said you -wouldn't go, but I knew that today is the sort of day when you -couldn't help going." - -"Yes, we are going," replied Nicholas reluctantly, for today, as -he intended to hunt seriously, he did not want to take Natasha and -Petya. "We are going, but only wolf hunting: it would be dull for -you." - -"You know it is my greatest pleasure," said Natasha. "It's not fair; -you are going by yourself, are having the horses saddled and said -nothing to us about it." - -"'No barrier bars a Russian's path'--we'll go!" shouted Petya. - -"But you can't. Mamma said you mustn't," said Nicholas to Natasha. - -"Yes, I'll go. I shall certainly go," said Natasha decisively. -"Daniel, tell them to saddle for us, and Michael must come with my -dogs," she added to the huntsman. - -It seemed to Daniel irksome and improper to be in a room at all, but -to have anything to do with a young lady seemed to him impossible. -He cast down his eyes and hurried out as if it were none of his -business, careful as he went not to inflict any accidental injury on -the young lady. - - - - - -CHAPTER IV - - -The old count, who had always kept up an enormous hunting -establishment but had now handed it all completely over to his son's -care, being in very good spirits on this fifteenth of September, -prepared to go out with the others. - -In an hour's time the whole hunting party was at the porch. -Nicholas, with a stern and serious air which showed that now was no -time for attending to trifles, went past Natasha and Petya who were -trying to tell him something. He had a look at all the details of -the hunt, sent a pack of hounds and huntsmen on ahead to find the -quarry, mounted his chestnut Donets, and whistling to his own leash of -borzois, set off across the threshing ground to a field leading to the -Otradnoe wood. The old count's horse, a sorrel gelding called -Viflyanka, was led by the groom in attendance on him, while the -count himself was to drive in a small trap straight to a spot reserved -for him. - -They were taking fifty-four hounds, with six hunt attendants and -whippers-in. Besides the family, there were eight borzoi kennelmen and -more than forty borzois, so that, with the borzois on the leash -belonging to members of the family, there were about a hundred and -thirty dogs and twenty horsemen. - -Each dog knew its master and its call. Each man in the hunt knew his -business, his place, what he had to do. As soon as they had passed the -fence they all spread out evenly and quietly, without noise or talk, -along the road and field leading to the Otradnoe covert. - -The horses stepped over the field as over a thick carpet, now and -then splashing into puddles as they crossed a road. The misty sky -still seemed to descend evenly and imperceptibly toward the earth, the -air was still, warm, and silent. Occasionally the whistle of a -huntsman, the snort of a horse, the crack of a whip, or the whine of a -straggling hound could be heard. - -When they had gone a little less than a mile, five more riders -with dogs appeared out of the mist, approaching the Rostovs. In -front rode a fresh-looking, handsome old man with a large gray -mustache. - -"Good morning, Uncle!" said Nicholas, when the old man drew near. - -"That's it. Come on!... I was sure of it," began "Uncle." (He was -a distant relative of the Rostovs', a man of small means, and their -neighbor.) "I knew you wouldn't be able to resist it and it's a good -thing you're going. That's it! Come on! (This was "Uncle's" favorite -expression.) "Take the covert at once, for my Girchik says the Ilagins -are at Korniki with their hounds. That's it. Come on!... They'll -take the cubs from under your very nose." - -"That's where I'm going. Shall we join up our packs?" asked -Nicholas. - -The hounds were joined into one pack, and "Uncle" and Nicholas -rode on side by side. Natasha, muffled up in shawls which did not hide -her eager face and shining eyes, galloped up to them. She was followed -by Petya who always kept close to her, by Michael, a huntsman, and -by a groom appointed to look after her. Petya, who was laughing, -whipped and pulled at his horse. Natasha sat easily and confidently on -her black Arabchik and reined him in without effort with a firm hand. - -"Uncle" looked round disapprovingly at Petya and Natasha. He did not -like to combine frivolity with the serious business of hunting. - -"Good morning, Uncle! We are going too!" shouted Petya. - -"Good morning, good morning! But don't go overriding the hounds," -said "Uncle" sternly. - -"Nicholas, what a fine dog Trunila is! He knew me," said Natasha, -referring to her favorite hound. - -"In the first place, Trunila is not a 'dog,' but a harrier," thought -Nicholas, and looked sternly at his sister, trying to make her feel -the distance that ought to separate them at that moment. Natasha -understood it. - -"You mustn't think we'll be in anyone's way, Uncle," she said. -"We'll go to our places and won't budge." - -"A good thing too, little countess," said "Uncle," "only mind you -don't fall off your horse," he added, "because--that's it, come on!- -you've nothing to hold on to." - -The oasis of the Otradnoe covert came in sight a few hundred yards -off, the huntsmen were already nearing it. Rostov, having finally -settled with "Uncle" where they should set on the hounds, and having -shown Natasha where she was to stand--a spot where nothing could -possibly run out--went round above the ravine. - -"Well, nephew, you're going for a big wolf," said "Uncle." "Mind and -don't let her slip!" - -"That's as may happen," answered Rostov. "Karay, here!" he -shouted, answering "Uncle's" remark by this call to his borzoi. -Karay was a shaggy old dog with a hanging jowl, famous for having -tackled a big wolf unaided. They all took up their places. - -The old count, knowing his son's ardor in the hunt, hurried so as -not to be late, and the huntsmen had not yet reached their places when -Count Ilya Rostov, cheerful, flushed, and with quivering cheeks, drove -up with his black horses over the winter rye to the place reserved for -him, where a wolf might come out. Having straightened his coat and -fastened on his hunting knives and horn, he mounted his good, sleek, -well-fed, and comfortable horse, Viflyanka, which was turning gray, -like himself. His horses and trap were sent home. Count Ilya Rostov, -though not at heart a keen sportsman, knew the rules of the hunt well, -and rode to the bushy edge of the road where he was to stand, arranged -his reins, settled himself in the saddle, and, feeling that he was -ready, looked about with a smile. - -Beside him was Simon Chekmar, his personal attendant, an old -horseman now somewhat stiff in the saddle. Chekmar held in leash three -formidable wolfhounds, who had, however, grown fat like their master -and his horse. Two wise old dogs lay down unleashed. Some hundred -paces farther along the edge of the wood stood Mitka, the count's -other groom, a daring horseman and keen rider to hounds. Before the -hunt, by old custom, the count had drunk a silver cupful of mulled -brandy, taken a snack, and washed it down with half a bottle of his -favorite Bordeaux. - -He was somewhat flushed with the wine and the drive. His eyes were -rather moist and glittered more than usual, and as he sat in his -saddle, wrapped up in his fur coat, he looked like a child taken out -for an outing. - -The thin, hollow-cheeked Chekmar, having got everything ready, -kept glancing at his master with whom he had lived on the best of -terms for thirty years, and understanding the mood he was in -expected a pleasant chat. A third person rode up circumspectly through -the wood (it was plain that he had had a lesson) and stopped behind -the count. This person was a gray-bearded old man in a woman's -cloak, with a tall peaked cap on his head. He was the buffoon, who -went by a woman's name, Nastasya Ivanovna. - -"Well, Nastasya Ivanovna!" whispered the count, winking at him. -"If you scare away the beast, Daniel'll give it you!" - -"I know a thing or two myself!" said Nastasya Ivanovna. - -"Hush!" whispered the count and turned to Simon. "Have you seen -the young countess?" he asked. "Where is she?" - -"With young Count Peter, by the Zharov rank grass," answered -Simon, smiling. "Though she's a lady, she's very fond of hunting." - -"And you're surprised at the way she rides, Simon, eh?" said the -count. "She's as good as many a man!" - -"Of course! It's marvelous. So bold, so easy!" - -"And Nicholas? Where is he? By the Lyadov upland, isn't he?" - -"Yes, sir. He knows where to stand. He understands the matter so -well that Daniel and I are often quite astounded," said Simon, well -knowing what would please his master. - -"Rides well, eh? And how well he looks on his horse, eh?" - -"A perfect picture! How he chased a fox out of the rank grass by the -Zavarzinsk thicket the other day! Leaped a fearful place; what a sight -when they rushed from the covert... the horse worth a thousand -rubles and the rider beyond all price! Yes, one would have to search -far to find another as smart." - -"To search far..." repeated the count, evidently sorry Simon had not -said more. "To search far," he said, turning back the skirt of his -coat to get at his snuffbox. - -"The other day when he came out from Mass in full uniform, Michael -Sidorych..." Simon did not finish, for on the still air he had -distinctly caught the music of the hunt with only two or three -hounds giving tongue. He bent down his head and listened, shaking a -warning finger at his master. "They are on the scent of the cubs..." -he whispered, "straight to the Lyadov uplands." - -The count, forgetting to smooth out the smile on his face, looked -into the distance straight before him, down the narrow open space, -holding the snuffbox in his hand but not taking any. After the cry -of the hounds came the deep tones of the wolf call from Daniel's -hunting horn; the pack joined the first three hounds and they could be -heard in full cry, with that peculiar lift in the note that -indicates that they are after a wolf. The whippers-in no longer set on -the hounds, but changed to the cry of ulyulyu, and above the others -rose Daniel's voice, now a deep bass, now piercingly shrill. His voice -seemed to fill the whole wood and carried far beyond out into the open -field. - -After listening a few moments in silence, the count and his -attendant convinced themselves that the hounds had separated into -two packs: the sound of the larger pack, eagerly giving tongue, -began to die away in the distance, the other pack rushed by the wood -past the count, and it was with this that Daniel's voice was heard -calling ulyulyu. The sounds of both packs mingled and broke apart -again, but both were becoming more distant. - -Simon sighed and stooped to straighten the leash a young borzoi -had entangled; the count too sighed and, noticing the snuffbox in -his hand, opened it and took a pinch. "Back!" cried Simon to a -borzoi that was pushing forward out of the wood. The count started and -dropped the snuffbox. Nastasya Ivanovna dismounted to pick it up. -The count and Simon were looking at him. - -Then, unexpectedly, as often happens, the sound of the hunt suddenly -approached, as if the hounds in full cry and Daniel ulyulyuing were -just in front of them. - -The count turned and saw on his right Mitka staring at him with eyes -starting out of his head, raising his cap and pointing before him to -the other side. - -"Look out!" he shouted, in a voice plainly showing that he had -long fretted to utter that word, and letting the borzois slip he -galloped toward the count. - -The count and Simon galloped out of the wood and saw on their left a -wolf which, softly swaying from side to side, was coming at a quiet -lope farther to the left to the very place where they were standing. -The angry borzois whined and getting free of the leash rushed past the -horses' feet at the wolf. - -The wolf paused, turned its heavy forehead toward the dogs -awkwardly, like a man suffering from the quinsy, and, still slightly -swaying from side to side, gave a couple of leaps and with a swish -of its tail disappeared into the skirt of the wood. At the same -instant, with a cry like a wail, first one hound, then another, and -then another, sprang helter-skelter from the wood opposite and the -whole pack rushed across the field toward the very spot where the wolf -had disappeared. The hazel bushes parted behind the hounds and -Daniel's chestnut horse appeared, dark with sweat. On its long back -sat Daniel, hunched forward, capless, his disheveled gray hair hanging -over his flushed, perspiring face. - -"Ulyulyulyu! ulyulyu!..." he cried. When he caught sight of the -count his eyes flashed lightning. - -"Blast you!" he shouted, holding up his whip threateningly at the -count. - -"You've let the wolf go!... What sportsmen!" and as if scorning to -say more to the frightened and shamefaced count, he lashed the heaving -flanks of his sweating chestnut gelding with all the anger the count -had aroused and flew off after the hounds. The count, like a -punished schoolboy, looked round, trying by a smile to win Simon's -sympathy for his plight. But Simon was no longer there. He was -galloping round by the bushes while the field was coming up on both -sides, all trying to head the wolf, but it vanished into the wood -before they could do so. - - - - - -CHAPTER V - - -Nicholas Rostov meanwhile remained at his post, waiting for the -wolf. By the way the hunt approached and receded, by the cries of -the dogs whose notes were familiar to him, by the way the voices of -the huntsmen approached, receded, and rose, he realized what was -happening at the copse. He knew that young and old wolves were -there, that the hounds had separated into two packs, that somewhere -a wolf was being chased, and that something had gone wrong. He -expected the wolf to come his way any moment. He made thousands of -different conjectures as to where and from what side the beast would -come and how he would set upon it. Hope alternated with despair. -Several times he addressed a prayer to God that the wolf should come -his way. He prayed with that passionate and shame-faced feeling with -which men pray at moments of great excitement arising from trivial -causes. "What would it be to Thee to do this for me?" he said to -God. "I know Thou art great, and that it is a sin to ask this of Thee, -but for God's sake do let the old wolf come my way and let Karay -spring at it--in sight of 'Uncle' who is watching from over there--and -seize it by the throat in a death grip!" A thousand times during -that half-hour Rostov cast eager and restless glances over the edge of -the wood, with the two scraggy oaks rising above the aspen undergrowth -and the gully with its water-worn side and "Uncle's" cap just -visible above the bush on his right. - -"No, I shan't have such luck," thought Rostov, "yet what wouldn't it -be worth! It is not to be! Everywhere, at cards and in war, I am -always unlucky." Memories of Austerlitz and of Dolokhov flashed -rapidly and clearly through his mind. "Only once in my life to get -an old wolf, I want only that!" thought he, straining eyes and ears -and looking to the left and then to the right and listening to the -slightest variation of note in the cries of the dogs. - -Again he looked to the right and saw something running toward him -across the deserted field. "No, it can't be!" thought Rostov, taking a -deep breath, as a man does at the coming of something long hoped -for. The height of happiness was reached--and so simply, without -warning, or noise, or display, that Rostov could not believe his -eyes and remained in doubt for over a second. The wolf ran forward and -jumped heavily over a gully that lay in her path. She was an old -animal with a gray back and big reddish belly. She ran without -hurry, evidently feeling sure that no one saw her. Rostov, holding his -breath, looked round at the borzois. They stood or lay not seeing -the wolf or understanding the situation. Old Karay had turned his head -and was angrily searching for fleas, baring his yellow teeth and -snapping at his hind legs. - -"Ulyulyulyu!" whispered Rostov, pouting his lips. The borzois jumped -up, jerking the rings of the leashes and pricking their ears. Karay -finished scratching his hindquarters and, cocking his ears, got up -with quivering tail from which tufts of matted hair hung down. - -"Shall I loose them or not?" Nicholas asked himself as the wolf -approached him coming from the copse. Suddenly the wolf's whole -physiognomy changed: she shuddered, seeing what she had probably never -seen before--human eyes fixed upon her--and turning her head a -little toward Rostov, she paused. - -"Back or forward? Eh, no matter, forward..." the wolf seemed to -say to herself, and she moved forward without again looking round -and with a quiet, long, easy yet resolute lope. - -"Ulyulyu!" cried Nicholas, in a voice not his own, and of its own -accord his good horse darted headlong downhill, leaping over gullies -to head off the wolf, and the borzois passed it, running faster still. -Nicholas did not hear his own cry nor feel that he was galloping, -nor see the borzois, nor the ground over which he went: he saw only -the wolf, who, increasing her speed, bounded on in the same -direction along the hollow. The first to come into view was Milka, -with her black markings and powerful quarters, gaining upon the -wolf. Nearer and nearer... now she was ahead of it; but the wolf -turned its head to face her, and instead of putting on speed as she -usually did Milka suddenly raised her tail and stiffened her forelegs. - -"Ulyulyulyulyu!" shouted Nicholas. - -The reddish Lyubim rushed forward from behind Milka, sprang -impetuously at the wolf, and seized it by its hindquarters, but -immediately jumped aside in terror. The wolf crouched, gnashed her -teeth, and again rose and bounded forward, followed at the distance of -a couple of feet by all the borzois, who did not get any closer to -her. - -"She'll get away! No, it's impossible!" thought Nicholas, still -shouting with a hoarse voice. - -"Karay, ulyulyu!..." he shouted, looking round for the old borzoi -who was now his only hope. Karay, with all the strength age had left -him, stretched himself to the utmost and, watching the wolf, -galloped heavily aside to intercept it. But the quickness of the -wolf's lope and the borzoi's slower pace made it plain that Karay -had miscalculated. Nicholas could already see not far in front of -him the wood where the wolf would certainly escape should she reach -it. But, coming toward him, he saw hounds and a huntsman galloping -almost straight at the wolf. There was still hope. A long, yellowish - -young borzoi, one Nicholas did not know, from another leash, rushed -impetuously at the wolf from in front and almost knocked her over. But -the wolf jumped up more quickly than anyone could have expected and, -gnashing her teeth, flew at the yellowish borzoi, which, with a -piercing yelp, fell with its head on the ground, bleeding from a -gash in its side. - -"Karay? Old fellow!..." wailed Nicholas. - -Thanks to the delay caused by this crossing of the wolf's path, -the old dog with its felted hair hanging from its thigh was within -five paces of it. As if aware of her danger, the wolf turned her -eyes on Karay, tucked her tail yet further between her legs, and -increased her speed. But here Nicholas only saw that something -happened to Karay--the borzoi was suddenly on the wolf, and they -rolled together down into a gully just in front of them. - -That instant, when Nicholas saw the wolf struggling in the gully -with the dogs, while from under them could be seen her gray hair and -outstretched hind leg and her frightened choking head, with her ears -laid back (Karay was pinning her by the throat), was the happiest -moment of his life. With his hand on his saddlebow, he was ready to -dismount and stab the wolf, when she suddenly thrust her head up -from among that mass of dogs, and then her forepaws were on the edge -of the gully. She clicked her teeth (Karay no longer had her by the -throat), leaped with a movement of her hind legs out of the gully, and -having disengaged herself from the dogs, with tail tucked in again, -went forward. Karay, his hair bristling, and probably bruised or -wounded, climbed with difficulty out of the gully. - -"Oh my God! Why?" Nicholas cried in despair. - -"Uncle's" huntsman was galloping from the other side across the -wolf's path and his borzois once more stopped the animal's advance. -She was again hemmed in. - -Nicholas and his attendant, with "Uncle" and his huntsman, were -all riding round the wolf, crying "ulyulyu!" shouting and preparing to -dismount each moment that the wolf crouched back, and starting forward -again every time she shook herself and moved toward the wood where she -would be safe. - -Already, at the beginning of this chase, Daniel, hearing the -ulyulyuing, had rushed out from the wood. He saw Karay seize the wolf, -and checked his horse, supposing the affair to be over. But when he -saw that the horsemen did not dismount and that the wolf shook herself -and ran for safety, Daniel set his chestnut galloping, not at the wolf -but straight toward the wood, just as Karay had run to cut the -animal off. As a result of this, he galloped up to the wolf just -when she had been stopped a second time by "Uncle's" borzois. - -Daniel galloped up silently, holding a naked dagger in his left hand -and thrashing the laboring sides of his chestnut horse with his whip -as if it were a flail. - -Nicholas neither saw nor heard Daniel until the chestnut, -breathing heavily, panted past him, and he heard the fall of a body -and saw Daniel lying on the wolf's back among the dogs, trying to -seize her by the ears. It was evident to the dogs, the hunters, and to -the wolf herself that all was now over. The terrified wolf pressed -back her ears and tried to rise, but the borzois stuck to her. -Daniel rose a little, took a step, and with his whole weight, as if -lying down to rest, fell on the wolf, seizing her by the ears. -Nicholas was about to stab her, but Daniel whispered, "Don't! We'll -gag her!" and, changing his position, set his foot on the wolf's neck. -A stick was thrust between her jaws and she was fastened with a leash, -as if bridled, her legs were bound together, and Daniel rolled her -over once or twice from side to side. - -With happy, exhausted faces, they laid the old wolf, alive, on a -shying and snorting horse and, accompanied by the dogs yelping at her, -took her to the place where they were all to meet. The hounds had -killed two of the cubs and the borzois three. The huntsmen assembled -with their booty and their stories, and all came to look at the -wolf, which, with her broad-browed head hanging down and the bitten -stick between her jaws, gazed with great glassy eyes at this crowd -of dogs and men surrounding her. When she was touched, she jerked -her bound legs and looked wildly yet simply at everybody. Old Count -Rostov also rode up and touched the wolf. - -"Oh, what a formidable one!" said he. "A formidable one, eh?" he -asked Daniel, who was standing near. - -"Yes, your excellency," answered Daniel, quickly doffing his cap. - -The count remembered the wolf he had let slip and his encounter with -Daniel. - -"Ah, but you are a crusty fellow, friend!" said the count. - -For sole reply Daniel gave him a shy, childlike, meek, and amiable -smile. - - - - - -CHAPTER VI - - -The old count went home, and Natasha and Petya promised to return -very soon, but as it was still early the hunt went farther. At -midday they put the hounds into a ravine thickly overgrown with -young trees. Nicholas standing in a fallow field could see all his -whips. - -Facing him lay a field of winter rye, there his own huntsman stood -alone in a hollow behind a hazel bush. The hounds had scarcely been -loosed before Nicholas heard one he knew, Voltorn, giving tongue at -intervals; other hounds joined in, now pausing and now again giving -tongue. A moment later he heard a cry from the wooded ravine that a -fox had been found, and the whole pack, joining together, rushed along -the ravine toward the ryefield and away from Nicholas. - -He saw the whips in their red caps galloping along the edge of the -ravine, he even saw the hounds, and was expecting a fox to show itself -at any moment on the ryefield opposite. - -The huntsman standing in the hollow moved and loosed his borzois, -and Nicholas saw a queer, short-legged red fox with a fine brush going -hard across the field. The borzois bore down on it.... Now they drew -close to the fox which began to dodge between the field in sharper and -sharper curves, trailing its brush, when suddenly a strange white -borzoi dashed in followed by a black one, and everything was in -confusion; the borzois formed a star-shaped figure, scarcely swaying -their bodies and with tails turned away from the center of the -group. Two huntsmen galloped up to the dogs; one in a red cap, the -other, a stranger, in a green coat. - -"What's this?" thought Nicholas. "Where's that huntsman from? He -is not 'Uncle's' man." - -The huntsmen got the fox, but stayed there a long time without -strapping it to the saddle. Their horses, bridled and with high -saddles, stood near them and there too the dogs were lying. The -huntsmen waved their arms and did something to the fox. Then from that -spot came the sound of a horn, with the signal agreed on in case of -a fight. - -"That's Ilagin's huntsman having a row with our Ivan," said -Nicholas' groom. - -Nicholas sent the man to call Natasha and Petya to him, and rode -at a footpace to the place where the whips were getting the hounds -together. Several of the field galloped to the spot where the fight -was going on. - -Nicholas dismounted, and with Natasha and Petya, who had ridden -up, stopped near the hounds, waiting to see how the matter would -end. Out of the bushes came the huntsman who had been fighting and -rode toward his young master, with the fox tied to his crupper. -While still at a distance he took off his cap and tried to speak -respectfully, but he was pale and breathless and his face was angry. -One of his eyes was black, but he probably was not even aware of it. - -"What has happened?" asked Nicholas. - -"A likely thing, killing a fox our dogs had hunted! And it was my -gray bitch that caught it! Go to law, indeed!... He snatches at the -fox! I gave him one with the fox. Here it is on my saddle! Do you want -a taste of this?..." said the huntsman, pointing to his dagger and -probably imagining himself still speaking to his foe. - -Nicholas, not stopping to talk to the man, asked his sister and -Petya to wait for him and rode to the spot where the enemy's, -Ilagin's, hunting party was. - -The victorious huntsman rode off to join the field, and there, -surrounded by inquiring sympathizers, recounted his exploits. - -The facts were that Ilagin, with whom the Rostovs had a quarrel -and were at law, hunted over places that belonged by custom to the -Rostovs, and had now, as if purposely, sent his men to the very -woods the Rostovs were hunting and let his man snatch a fox their dogs -had chased. - -Nicholas, though he had never seen Ilagin, with his usual absence of -moderation in judgment, hated him cordially from reports of his -arbitrariness and violence, and regarded him as his bitterest foe. -He rode in angry agitation toward him, firmly grasping his whip and -fully prepared to take the most resolute and desperate steps to punish -his enemy. - -Hardly had he passed an angle of the wood before a stout gentleman -in a beaver cap came riding toward him on a handsome raven-black -horse, accompanied by two hunt servants. - -Instead of an enemy, Nicholas found in Ilagin a stately and -courteous gentleman who was particularly anxious to make the young -count's acquaintance. Having ridden up to Nicholas, Ilagin raised -his beaver cap and said he much regretted what had occurred and -would have the man punished who had allowed himself to seize a fox -hunted by someone else's borzois. He hoped to become better acquainted -with the count and invited him to draw his covert. - -Natasha, afraid that her brother would do something dreadful, had -followed him in some excitement. Seeing the enemies exchanging -friendly greetings, she rode up to them. Ilagin lifted his beaver -cap still higher to Natasha and said, with a pleasant smile, that -the young countess resembled Diana in her passion for the chase as -well as in her beauty, of which he had heard much. - -To expiate his huntsman's offense, Ilagin pressed the Rostovs to -come to an upland of his about a mile away which he usually kept for -himself and which, he said, swarmed with hares. Nicholas agreed, and -the hunt, now doubled, moved on. - -The way to Iligin's upland was across the fields. The hunt -servants fell into line. The masters rode together. "Uncle," Rostov, -and Ilagin kept stealthily glancing at one another's dogs, trying -not to be observed by their companions and searching uneasily for -rivals to their own borzois. - -Rostov was particularly struck by the beauty of a small, -pure-bred, red-spotted bitch on Ilagin's leash, slender but with -muscles like steel, a delicate muzzle, and prominent black eyes. He -had heard of the swiftness of Ilagin's borzois, and in that -beautiful bitch saw a rival to his own Milka. - -In the middle of a sober conversation begun by Ilagin about the -year's harvest, Nicholas pointed to the red-spotted bitch. - -"A fine little bitch, that!" said he in a careless tone. "Is she -swift?" - -"That one? Yes, she's a good dog, gets what she's after," answered -Ilagin indifferently, of the red-spotted bitch Erza, for which, a year -before, he had given a neighbor three families of house serfs. "So -in your parts, too, the harvest is nothing to boast of, Count?" he -went on, continuing the conversation they had begun. And considering -it polite to return the young count's compliment, Ilagin looked at his -borzois and picked out Milka who attracted his attention by her -breadth. "That black-spotted one of yours is fine--well shaped!" -said he. - -"Yes, she's fast enough," replied Nicholas, and thought: "If only -a full-grown hare would cross the field now I'd show you what sort -of borzoi she is," and turning to his groom, he said he would give a -ruble to anyone who found a hare. - -"I don't understand," continued Ilagin, "how some sportsmen can be -so jealous about game and dogs. For myself, I can tell you, Count, I -enjoy riding in company such as this... what could be better?" (he -again raised his cap to Natasha) "but as for counting skins and what -one takes, I don't care about that." - -"Of course not!" - -"Or being upset because someone else's borzoi and not mine catches -something. All I care about is to enjoy seeing the chase, is it not -so, Count? For I consider that..." - -"A-tu!" came the long-drawn cry of one of the borzoi whippers-in, -who had halted. He stood on a knoll in the stubble, holding his whip -aloft, and again repeated his long-drawn cry, "A-tu!" (This call and -the uplifted whip meant that he saw a sitting hare.) - -"Ah, he has found one, I think," said Ilagin carelessly. "Yes, we -must ride up.... Shall we both course it?" answered Nicholas, seeing -in Erza and "Uncle's" red Rugay two rivals he had never yet had a -chance of pitting against his own borzois. "And suppose they outdo -my Milka at once!" he thought as he rode with "Uncle" and Ilagin -toward the hare. - -"A full-grown one?" asked Ilagin as he approached the whip who had -sighted the hare--and not without agitation he looked round and -whistled to Erza. - -"And you, Michael Nikanorovich?" he said, addressing "Uncle." - -The latter was riding with a sullen expression on his face. - -"How can I join in? Why, you've given a village for each of your -borzois! That's it, come on! Yours are worth thousands. Try yours -against one another, you two, and I'll look on!" - -"Rugay, hey, hey!" he shouted. "Rugayushka!" he added, involuntarily -by this diminutive expressing his affection and the hopes he placed on -this red borzoi. Natasha saw and felt the agitation the two elderly -men and her brother were trying to conceal, and was herself excited by -it. - -The huntsman stood halfway up the knoll holding up his whip and -the gentlefolk rode up to him at a footpace; the hounds that were -far off on the horizon turned away from the hare, and the whips, but -not the gentlefolk, also moved away. All were moving slowly and -sedately. - -"How is it pointing?" asked Nicholas, riding a hundred paces -toward the whip who had sighted the hare. - -But before the whip could reply, the hare, scenting the frost coming -next morning, was unable to rest and leaped up. The pack on leash -rushed downhill in full cry after the hare, and from all sides the -borzois that were not on leash darted after the hounds and the hare. -All the hunt, who had been moving slowly, shouted, "Stop!" calling -in the hounds, while the borzoi whips, with a cry of "A-tu!" galloped -across the field setting the borzois on the hare. The tranquil Ilagin, -Nicholas, Natasha, and "Uncle" flew, reckless of where and how they -went, seeing only the borzois and the hare and fearing only to lose -sight even for an instant of the chase. The hare they had started -was a strong and swift one. When he jumped up he did not run at -once, but pricked his ears listening to the shouting and trampling -that resounded from all sides at once. He took a dozen bounds, not -very quickly, letting the borzois gain on him, and, finally having -chosen his direction and realized his danger, laid back his ears and -rushed off headlong. He had been lying in the stubble, but in front of -him was the autumn sowing where the ground was soft. The two borzois -of the huntsman who had sighted him, having been the nearest, were the -first to see and pursue him, but they had not gone far before Ilagin's -red-spotted Erza passed them, got within a length, flew at the hare -with terrible swiftness aiming at his scut, and, thinking she had -seized him, rolled over like a ball. The hare arched his back and -bounded off yet more swiftly. From behind Erza rushed the -broad-haunched, black-spotted Milka and began rapidly gaining on the -hare. - -"Milashka, dear!" rose Nicholas' triumphant cry. It looked as if -Milka would immediately pounce on the hare, but she overtook him and -flew past. The hare had squatted. Again the beautiful Erza reached -him, but when close to the hare's scut paused as if measuring the -distance, so as not to make a mistake this time but seize his hind -leg. - -"Erza, darling!" Ilagin wailed in a voice unlike his own. Erza did -not hearken to his appeal. At the very moment when she would have -seized her prey, the hare moved and darted along the balk between -the winter rye and the stubble. Again Erza and Milka were abreast, -running like a pair of carriage horses, and began to overtake the -hare, but it was easier for the hare to run on the balk and the -borzois did not overtake him so quickly. - -"Rugay, Rugayushka! That's it, come on!" came a third voice just -then, and "Uncle's" red borzoi, straining and curving its back, caught -up with the two foremost borzois, pushed ahead of them regardless of -the terrible strain, put on speed close to the hare, knocked it off -the balk onto the ryefield, again put on speed still more viciously, -sinking to his knees in the muddy field, and all one could see was -how, muddying his back, he rolled over with the hare. A ring of -borzois surrounded him. A moment later everyone had drawn up round the -crowd of dogs. Only the delighted "Uncle" dismounted, and cut off a -pad, shaking the hare for the blood to drip off, and anxiously -glancing round with restless eyes while his arms and legs twitched. He -spoke without himself knowing whom to or what about. "That's it, -come on! That's a dog!... There, it has beaten them all, the -thousand-ruble as well as the one-ruble borzois. That's it, come -on!" said he, panting and looking wrathfully around as if he were -abusing someone, as if they were all his enemies and had insulted him, -and only now had he at last succeeded in justifying himself. "There -are your thousand-ruble ones.... That's it, come on!..." - -"Rugay, here's a pad for you!" he said, throwing down the hare's -muddy pad. "You've deserved it, that's it, come on!" - -"She'd tired herself out, she'd run it down three times by herself," -said Nicholas, also not listening to anyone and regardless of -whether he were heard or not. - -"But what is there in running across it like that?" said Ilagin's -groom. - -"Once she had missed it and turned it away, any mongrel could take -it," Ilagin was saying at the same time, breathless from his gallop -and his excitement. At the same moment Natasha, without drawing -breath, screamed joyously, ecstatically, and so piercingly that it set -everyone's ear tingling. By that shriek she expressed what the -others expressed by all talking at once, and it was so strange that -she must herself have been ashamed of so wild a cry and everyone -else would have been amazed at it at any other time. "Uncle" himself -twisted up the hare, threw it neatly and smartly across his horse's -back as if by that gesture he meant to rebuke everybody, and, with -an air of not wishing to speak to anyone, mounted his bay and rode -off. The others all followed, dispirited and shamefaced, and only much -later were they able to regain their former affectation of -indifference. For a long time they continued to look at red Rugay who, -his arched back spattered with mud and clanking the ring of his leash, -walked along just behind "Uncle's" horse with the serene air of a -conqueror. - -"Well, I am like any other dog as long as it's not a question of -coursing. But when it is, then look out!" his appearance seemed to -Nicholas to be saying. - -When, much later, "Uncle" rode up to Nicholas and began talking to -him, he felt flattered that, after what had happened, "Uncle" -deigned to speak to him. - - - - - -CHAPTER VII - - -Toward evening Ilagin took leave of Nicholas, who found that they -were so far from home that he accepted "Uncle's" offer that the -hunting party should spend the night in his little village of -Mikhaylovna. - -"And if you put up at my house that will be better still. That's it, -come on!" said "Uncle." "You see it's damp weather, and you could -rest, and the little countess could be driven home in a trap." - -"Uncle's" offer was accepted. A huntsman was sent to Otradnoe for -a trap, while Nicholas rode with Natasha and Petya to "Uncle's" house. - -Some five male domestic serfs, big and little, rushed out to the -front porch to meet their master. A score of women serfs, old and -young, as well as children, popped out from the back entrance to -have a look at the hunters who were arriving. The presence of Natasha- -a woman, a lady, and on horseback--raised the curiosity of the serfs -to such a degree that many of them came up to her, stared her in the -face, and unabashed by her presence made remarks about her as though -she were some prodigy on show and not a human being able to hear or -understand what was said about her. - -"Arinka! Look, she sits sideways! There she sits and her skirt -dangles.... See, she's got a little hunting horn!" - -"Goodness gracious! See her knife?..." - -"Isn't she a Tartar!" - -"How is it you didn't go head over heels?" asked the boldest of all, -addressing Natasha directly. - -"Uncle" dismounted at the porch of his little wooden house which -stood in the midst of an overgrown garden and, after a glance at his -retainers, shouted authoritatively that the superfluous ones should -take themselves off and that all necessary preparations should be made -to receive the guests and the visitors. - -The serfs all dispersed. "Uncle" lifted Natasha off her horse and -taking her hand led her up the rickety wooden steps of the porch. -The house, with its bare, unplastered log walls, was not overclean--it -did not seem that those living in it aimed at keeping it spotless--but -neither was it noticeably neglected. In the entry there was a smell of -fresh apples, and wolf and fox skins hung about. - -"Uncle" led the visitors through the anteroom into a small hall with -a folding table and red chairs, then into the drawing room with a -round birchwood table and a sofa, and finally into his private room -where there was a tattered sofa, a worn carpet, and portraits of -Suvorov, of the host's father and mother, and of himself in military -uniform. The study smelt strongly of tobacco and dogs. "Uncle" asked -his visitors to sit down and make themselves at home, and then went -out of the room. Rugay, his back still muddy, came into the room and -lay down on the sofa, cleaning himself with his tongue and teeth. -Leading from the study was a passage in which a partition with -ragged curtains could be seen. From behind this came women's -laughter and whispers. Natasha, Nicholas, and Petya took off their -wraps and sat down on the sofa. Petya, leaning on his elbow, fell -asleep at once. Natasha and Nicholas were silent. Their faces -glowed, they were hungry and very cheerful. They looked at one another -(now that the hunt was over and they were in the house, Nicholas no -longer considered it necessary to show his manly superiority over -his sister), Natasha gave him a wink, and neither refrained long -from bursting into a peal of ringing laughter even before they had a -pretext ready to account for it. - -After a while "Uncle" came in, in a Cossack coat, blue trousers, and -small top boots. And Natasha felt that this costume, the very one -she had regarded with surprise and amusement at Otradnoe, was just the -right thing and not at all worse than a swallow-tail or frock coat. -"Uncle" too was in high spirits and far from being offended by the -brother's and sister's laughter (it could never enter his head that -they might be laughing at his way of life) he himself joined in the -merriment. - -"That's right, young countess, that's it, come on! I never saw -anyone like her!" said he, offering Nicholas a pipe with a long stem -and, with a practiced motion of three fingers, taking down another -that had been cut short. "She's ridden all day like a man, and is as -fresh as ever!" - -Soon after "Uncle's" reappearance the door was opened, evidently -from the sound by a barefooted girl, and a stout, rosy, good-looking -woman of about forty, with a double chin and full red lips, entered -carrying a large loaded tray. With hospitable dignity and cordiality -in her glance and in every motion, she looked at the visitors and, -with a pleasant smile, bowed respectfully. In spite of her exceptional -stoutness, which caused her to protrude her chest and stomach and -throw back her head, this woman (who was "Uncle's" housekeeper) trod -very lightly. She went to the table, set down the tray, and with her -plump white hands deftly took from it the bottles and various hors -d'oeuvres and dishes and arranged them on the table. When she had -finished, she stepped aside and stopped at the door with a smile on -her face. "Here I am. I am she! Now do you understand 'Uncle'?" her -expression said to Rostov. How could one help understanding? Not -only Nicholas, but even Natasha understood the meaning of his puckered -brow and the happy complacent smile that slightly puckered his lips -when Anisya Fedorovna entered. On the tray was a bottle of herb -wine, different kinds of vodka, pickled mushrooms, rye cakes made with -buttermilk, honey in the comb, still mead and sparkling mead, -apples, nuts (raw and roasted), and nut-and-honey sweets. Afterwards -she brought a freshly roasted chicken, ham, preserves made with honey, -and preserves made with sugar. - -All this was the fruit of Anisya Fedorovna's housekeeping, -gathered and prepared by her. The smell and taste of it all had a -smack of Anisya Fedorovna herself: a savor of juiciness, -cleanliness, whiteness, and pleasant smiles. - -"Take this, little Lady-Countess!" she kept saying, as she offered -Natasha first one thing and then another. - -Natasha ate of everything and thought she had never seen or eaten -such buttermilk cakes, such aromatic jam, such honey-and-nut sweets, -or such a chicken anywhere. Anisya Fedorovna left the room. - -After supper, over their cherry brandy, Rostov and "Uncle" talked of -past and future hunts, of Rugay and Ilagin's dogs, while Natasha sat -upright on the sofa and listened with sparkling eyes. She tried -several times to wake Petya that he might eat something, but he only -muttered incoherent words without waking up. Natasha felt so -lighthearted and happy in these novel surroundings that she only -feared the trap would come for her too soon. After a casual pause, -such as often occurs when receiving friends for the first time in -one's own house, "Uncle," answering a thought that was in his -visitors' mind, said: - -"This, you see, is how I am finishing my days... Death will come. -That's it, come on! Nothing will remain. Then why harm anyone?" - -"Uncle's" face was very significant and even handsome as he said -this. Involuntarily Rostov recalled all the good he had heard about -him from his father and the neighbors. Throughout the whole province -"Uncle" had the reputation of being the most honorable and -disinterested of cranks. They called him in to decide family disputes, -chose him as executor, confided secrets to him, elected him to be a -justice and to other posts; but he always persistently refused -public appointments, passing the autumn and spring in the fields on -his bay gelding, sitting at home in winter, and lying in his overgrown -garden in summer. - -"Why don't you enter the service, Uncle?" - -"I did once, but gave it up. I am not fit for it. That's it, come -on! I can't make head or tail of it. That's for you--I haven't -brains enough. Now, hunting is another matter--that's it, come on! -Open the door, there!" he shouted. "Why have you shut it?" - -The door at the end of the passage led to the huntsmen's room, as -they called the room for the hunt servants. - -There was a rapid patter of bare feet, and an unseen hand opened the -door into the huntsmen's room, from which came the clear sounds of a -balalayka on which someone, who was evidently a master of the art, was -playing. Natasha had been listening to those strains for some time and -now went out into the passage to hear better. - -"That's Mitka, my coachman.... I have got him a good balalayka. -I'm fond of it," said "Uncle." - -It was the custom for Mitka to play the balalayka in the -huntsmen's room when "Uncle" returned from the chase. "Uncle" was fond -of such music. - -"How good! Really very good!" said Nicholas with some -unintentional superciliousness, as if ashamed to confess that the -sounds pleased him very much. - -"Very good?" said Natasha reproachfully, noticing her brother's -tone. "Not 'very good' it's simply delicious!" - -Just as "Uncle's" pickled mushrooms, honey, and cherry brandy had -seemed to her the best in the world, so also that song, at that -moment, seemed to her the acme of musical delight. - -"More, please, more!" cried Natasha at the door as soon as the -balalayka ceased. Mitka tuned up afresh, and recommenced thrumming the -balalayka to the air of My Lady, with trills and variations. "Uncle" -sat listening, slightly smiling, with his head on one side. The air -was repeated a hundred times. The balalayka was retuned several -times and the same notes were thrummed again, but the listeners did -not grow weary of it and wished to hear it again and again. Anisya -Fedorovna came in and leaned her portly person against the doorpost. - -"You like listening?" she said to Natasha, with a smile extremely -like "Uncle's." "That's a good player of ours," she added. - -"He doesn't play that part right!" said "Uncle" suddenly, with an -energetic gesture. "Here he ought to burst out--that's it, come on!- -ought to burst out." - -"Do you play then?" asked Natasha. - -"Uncle" did not answer, but smiled. - -"Anisya, go and see if the strings of my guitar are all right. I -haven't touched it for a long time. That's it--come on! I've given -it up." - -Anisya Fedorovna, with her light step, willingly went to fulfill her -errand and brought back the guitar. - -Without looking at anyone, "Uncle" blew the dust off it and, tapping -the case with his bony fingers, tuned the guitar and settled himself -in his armchair. He took the guitar a little above the fingerboard, -arching his left elbow with a somewhat theatrical gesture, and, with a -wink at Anisya Fedorovna, struck a single chord, pure and sonorous, -and then quietly, smoothly, and confidently began playing in very slow -time, not My Lady, but the well-known song: Came a maiden down the -street. The tune, played with precision and in exact time, began to -thrill in the hearts of Nicholas and Natasha, arousing in them the -same kind of sober mirth as radiated from Anisya Fedorovna's whole -being. Anisya Fedorovna flushed, and drawing her kerchief over her -face went laughing out of the room. "Uncle" continued to play -correctly, carefully, with energetic firmness, looking with a -changed and inspired expression at the spot where Anisya Fedorovna had -just stood. Something seemed to be laughing a little on one side of -his face under his gray mustaches, especially as the song grew brisker -and the time quicker and when, here and there, as he ran his fingers -over the strings, something seemed to snap. - -"Lovely, lovely! Go on, Uncle, go on!" shouted Natasha as soon as he -had finished. She jumped up and hugged and kissed him. "Nicholas, -Nicholas!" she said, turning to her brother, as if asking him: "What -is it moves me so?" - -Nicholas too was greatly pleased by "Uncle's" playing, and "Uncle" -played the piece over again. Anisya Fedorovna's smiling face -reappeared in the doorway and behind hers other faces... - - Fetching water clear and sweet, - Stop, dear maiden, I entreat- - -played "Uncle" once more, running his fingers skillfully over the -strings, and then he stopped short and jerked his shoulders. - -"Go on, Uncle dear," Natasha wailed in an imploring tone as if her -life depended on it. - -"Uncle" rose, and it was as if there were two men in him: one of -them smiled seriously at the merry fellow, while the merry fellow -struck a naive and precise attitude preparatory to a folk dance. - -"Now then, niece!" he exclaimed, waving to Natasha the hand that had -just struck a chord. - -Natasha threw off the shawl from her shoulders, ran forward to -face "Uncle," and setting her arms akimbo also made a motion with -her shoulders and struck an attitude. - -Where, how, and when had this young countess, educated by an emigree -French governess, imbibed from the Russian air she breathed that -spirit and obtained that manner which the pas de chale* would, one -would have supposed, long ago have effaced? But the spirit and the -movements were those inimitable and unteachable Russian ones that -"Uncle" had expected of her. As soon as she had struck her pose, and -smiled triumphantly, proudly, and with sly merriment, the fear that -had at first seized Nicholas and the others that she might not do -the right thing was at an end, and they were already admiring her. - - -*The French shawl dance. - - -She did the right thing with such precision, such complete -precision, that Anisya Fedorovna, who had at once handed her the -handkerchief she needed for the dance, had tears in her eyes, though -she laughed as she watched this slim, graceful countess, reared in -silks and velvets and so different from herself, who yet was able to -understand all that was in Anisya and in Anisya's father and mother -and aunt, and in every Russian man and woman. - -"Well, little countess; that's it--come on!" cried "Uncle," with a -joyous laugh, having finished the dance. "Well done, niece! Now a fine -young fellow must be found as husband for you. That's it--come on!" - -"He's chosen already," said Nicholas smiling. - -"Oh?" said "Uncle" in surprise, looking inquiringly at Natasha, -who nodded her head with a happy smile. - -"And such a one!" she said. But as soon as she had said it a new -train of thoughts and feelings arose in her. "What did Nicholas' smile -mean when he said 'chosen already'? Is he glad of it or not? It is -as if he thought my Bolkonski would not approve of or understand our -gaiety. But he would understand it all. Where is he now?" she thought, -and her face suddenly became serious. But this lasted only a second. -"Don't dare to think about it," she said to herself, and sat down -again smilingly beside "Uncle," begging him to play something more. - -"Uncle" played another song and a valse; then after a pause he -cleared his throat and sang his favorite hunting song: - - As 'twas growing dark last night - Fell the snow so soft and light... - - -"Uncle" sang as peasants sing, with full and naive conviction that -the whole meaning of a song lies in the words and that the tune -comes of itself, and that apart from the words there is no tune, which -exists only to give measure to the words. As a result of this the -unconsidered tune, like the song of a bird, was extraordinarily -good. Natasha was in ecstasies over "Uncle's" singing. She resolved to -give up learning the harp and to play only the guitar. She asked -"Uncle" for his guitar and at once found the chords of the song. - -After nine o'clock two traps and three mounted men, who had been -sent to look for them, arrived to fetch Natasha and Petya. The count -and countess did not know where they were and were very anxious, -said one of the men. - -Petya was carried out like a log and laid in the larger of the two -traps. Natasha and Nicholas got into the other. "Uncle" wrapped -Natasha up warmly and took leave of her with quite a new tenderness. -He accompanied them on foot as far as the bridge that could not be -crossed, so that they had to go round by the ford, and he sent -huntsmen to ride in front with lanterns. - -"Good-by, dear niece," his voice called out of the darkness--not the -voice Natasha had known previously, but the one that had sung As 'twas -growing dark last night. - -In the village through which they passed there were red lights and a -cheerful smell of smoke. - -"What a darling Uncle is!" said Natasha, when they had come out onto -the highroad. - -"Yes," returned Nicholas. "You're not cold?" - -"No. I'm quite, quite all right. I feel so comfortable!" answered -Natasha, almost perplexed by her feelings. They remained silent a long -while. The night was dark and damp. They could not see the horses, but -only heard them splashing through the unseen mud. - -What was passing in that receptive childlike soul that so eagerly -caught and assimilated all the diverse impressions of life? How did -they all find place in her? But she was very happy. As they were -nearing home she suddenly struck up the air of As 'twas growing dark -last night--the tune of which she had all the way been trying to get -and had at last caught. - -"Got it?" said Nicholas. - -"What were you thinking about just now, Nicholas?" inquired Natasha. - -They were fond of asking one another that question. - -"I?" said Nicholas, trying to remember. "Well, you see, first I -thought that Rugay, the red hound, was like Uncle, and that if he were -a man he would always keep Uncle near him, if not for his riding, then -for his manner. What a good fellow Uncle is! Don't you think so?... -Well, and you?" - -"I? Wait a bit, wait.... Yes, first I thought that we are driving -along and imagining that we are going home, but that heaven knows -where we are really going in the darkness, and that we shall arrive -and suddenly find that we are not in Otradnoe, but in Fairyland. And -then I thought... No, nothing else." - -"I know, I expect you thought of him," said Nicholas, smiling as -Natasha knew by the sound of his voice. - -"No," said Natasha, though she had in reality been thinking about -Prince Andrew at the same time as of the rest, and of how he would -have liked "Uncle." "And then I was saying to myself all the way, 'How -well Anisya carried herself, how well!'" And Nicholas heard her -spontaneous, happy, ringing laughter. "And do you know," she -suddenly said, "I know that I shall never again be as happy and -tranquil as I am now." - -"Rubbish, nonsense, humbug!" exclaimed Nicholas, and he thought: -"How charming this Natasha of mine is! I have no other friend like her -and never shall have. Why should she marry? We might always drive -about together!" - -"What a darling this Nicholas of mine is!" thought Natasha. - -"Ah, there are still lights in the drawingroom!" she said, -pointing to the windows of the house that gleamed invitingly in the -moist velvety darkness of the night. - - - - - -CHAPTER VIII - - -Count Ilya Rostov had resigned the position of Marshal of the -Nobility because it involved him in too much expense, but still his -affairs did not improve. Natasha and Nicholas often noticed their -parents conferring together anxiously and privately and heard -suggestions of selling the fine ancestral Rostov house and estate near -Moscow. It was not necessary to entertain so freely as when the -count had been Marshal, and life at Otradnoe was quieter than in -former years, but still the enormous house and its lodges were full of -people and more than twenty sat down to table every day. These were -all their own people who had settled down in the house almost as -members of the family, or persons who were, it seemed, obliged to live -in the count's house. Such were Dimmler the musician and his wife, -Vogel the dancing master and his family, Belova, an old maiden lady, -an inmate of the house, and many others such as Petya's tutors, the -girls' former governess, and other people who simply found it -preferable and more advantageous to live in the count's house than -at home. They had not as many visitors as before, but the old habits -of life without which the count and countess could not conceive of -existence remained unchanged. There was still the hunting -establishment which Nicholas had even enlarged, the same fifty -horses and fifteen grooms in the stables, the same expensive -presents and dinner parties to the whole district on name days; -there were still the count's games of whist and boston, at which- -spreading out his cards so that everybody could see them--he let -himself be plundered of hundreds of rubles every day by his neighbors, -who looked upon an opportunity to play a rubber with Count Rostov as a -most profitable source of income. - -The count moved in his affairs as in a huge net, trying not to -believe that he was entangled but becoming more and more so at every -step, and feeling too feeble to break the meshes or to set to work -carefully and patiently to disentangle them. The countess, with her -loving heart, felt that her children were being ruined, that it was -not the count's fault for he could not help being what he was--that -(though he tried to hide it) he himself suffered from the -consciousness of his own and his children's ruin, and she tried to -find means of remedying the position. From her feminine point of -view she could see only one solution, namely, for Nicholas to marry -a rich heiress. She felt this to be their last hope and that if -Nicholas refused the match she had found for him, she would have to -abandon the hope of ever getting matters right. This match was with -Julie Karagina, the daughter of excellent and virtuous parents, a girl -the Rostovs had known from childhood, and who had now become a wealthy -heiress through the death of the last of her brothers. - -The countess had written direct to Julie's mother in Moscow -suggesting a marriage between their children and had received a -favorable answer from her. Karagina had replied that for her part -she was agreeable, and everything depend on her daughter's -inclination. She invited Nicholas to come to Moscow. - -Several times the countess, with tears in her eyes, told her son -that now both her daughters were settled, her only wish was to see him -married. She said she could lie down in her grave peacefully if that -were accomplished. Then she told him that she knew of a splendid -girl and tried to discover what he thought about marriage. - -At other times she praised Julie to him and advised him to go to -Moscow during the holidays to amuse himself. Nicholas guessed what his -mother's remarks were leading to and during one of these conversations -induced her to speak quite frankly. She told him that her only hope of -getting their affairs disentangled now lay in his marrying Julie -Karagina. - -"But, Mamma, suppose I loved a girl who has no fortune, would you -expect me to sacrifice my feelings and my honor for the sake of -money?" he asked his mother, not realizing the cruelty of his question -and only wishing to show his noble-mindedness. - -"No, you have not understood me," said his mother, not knowing how -to justify herself. "You have not understood me, Nikolenka. It is your -happiness I wish for," she added, feeling that she was telling an -untruth and was becoming entangled. She began to cry. - -"Mamma, don't cry! Only tell me that you wish it, and you know I -will give my life, anything, to put you at ease," said Nicholas. "I -would sacrifice anything for you--even my feelings." - -But the countess did not want the question put like that: she did -not want a sacrifice from her son, she herself wished to make a -sacrifice for him. - -"No, you have not understood me, don't let us talk about it," she -replied, wiping away her tears. - -"Maybe I do love a poor girl," said Nicholas to himself. "Am I to -sacrifice my feelings and my honor for money? I wonder how Mamma could -speak so to me. Because Sonya is poor I must not love her," he -thought, "must not respond to her faithful, devoted love? Yet I should -certainly be happier with her than with some doll-like Julie. I can -always sacrifice my feelings for my family's welfare," he said to -himself, "but I can't coerce my feelings. If I love Sonya, that -feeling is for me stronger and higher than all else." - -Nicholas did not go to Moscow, and the countess did not renew the -conversation with him about marriage. She saw with sorrow, and -sometimes with exasperation, symptoms of a growing attachment -between her son and the portionless Sonya. Though she blamed herself -for it, she could not refrain from grumbling at and worrying Sonya, -often pulling her up without reason, addressing her stiffly as "my -dear," and using the formal "you" instead of the intimate "thou" in -speaking to her. The kindhearted countess was the more vexed with -Sonya because that poor, dark-eyed niece of hers was so meek, so kind, -so devotedly grateful to her benefactors, and so faithfully, -unchangingly, and unselfishly in love with Nicholas, that there were -no grounds for finding fault with her. - -Nicholas was spending the last of his leave at home. A fourth letter -had come from Prince Andrew, from Rome, in which he wrote that he -would have been on his way back to Russia long ago had not his wound -unexpectedly reopened in the warm climate, which obliged him to -defer his return till the beginning of the new year. Natasha was still -as much in love with her betrothed, found the same comfort in that -love, and was still as ready to throw herself into all the pleasures -of life as before; but at the end of the fourth month of their -separation she began to have fits of depression which she could not -master. She felt sorry for herself: sorry that she was being wasted -all this time and of no use to anyone--while she felt herself so -capable of loving and being loved. - -Things were not cheerful in the Rostovs' home. - - - - - -CHAPTER IX - - -Christmas came and except for the ceremonial Mass, the solemn and -wearisome Christmas congratulations from neighbors and servants, and -the new dresses everyone put on, there were no special festivities, -though the calm frost of twenty degrees Reaumur, the dazzling sunshine -by day, and the starlight of the winter nights seemed to call for some -special celebration of the season. - -On the third day of Christmas week, after the midday dinner, all the -inmates of the house dispersed to various rooms. It was the dullest -time of the day. Nicholas, who had been visiting some neighbors that -morning, was asleep on the sitting-room sofa. The old count was -resting in his study. Sonya sat in the drawing room at the round -table, copying a design for embroidery. The countess was playing -patience. Nastasya Ivanovna the buffoon sat with a sad face at the -window with two old ladies. Natasha came into the room, went up to -Sonya, glanced at what she was doing, and then went up to her mother -and stood without speaking. - -"Why are you wandering about like an outcast?" asked her mother. -"What do you want?" - -"Him... I want him... now, this minute! I want him!" said Natasha, -with glittering eyes and no sign of a smile. - -The countess lifted her head and looked attentively at her daughter. - -"Don't look at me, Mamma! Don't look; I shall cry directly." - -"Sit down with me a little," said the countess. - -"Mamma, I want him. Why should I be wasted like this, Mamma?" - -Her voice broke, tears gushed from her eyes, and she turned -quickly to hide them and left the room. - -She passed into the sitting room, stood there thinking awhile, and -then went into the maids' room. There an old maidservant was grumbling -at a young girl who stood panting, having just run in through the cold -from the serfs' quarters. - -"Stop playing--there's a time for everything," said the old woman. - -"Let her alone, Kondratevna," said Natasha. "Go, Mavrushka, go." - -Having released Mavrushka, Natasha crossed the dancing hall and went -to the vestibule. There an old footman and two young ones were playing -cards. They broke off and rose as she entered. - -"What can I do with them?" thought Natasha. - -"Oh, Nikita, please go... where can I send him?... Yes, go to the -yard and fetch a fowl, please, a cock, and you, Misha, bring me some -oats." - -"Just a few oats?" said Misha, cheerfully and readily. - -"Go, go quickly," the old man urged him. - -"And you, Theodore, get me a piece of chalk." - -On her way past the butler's pantry she told them to set a -samovar, though it was not at all the time for tea. - -Foka, the butler, was the most ill-tempered person in the house. -Natasha liked to test her power over him. He distrusted the order -and asked whether the samovar was really wanted. - -"Oh dear, what a young lady!" said Foka, pretending to frown at -Natasha. - -No one in the house sent people about or gave them as much trouble -as Natasha did. She could not see people unconcernedly, but had to -send them on some errand. She seemed to be trying whether any of -them would get angry or sulky with her; but the serfs fulfilled no -one's orders so readily as they did hers. "What can I do, where can -I go?" thought she, as she went slowly along the passage. - -"Nastasya Ivanovna, what sort of children shall I have?" she asked -the buffoon, who was coming toward her in a woman's jacket. - -"Why, fleas, crickets, grasshoppers," answered the buffoon. - -"O Lord, O Lord, it's always the same! Oh, where am I to go? What am -I to do with myself?" And tapping with her heels, she ran quickly -upstairs to see Vogel and his wife who lived on the upper story. - -Two governesses were sitting with the Vogels at a table, on which -were plates of raisins, walnuts, and almonds. The governesses were -discussing whether it was cheaper to live in Moscow or Odessa. Natasha -sat down, listened to their talk with a serious and thoughtful air, -and then got up again. - -"The island of Madagascar," she said, "Ma-da-gas-car," she repeated, -articulating each syllable distinctly, and, not replying to Madame -Schoss who asked her what she was saying, she went out of the room. - -Her brother Petya was upstairs too; with the man in attendance on -him he was preparing fireworks to let off that night. - -"Petya! Petya!" she called to him. "Carry me downstairs." - -Petya ran up and offered her his back. She jumped on it, putting her -arms round his neck, and he pranced along with her. - -"No, don't... the island of Madagascar!" she said, and jumping off -his back she went downstairs. - -Having as it were reviewed her kingdom, tested her power, and made -sure that everyone was submissive, but that all the same it was -dull, Natasha betook herself to the ballroom, picked up her guitar, -sat down in a dark corner behind a bookcase, and began to run her -fingers over the strings in the bass, picking out a passage she -recalled from an opera she had heard in Petersburg with Prince Andrew. -What she drew from the guitar would have had no meaning for other -listeners, but in her imagination a whole series of reminiscences -arose from those sounds. She sat behind the bookcase with her eyes -fixed on a streak of light escaping from the pantry door and -listened to herself and pondered. She was in a mood for brooding on -the past. - -Sonya passed to the pantry with a glass in her hand. Natasha glanced -at her and at the crack in the pantry door, and it seemed to her -that she remembered the light failing through that crack once before -and Sonya passing with a glass in her hand. "Yes it was exactly the -same," thought Natasha. - -"Sonya, what is this?" she cried, twanging a thick string. - -"Oh, you are there!" said Sonya with a start, and came near and -listened. "I don't know. A storm?" she ventured timidly, afraid of -being wrong. - -"There! That's just how she started and just how she came up smiling -timidly when all this happened before," thought Natasha, "and in -just the same way I thought there was something lacking in her." - -"No, it's the chorus from The Water-Carrier, listen!" and Natasha -sang the air of the chorus so that Sonya should catch it. "Where -were you going?" she asked. - -"To change the water in this glass. I am just finishing the design." - -"You always find something to do, but I can't," said Natasha. "And -where's Nicholas?" - -"Asleep, I think." - -"Sonya, go and wake him," said Natasha. "Tell him I want him to come -and sing." - -She sat awhile, wondering what the meaning of it all having happened -before could be, and without solving this problem, or at all -regretting not having done so, she again passed in fancy to the time -when she was with him and he was looking at her with a lover's eyes. - -"Oh, if only he would come quicker! I am so afraid it will never be! -And, worst of all, I am growing old--that's the thing! There won't -then be in me what there is now. But perhaps he'll come today, will -come immediately. Perhaps he has come and is sitting in the drawing -room. Perhaps he came yesterday and I have forgotten it." She rose, -put down the guitar, and went to the drawing room. - -All the domestic circle, tutors, governesses, and guests, were -already at the tea table. The servants stood round the table--but -Prince Andrew was not there and life was going on as before. - -"Ah, here she is!" said the old count, when he saw Natasha enter. -"Well, sit down by me." But Natasha stayed by her mother and glanced -round as if looking for something. - -"Mamma!" she muttered, "give him to me, give him, Mamma, quickly, -quickly!" and she again had difficulty in repressing her sobs. - -She sat down at the table and listened to the conversation between -the elders and Nicholas, who had also come to the table. "My God, my -God! The same faces, the same talk, Papa holding his cup and blowing -in the same way!" thought Natasha, feeling with horror a sense of -repulsion rising up in her for the whole household, because they -were always the same. - -After tea, Nicholas, Sonya, and Natasha went to the sitting room, to -their favorite corner where their most intimate talks always began. - - - - - -CHAPTER X - - -"Does it ever happen to you," said Natasha to her brother, when -they settled down in the sitting room, "does it ever happen to you -to feel as if there were nothing more to come--nothing; that -everything good is past? And to feel not exactly dull, but sad?" - -"I should think so!" he replied. "I have felt like that when -everything was all right and everyone was cheerful. The thought has -come into my mind that I was already tired of it all, and that we must -all die. Once in the regiment I had not gone to some merrymaking where -there was music... and suddenly I felt so depressed..." - -"Oh yes, I know, I know, I know!" Natasha interrupted him. "When I -was quite little that used to be so with me. Do you remember when I -was punished once about some plums? You were all dancing, and I sat -sobbing in the schoolroom? I shall never forget it: I felt sad and -sorry for everyone, for myself, and for everyone. And I was -innocent--that was the chief thing," said Natasha. "Do you remember?" - -"I remember," answered Nicholas. "I remember that I came to you -afterwards and wanted to comfort you, but do you know, I felt -ashamed to. We were terribly absurd. I had a funny doll then and -wanted to give it to you. Do you remember?" - -"And do you remember," Natasha asked with a pensive smile, "how -once, long, long ago, when we were quite little, Uncle called us -into the study--that was in the old house--and it was dark--we went in -and suddenly there stood..." - -"A Negro," chimed in Nicholas with a smile of delight. "Of course -I remember. Even now I don't know whether there really was a Negro, or -if we only dreamed it or were told about him." - -"He was gray, you remember, and had white teeth, and stood and -looked at us..." - -"Sonya, do you remember?" asked Nicholas. - -"Yes, yes, I do remember something too," Sonya answered timidly. - -"You know I have asked Papa and Mamma about that Negro," said -Natasha, "and they say there was no Negro at all. But you see, you -remember!" - -"Of course I do, I remember his teeth as if I had just seen them." - -"How strange it is! It's as if it were a dream! I like that." - -"And do you remember how we rolled hard-boiled eggs in the ballroom, -and suddenly two old women began spinning round on the carpet? Was -that real or not? Do you remember what fun it was?" - -"Yes, and you remember how Papa in his blue overcoat fired a gun -in the porch?" - -So they went through their memories, smiling with pleasure: not -the sad memories of old age, but poetic, youthful ones--those -impressions of one's most distant past in which dreams and realities -blend--and they laughed with quiet enjoyment. - -Sonya, as always, did not quite keep pace with them, though they -shared the same reminiscences. - -Much that they remembered had slipped from her mind, and what she -recalled did not arouse the same poetic feeling as they experienced. -She simply enjoyed their pleasure and tried to fit in with it. - -She only really took part when they recalled Sonya's first -arrival. She told them how afraid she had been of Nicholas because -he had on a corded jacket and her nurse had told her that she, too, -would be sewn up with cords. - -"And I remember their telling me that you had been born under a -cabbage," said Natasha, "and I remember that I dared not disbelieve -it then, but knew that it was not true, and I felt so uncomfortable." - -While they were talking a maid thrust her head in at the other -door of the sitting room. - -"They have brought the cock, Miss," she said in a whisper. - -"It isn't wanted, Petya. Tell them to take it away," replied -Natasha. - -In the middle of their talk in the sitting room, Dimmler came in and -went up to the harp that stood there in a corner. He took off its -cloth covering, and the harp gave out a jarring sound. - -"Mr. Dimmler, please play my favorite nocturne by Field," came the -old countess' voice from the drawing room. - -Dimmler struck a chord and, turning to Natasha, Nicholas, and Sonya, -remarked: "How quiet you young people are!" - -"Yes, we're philosophizing," said Natasha, glancing round for a -moment and then continuing the conversation. They were now -discussing dreams. - -Dimmler began to play; Natasha went on tiptoe noiselessly to the -table, took up a candle, carried it out, and returned, seating herself -quietly in her former place. It was dark in the room especially -where they were sitting on the sofa, but through the big windows the -silvery light of the full moon fell on the floor. Dimmler had finished -the piece but still sat softly running his fingers over the strings, -evidently uncertain whether to stop or to play something else. - -"Do you know," said Natasha in a whisper, moving closer to -Nicholas and Sonya, "that when one goes on and on recalling -memories, one at last begins to remember what happened before one -was in the world..." - -"That is metempsychosis," said Sonya, who had always learned well, -and remembered everything. "The Egyptians believed that our souls have -lived in animals, and will go back into animals again." - -"No, I don't believe we ever were in animals," said Natasha, still -in a whisper though the music had ceased. "But I am certain that we -were angels somewhere there, and have been here, and that is why we -remember...." - -"May I join you?" said Dimmler who had come up quietly, and he sat -down by them. - -"If we have been angels, why have we fallen lower?" said Nicholas. -"No, that can't be!" - -"Not lower, who said we were lower?... How do I know what I was -before?" Natasha rejoined with conviction. "The soul is immortal--well -then, if I shall always live I must have lived before, lived for a -whole eternity." - -"Yes, but it is hard for us to imagine eternity," remarked -Dimmler, who had joined the young folk with a mildly condescending -smile but now spoke as quietly and seriously as they. - -"Why is it hard to imagine eternity?" said Natasha. "It is now -today, and it will be tomorrow, and always; and there was yesterday, -and the day before..." - -"Natasha! Now it's your turn. Sing me something," they heard the -countess say. "Why are you sitting there like conspirators?" - -"Mamma, I don't at all want to," replied Natasha, but all the same -she rose. - -None of them, not even the middle-aged Dimmler, wanted to break -off their conversation and quit that corner in the sitting room, but -Natasha got up and Nicholas sat down at the clavichord. Standing as -usual in the middle of the hall and choosing the place where the -resonance was best, Natasha began to sing her mother's favorite song. - -She had said she did not want to sing, but it was long since she had -sung, and long before she again sang, as she did that evening. The -count, from his study where he was talking to Mitenka, heard her -and, like a schoolboy in a hurry to run out to play, blundered in -his talk while giving orders to the steward, and at last stopped, -while Mitenka stood in front of him also listening and smiling. -Nicholas did not take his eyes off his sister and drew breath in -time with her. Sonya, as she listened, thought of the immense -difference there was between herself and her friend, and how -impossible it was for her to be anything like as bewitching as her -cousin. The old countess sat with a blissful yet sad smile and with -tears in her eyes, occasionally shaking her head. She thought of -Natasha and of her own youth, and of how there was something unnatural -and dreadful in this impending marriage of Natasha and Prince Andrew. - -Dimmler, who had seated himself beside the countess, listened with -closed eyes. - -"Ah, Countess," he said at last, "that's a European talent, she -has nothing to learn--what softness, tenderness, and strength...." - -"Ah, how afraid I am for her, how afraid I am!" said the countess, -not realizing to whom she was speaking. Her maternal instinct told her -that Natasha had too much of something, and that because of this she -would not be happy. Before Natasha had finished singing, -fourteen-year-old Petya rushed in delightedly, to say that some -mummers had arrived. - -Natasha stopped abruptly. - -"Idiot!" she screamed at her brother and, running to a chair, -threw herself on it, sobbing so violently that she could not stop -for a long time. - -"It's nothing, Mamma, really it's nothing; only Petya startled -me," she said, trying to smile, but her tears still flowed and sobs -still choked her. - -The mummers (some of the house serfs) dressed up as bears, Turks, -innkeepers, and ladies--frightening and funny--bringing in with them -the cold from outside and a feeling of gaiety, crowded, at first -timidly, into the anteroom, then hiding behind one another they pushed -into the ballroom where, shyly at first and then more and more merrily -and heartily, they started singing, dancing, and playing Christmas -games. The countess, when she had identified them and laughed at their -costumes, went into the drawing room. The count sat in the ballroom, -smiling radiantly and applauding the players. The young people had -disappeared. - -Half an hour later there appeared among the other mummers in the -ballroom an old lady in a hooped skirt--this was Nicholas. A Turkish -girl was Petya. A clown was Dimmler. An hussar was Natasha, and a -Circassian was Sonya with burnt-cork mustache and eyebrows. - -After the condescending surprise, nonrecognition, and praise, from -those who were not themselves dressed up, the young people decided -that their costumes were so good that they ought to be shown -elsewhere. - -Nicholas, who, as the roads were in splendid condition, wanted to -take them all for a drive in his troyka, proposed to take with them -about a dozen of the serf mummers and drive to "Uncle's." - -"No, why disturb the old fellow?" said the countess. "Besides, you -wouldn't have room to turn round there. If you must go, go to the -Melyukovs'." - -Melyukova was a widow, who, with her family and their tutors and -governesses, lived three miles from the Rostovs. - -"That's right, my dear," chimed in the old count, thoroughly -aroused. "I'll dress up at once and go with them. I'll make Pashette -open her eyes." - -But the countess would not agree to his going; he had had a bad -leg all these last days. It was decided that the count must not go, -but that if Louisa Ivanovna (Madame Schoss) would go with them, the -young ladies might go to the Melyukovs', Sonya, generally so timid and -shy, more urgently than anyone begging Louisa Ivanovna not to refuse. - -Sonya's costume was the best of all. Her mustache and eyebrows -were extraordinarily becoming. Everyone told her she looked very -handsome, and she was in a spirited and energetic mood unusual with -her. Some inner voice told her that now or never her fate would be -decided, and in her male attire she seemed quite a different person. -Louisa Ivanovna consented to go, and in half an hour four troyka -sleighs with large and small bells, their runners squeaking and -whistling over the frozen snow, drove up to the porch. - -Natasha was foremost in setting a merry holiday tone, which, passing -from one to another, grew stronger and reached its climax -when they all came out into the frost and got into the sleighs, -talking, calling to one another, laughing, and shouting. - -Two of the troykas were the usual household sleighs, the third was -the old count's with a trotter from the Orlov stud as shaft horse, the -fourth was Nicholas' own with a short shaggy black shaft horse. -Nicholas, in his old lady's dress over which he had belted his -hussar overcoat, stood in the middle of the sleigh, reins in hand. - -It was so light that he could see the moonlight reflected from the -metal harness disks and from the eyes of the horses, who looked -round in alarm at the noisy party under the shadow of the porch roof. - -Natasha, Sonya, Madame Schoss, and two maids got into Nicholas' -sleigh; Dimmler, his wife, and Petya, into the old count's, and the -rest of the mummers seated themselves in the other two sleighs. - -"You go ahead, Zakhar!" shouted Nicholas to his father's coachman, -wishing for a chance to race past him. - -The old count's troyka, with Dimmler and his party, started forward, -squeaking on its runners as though freezing to the snow, its -deep-toned bell clanging. The side horses, pressing against the shafts -of the middle horse, sank in the snow, which was dry and glittered -like sugar, and threw it up. - -Nicholas set off, following the first sleigh; behind him the -others moved noisily, their runners squeaking. At first they drove -at a steady trot along the narrow road. While they drove past the -garden the shadows of the bare trees often fell across the road and -hid the brilliant moonlight, but as soon as they were past the -fence, the snowy plain bathed in moonlight and motionless spread out -before them glittering like diamonds and dappled with bluish -shadows. Bang, bang! went the first sleigh over a cradle hole in the -snow of the road, and each of the other sleighs jolted in the same -way, and rudely breaking the frost-bound stillness, the troykas -began to speed along the road, one after the other. - -"A hare's track, a lot of tracks!" rang out Natasha's voice -through the frost-bound air. - -"How light it is, Nicholas!" came Sonya's voice. - -Nicholas glanced round at Sonya, and bent down to see her face -closer. Quite a new, sweet face with black eyebrows and mustaches -peeped up at him from her sable furs--so close and yet so distant- -in the moonlight. - -"That used to be Sonya," thought he, and looked at her closer and -smiled. - -"What is it, Nicholas?" - -"Nothing," said he and turned again to the horses. - -When they came out onto the beaten highroad--polished by sleigh -runners and cut up by rough-shod hoofs, the marks of which were -visible in the moonlight--the horses began to tug at the reins of -their own accord and increased their pace. The near side horse, -arching his head and breaking into a short canter, tugged at his -traces. The shaft horse swayed from side to side, moving his ears as -if asking: "Isn't it time to begin now?" In front, already far ahead -the deep bell of the sleigh ringing farther and farther off, the black -horses driven by Zakhar could be clearly seen against the white -snow. From that sleigh one could hear the shouts, laughter, and voices -of the mummers. - -"Gee up, my darlings!" shouted Nicholas, pulling the reins to one -side and flourishing the whip. - -It was only by the keener wind that met them and the jerks given -by the side horses who pulled harder--ever increasing their gallop- -that one noticed how fast the troyka was flying. Nicholas looked back. -With screams squeals, and waving of whips that caused even the shaft -horses to gallop--the other sleighs followed. The shaft horse swung -steadily beneath the bow over its head, with no thought of -slackening pace and ready to put on speed when required. - -Nicholas overtook the first sleigh. They were driving downhill and -coming out upon a broad trodden track across a meadow, near a river. - -"Where are we?" thought he. "It's the Kosoy meadow, I suppose. But -no--this is something new I've never seen before. This isn't the Kosoy -meadow nor the Demkin hill, and heaven only knows what it is! It is -something new and enchanted. Well, whatever it may be..." And shouting -to his horses, he began to pass the first sleigh. - -Zakhar held back his horses and turned his face, which was already -covered with hoarfrost to his eyebrows. - -Nicholas gave the horses the rein, and Zakhar, stretching out his -arms, clucked his tongue and let his horses go. - -"Now, look out, master!" he cried. - -Faster still the two troykas flew side by side, and faster moved the -feet of the galloping side horses. Nicholas began to draw ahead. -Zakhar, while still keeping his arms extended, raised one hand with -the reins. - -"No you won't, master!" he shouted. - -Nicholas put all his horses to a gallop and passed Zakhar. The -horses showered the fine dry snow on the faces of those in the sleigh- -beside them sounded quick ringing bells and they caught confused -glimpses of swiftly moving legs and the shadows of the troyka they -were passing. The whistling sound of the runners on the snow and the -voices of girls shrieking were heard from different sides. - -Again checking his horses, Nicholas looked around him. They were -still surrounded by the magic plain bathed in moonlight and spangled -with stars. - -"Zakhar is shouting that I should turn to the left, but why to the -left?" thought Nicholas. "Are we getting to the Melyukovs'? Is this -Melyukovka? Heaven only knows where we are going, and heaven knows -what is happening to us--but it is very strange and pleasant -whatever it is." And he looked round in the sleigh. - -"Look, his mustache and eyelashes are all white!" said one of the -strange, pretty, unfamiliar people--the one with fine eyebrows and -mustache. - -"I think this used to be Natasha," thought Nicholas, "and that was -Madame Schoss, but perhaps it's not, and this Circassian with the -mustache I don't know, but I love her." - -"Aren't you cold?" he asked. - -They did not answer but began to laugh. Dimmler from the sleigh -behind shouted something--probably something funny--but they could not -make out what he said. - -"Yes, yes!" some voices answered, laughing. - -"But here was a fairy forest with black moving shadows, and a -glitter of diamonds and a flight of marble steps and the silver -roofs of fairy buildings and the shrill yells of some animals. And -if this is really Melyukovka, it is still stranger that we drove -heaven knows where and have come to Melyukovka," thought Nicholas. - -It really was Melyukovka, and maids and footmen with merry faces -came running, out to the porch carrying candles. - -"Who is it?" asked someone in the porch. - -"The mummers from the count's. I know by the horses," replied some -voices. - - - - - -CHAPTER XI - - -Pelageya Danilovna Melyukova, a broadly built, energetic woman -wearing spectacles, sat in the drawing room in a loose dress, -surrounded by her daughters whom she was trying to keep from feeling -dull. They were quietly dropping melted wax into snow and looking at -the shadows the wax figures would throw on the wall, when they heard -the steps and voices of new arrivals in the vestibule. - -Hussars, ladies, witches, clowns, and bears, after clearing their -throats and wiping the hoarfrost from their faces in the vestibule, -came into the ballroom where candles were hurriedly lighted. The -clown--Dimmler--and the lady--Nicholas--started a dance. Surrounded by -the screaming children the mummers, covering their faces and -disguising their voices, bowed to their hostess and arranged -themselves about the room. - -"Dear me! there's no recognizing them! And Natasha! See whom she -looks like! She really reminds me of somebody. But Herr Dimmler--isn't -he good! I didn't know him! And how he dances. Dear me, there's a -Circassian. Really, how becoming it is to dear Sonya. And who is that? -Well, you have cheered us up! Nikita and Vanya--clear away the tables! -And we were sitting so quietly. Ha, ha, ha!... The hussar, the hussar! -Just like a boy! And the legs!... I can't look at him..." different -voices were saying. - -Natasha, the young Melyukovs' favorite, disappeared with them into -the back rooms where a cork and various dressing gowns and male -garments were called for and received from the footman by bare girlish -arms from behind the door. Ten minutes later, all the young -Melyukovs joined the mummers. - -Pelageya Danilovna, having given orders to clear the rooms for the -visitors and arranged about refreshments for the gentry and the serfs, -went about among the mummers without removing her spectacles, -peering into their faces with a suppressed smile and failing to -recognize any of them. It was not merely Dimmler and the Rostovs she -failed to recognize, she did not even recognize her own daughters, -or her late husband's, dressing gowns and uniforms, which they had put -on. - -"And who is is this?" she asked her governess, peering into the face -of her own daughter dressed up as a Kazan-Tartar. "I suppose it is one -of the Rostovs! Well, Mr. Hussar, and what regiment do you serve -in?" she asked Natasha. "Here, hand some fruit jelly to the Turk!" she -ordered the butler who was handing things round. "That's not forbidden -by his law." - -Sometimes, as she looked at the strange but amusing capers cut by -the dancers, who--having decided once for all that being disguised, no -one would recognize them--were not at all shy, Pelageya Danilovna -hid her face in her handkerchief, and her whole stout body shook -with irrepressible, kindly, elderly laughter. - -"My little Sasha! Look at Sasha!" she said. - -After Russian country dances and chorus dances, Pelageya Danilovna -made the serfs and gentry join in one large circle: a ring, a -string, and a silver ruble were fetched and they all played games -together. - -In an hour, all the costumes were crumpled and disordered. The -corked eyebrows and mustaches were smeared over the perspiring, -flushed, and merry faces. Pelageya Danilovna began to recognize the -mummers, admired their cleverly contrived costumes, and particularly -how they suited the young ladies, and she thanked them all for -having entertained her so well. The visitors were invited to supper in -the drawing room, and the serfs had something served to them in the -ballroom. - -"Now to tell one's fortune in the empty bathhouse is frightening!" -said an old maid who lived with the Melyukovs, during supper. - -"Why?" said the eldest Melyukov girl. - -"You wouldn't go, it takes courage..." - -"I'll go," said Sonya. - -"Tell what happened to the young lady!" said the second Melyukov -girl. - -"Well," began the old maid, "a young lady once went out, took a -cock, laid the table for two, all properly, and sat down. After -sitting a while, she suddenly hears someone coming... a sleigh -drives up with harness bells; she hears him coming! He comes in, -just in the shape of a man, like an officer--comes in and sits down to -table with her." - -"Ah! ah!" screamed Natasha, rolling her eyes with horror. - -"Yes? And how... did he speak?" - -"Yes, like a man. Everything quite all right, and he began -persuading her; and she should have kept him talking till cockcrow, -but she got frightened, just got frightened and hid her face in her -hands. Then he caught her up. It was lucky the maids ran in just -then..." - -"Now, why frighten them?" said Pelageya Danilovna. - -"Mamma, you used to try your fate yourself..." said her daughter. - -"And how does one do it in a barn?" inquired Sonya. - -"Well, say you went to the barn now, and listened. It depends on -what you hear; hammering and knocking--that's bad; but a sound of -shifting grain is good and one sometimes hears that, too." - -"Mamma, tell us what happened to you in the barn." - -Pelageya Danilovna smiled. - -"Oh, I've forgotten..." she replied. "But none of you would go?" - -"Yes, I will; Pelageya Danilovna, let me! I'll go," said Sonya. - -"Well, why not, if you're not afraid?" - -"Louisa Ivanovna, may I?" asked Sonya. - -Whether they were playing the ring and string game or the ruble game -or talking as now, Nicholas did not leave Sonya's side, and gazed at -her with quite new eyes. It seemed to him that it was only today, -thanks to that burnt-cork mustache, that he had fully learned to -know her. And really, that evening, Sonya was brighter, more animated, -and prettier than Nicholas had ever seen her before. - -"So that's what she is like; what a fool I have been!" he thought -gazing at her sparkling eyes, and under the mustache a happy rapturous -smile dimpled her cheeks, a smile he had never seen before. - -"I'm not afraid of anything," said Sonya. "May I go at once?" She -got up. - -They told her where the barn was and how she should stand and -listen, and they handed her a fur cloak. She threw this over her -head and shoulders and glanced at Nicholas. - -"What a darling that girl is!" thought he. "And what have I been -thinking of till now?" - -Sonya went out into the passage to go to the barn. Nicholas went -hastily to the front porch, saying he felt too hot. The crowd of -people really had made the house stuffy. - -Outside, there was the same cold stillness and the same moon, but -even brighter than before. The light was so strong and the snow -sparkled with so many stars that one did not wish to look up at the -sky and the real stars were unnoticed. The sky was black and dreary, -while the earth was gay. - -"I am a fool, a fool! what have I been waiting for?" thought -Nicholas, and running out from the porch he went round the corner of -the house and along the path that led to the back porch. He knew Sonya -would pass that way. Halfway lay some snow-covered piles of firewood -and across and along them a network of shadows from the bare old -lime trees fell on the snow and on the path. This path led to the -barn. The log walls of the barn and its snow-covered roof, that looked -as if hewn out of some precious stone, sparkled in the moonlight. A -tree in the garden snapped with the frost, and then all was again -perfectly silent. His bosom seemed to inhale not air but the -strength of eternal youth and gladness. - -From the back porch came the sound of feet descending the steps, the -bottom step upon which snow had fallen gave a ringing creak and he -heard the voice of an old maidservant saying, "Straight, straight, -along the path, Miss. Only, don't look back." - -"I am not afraid," answered Sonya's voice, and along the path toward -Nicholas came the crunching, whistling sound of Sonya's feet in her -thin shoes. - -Sonya came along, wrapped in her cloak. She was only a couple of -paces away when she saw him, and to her too he was not the Nicholas -she had known and always slightly feared. He was in a woman's dress, -with tousled hair and a happy smile new to Sonya. She ran rapidly -toward him. - -"Quite different and yet the same," thought Nicholas, looking at her -face all lit up by the moonlight. He slipped his arms under the -cloak that covered her head, embraced her, pressed her to him, and -kissed her on the lips that wore a mustache and had a smell of burnt -cork. Sonya kissed him full on the lips, and disengaging her little -hands pressed them to his cheeks. - -"Sonya!... Nicholas!"... was all they said. They ran to the barn and -then back again, re-entering, he by the front and she by the back -porch. - - - - - -CHAPTER XII - - -When they all drove back from Pelageya Danilovna's, Natasha, who -always saw and noticed everything, arranged that she and Madame Schoss -should go back in the sleigh with Dimmler, and Sonya with Nicholas and -the maids. - -On the way back Nicholas drove at a steady pace instead of racing -and kept peering by that fantastic all-transforming light into Sonya's -face and searching beneath the eyebrows and mustache for his former -and his present Sonya from whom he had resolved never to be parted -again. He looked and recognizing in her both the old and the new -Sonya, and being reminded by the smell of burnt cork of the -sensation of her kiss, inhaled the frosty air with a full breast -and, looking at the ground flying beneath him and at the sparkling -sky, felt himself again in fairyland. - -"Sonya, is it well with thee?" he asked from time to time. - -"Yes!" she replied. "And with thee?" - -When halfway home Nicholas handed the reins to the coachman and -ran for a moment to Natasha's sleigh and stood on its wing. - -"Natasha!" he whispered in French, "do you know I have made up my -mind about Sonya?" - -"Have you told her?" asked Natasha, suddenly beaming all over with -joy. - -"Oh, how strange you are with that mustache and those eyebrows!... -Natasha--are you glad?" - -"I am so glad, so glad! I was beginning to be vexed with you. I -did not tell you, but you have been treating her badly. What a heart -she has, Nicholas! I am horrid sometimes, but I was ashamed to be -happy while Sonya was not," continued Natasha. "Now I am so glad! -Well, run back to her." - -"No, wait a bit.... Oh, how funny you look!" cried Nicholas, peering -into her face and finding in his sister too something new, unusual, -and bewitchingly tender that he had not seen in her before. -"Natasha, it's magical, isn't it?" - -"Yes," she replied. "You have done splendidly." - -"Had I seen her before as she is now," thought Nicholas, "I should -long ago have asked her what to do and have done whatever she told me, -and all would have been well." - -"So you are glad and I have done right?" - -"Oh, quite right! I had a quarrel with Mamma some time ago about it. -Mamma said she was angling for you. How could she say such a thing! -I nearly stormed at Mamma. I will never let anyone say anything bad of -Sonya, for there is nothing but good in her." - -"Then it's all right?" said Nicholas, again scrutinizing the -expression of his sister's face to see if she was in earnest. Then -he jumped down and, his boots scrunching the snow, ran back to his -sleigh. The same happy, smiling Circassian, with mustache and -beaming eyes looking up from under a sable hood, was still sitting -there, and that Circassian was Sonya, and that Sonya was certainly his -future happy and loving wife. - -When they reached home and had told their mother how they had -spent the evening at the Melyukovs', the girls went to their -bedroom. When they had undressed, but without washing off the cork -mustaches, they sat a long time talking of their happiness. They -talked of how they would live when they were married, how their -husbands would be friends, and how happy they would be. On Natasha's -table stood two looking glasses which Dunyasha had prepared -beforehand. - -"Only when will all that be? I am afraid never.... It would be too -good!" said Natasha, rising and going to the looking glasses. - -"Sit down, Natasha; perhaps you'll see him," said Sonya. - -Natasha lit the candles, one on each side of one of the looking -glasses, and sat down. - -"I see someone with a mustache," said Natasha, seeing her own face. - -"You mustn't laugh, Miss," said Dunyasha. - -With Sonya's help and the maid's, Natasha got the glass she held -into the right position opposite the other; her face assumed a serious -expression and she sat silent. She sat a long time looking at the -receding line of candles reflected in the glasses and expecting -(from tales she had heard) to see a coffin, or him, Prince Andrew, -in that last dim, indistinctly outlined square. But ready as she was -to take the smallest speck for the image of a man or of a coffin, -she saw nothing. She began blinking rapidly and moved away from the -looking glasses. - -"Why is it others see things and I don't?" she said. "You sit down -now, Sonya. You absolutely must, tonight! Do it for me.... Today I -feel so frightened!" - -Sonya sat down before the glasses, got the right position, and began -looking. - -"Now, Miss Sonya is sure to see something," whispered Dunyasha; -"while you do nothing but laugh." - -Sonya heard this and Natasha's whisper: - -"I know she will. She saw something last year." - -For about three minutes all were silent. - -"Of course she will!" whispered Natasha, but did not finish... -suddenly Sonya pushed away the glass she was holding and covered her -eyes with her hand. - -"Oh, Natasha!" she cried. - -"Did you see? Did you? What was it?" exclaimed Natasha, holding up -the looking glass. - -Sonya had not seen anything, she was just wanting to blink and to -get up when she heard Natasha say, "Of course she will!" She did not -wish to disappoint either Dunyasha or Natasha, but it was hard to -sit still. She did not herself know how or why the exclamation escaped -her when she covered her eyes. - -"You saw him?" urged Natasha, seizing her hand. - -"Yes. Wait a bit... I... saw him," Sonya could not help saying, -not yet knowing whom Natasha meant by him, Nicholas or Prince Andrew. - -"But why shouldn't I say I saw something? Others do see! Besides who -can tell whether I saw anything or not?" flashed through Sonya's mind. - -"Yes, I saw him," she said. - -"How? Standing or lying?" - -"No, I saw... At first there was nothing, then I saw him lying -down." - -"Andrew lying? Is he ill?" asked Natasha, her frightened eyes -fixed on her friend. - -"No, on the contrary, on the contrary! His face was cheerful, and he -turned to me." And when saying this she herself fancied she had really -seen what she described. - -"Well, and then, Sonya?..." - -"After that, I could not make out what there was; something blue and -red..." - -"Sonya! When will he come back? When shall I see him! O, God, how -afraid I am for him and for myself and about everything!..." Natasha -began, and without replying to Sonya's words of comfort she got into -bed, and long after her candle was out lay open-eyed and motionless, -gazing at the moonlight through the frosty windowpanes. - - - - - -CHAPTER XIII - - -Soon after the Christmas holidays Nicholas told his mother of his -love for Sonya and of his firm resolve to marry her. The countess, who -had long noticed what was going on between them and was expecting this -declaration, listened to him in silence and then told her son that -he might marry whom he pleased, but that neither she nor his father -would give their blessing to such a marriage. Nicholas, for the -first time, felt that his mother was displeased with him and that, -despite her love for him, she would not give way. Coldly, without -looking at her son, she sent for her husband and, when he came, -tried briefly and coldly to inform him of the facts, in her son's -presence, but unable to restrain herself she burst into tears of -vexation and left the room. The old count began irresolutely to -admonish Nicholas and beg him to abandon his purpose. Nicholas replied -that he could not go back on his word, and his father, sighing and -evidently disconcerted, very soon became silent and went in to the -countess. In all his encounters with his son, the count was always -conscious of his own guilt toward him for having wasted the family -fortune, and so he could not be angry with him for refusing to marry -an heiress and choosing the dowerless Sonya. On this occasion, he -was only more vividly conscious of the fact that if his affairs had -not been in disorder, no better wife for Nicholas than Sonya could -have been wished for, and that no one but himself with his Mitenka and -his uncomfortable habits was to blame for the condition of the -family finances. - -The father and mother did not speak of the matter to their son -again, but a few days later the countess sent for Sonya and, with a -cruelty neither of them expected, reproached her niece for trying to -catch Nicholas and for ingratitude. Sonya listened silently with -downcast eyes to the countess' cruel words, without understanding what -was required of her. She was ready to sacrifice everything for her -benefactors. Self-sacrifice was her most cherished idea but in this -case she could not see what she ought to sacrifice, or for whom. She -could not help loving the countess and the whole Rostov family, but -neither could she help loving Nicholas and knowing that his -happiness depended on that love. She was silent and sad and did not -reply. Nicholas felt the situation to be intolerable and went to -have an explanation with his mother. He first implored her to -forgive him and Sonya and consent to their marriage, then he -threatened that if she molested Sonya he would at once marry her -secretly. - -The countess, with a coldness her son had never seen in her -before, replied that he was of age, that Prince Andrew was marrying -without his father's consent, and he could do the same, but that she -would never receive that intriguer as her daughter. - -Exploding at the word intriguer, Nicholas, raising his voice, told -his mother he had never expected her to try to force him to sell his -feelings, but if that were so, he would say for the last time.... -But he had no time to utter the decisive word which the expression -of his face caused his mother to await with terror, and which would -perhaps have forever remained a cruel memory to them both. He had -not time to say it, for Natasha, with a pale and set face, entered the -room from the door at which she had been listening. - -"Nicholas, you are talking nonsense! Be quiet, be quiet, be quiet, I -tell you!..." she almost screamed, so as to drown his voice. - -"Mamma darling, it's not at all so... my poor, sweet darling," she -said to her mother, who conscious that they had been on the brink of a -rupture gazed at her son with terror, but in the obstinacy and -excitement of the conflict could not and would not give way. - -"Nicholas, I'll explain to you. Go away! Listen, Mamma darling," -said Natasha. - -Her words were incoherent, but they attained the purpose at which -she was aiming. - -The countess, sobbing heavily, hid her face on her daughter's -breast, while Nicholas rose, clutching his head, and left the room. - -Natasha set to work to effect a reconciliation, and so far succeeded -that Nicholas received a promise from his mother that Sonya should not -be troubled, while he on his side promised not to undertake anything -without his parents' knowledge. - -Firmly resolved, after putting his affairs in order in the regiment, -to retire from the army and return and marry Sonya, Nicholas, serious, -sorrowful, and at variance with his parents, but, as it seemed to him, -passionately in love, left at the beginning of January to rejoin his -regiment. - -After Nicholas had gone things in the Rostov household were more -depressing than ever, and the countess fell ill from mental agitation. - -Sonya was unhappy at the separation from Nicholas and still more -so on account of the hostile tone the countess could not help adopting -toward her. The count was more perturbed than ever by the condition of -his affairs, which called for some decisive action. Their town house -and estate near Moscow had inevitably to be sold, and for this they -had to go to Moscow. But the countess' health obliged them to delay -their departure from day to day. - -Natasha, who had borne the first period of separation from her -betrothed lightly and even cheerfully, now grew more agitated and -impatient every day. The thought that her best days, which she would -have employed in loving him, were being vainly wasted, with no -advantage to anyone, tormented her incessantly. His letters for the -most part irritated her. It hurt her to think that while she lived -only in the thought of him, he was living a real life, seeing new -places and new people that interested him. The more interesting his -letters were the more vexed she felt. Her letters to him, far from -giving her any comfort, seemed to her a wearisome and artificial -obligation. She could not write, because she could not conceive the -possibility of expressing sincerely in a letter even a thousandth part -of what she expressed by voice, smile, and glance. She wrote to him -formal, monotonous, and dry letters, to which she attached no -importance herself, and in the rough copies of which the countess -corrected her mistakes in spelling. - -There was still no improvement in the countess' health, but it was -impossible to defer the journey to Moscow any longer. Natasha's -trousseau had to be ordered and the house sold. Moreover, Prince -Andrew was expected in Moscow, where old Prince Bolkonski was spending -the winter, and Natasha felt sure he had already arrived. - -So the countess remained in the country, and the count, taking Sonya -and Natasha with him, went to Moscow at the end of January. - - - - -BOOK EIGHT: 1811 --12 - - - - - -CHAPTER I - - -After Prince Andrews engagement to Natasha, Pierre without any -apparent cause suddenly felt it impossible to go on living as -before. Firmly convinced as he was of the truths revealed to him by -his benefactor, and happy as he had been in perfecting his inner -man, to which he had devoted himself with such ardor--all the zest -of such a life vanished after the engagement of Andrew and Natasha and -the death of Joseph Alexeevich, the news of which reached him almost -at the same time. Only the skeleton of life remained: his house, a -brilliant wife who now enjoyed the favors of a very important -personage, acquaintance with all Petersburg, and his court service -with its dull formalities. And this life suddenly seemed to Pierre -unexpectedly loathsome. He ceased keeping a diary, avoided the company -of the Brothers, began going to the Club again, drank a great deal, -and came once more in touch with the bachelor sets, leading such a -life that the Countess Helene thought it necessary to speak severely -to him about it. Pierre felt that she right, and to avoid compromising -her went away to Moscow. - -In Moscow as soon as he entered his huge house in which the faded -and fading princesses still lived, with its enormous retinue; as -soon as, driving through the town, he saw the Iberian shrine with -innumerable tapers burning before the golden covers of the icons, -the Kremlin Square with its snow undisturbed by vehicles, the sleigh -drivers and hovels of the Sivtsev Vrazhok, those old Moscovites who -desired nothing, hurried nowhere, and were ending their days -leisurely; when he saw those old Moscow ladies, the Moscow balls, -and the English Club, he felt himself at home in a quiet haven. In -Moscow he felt at peace, at home, warm and dirty as in an old dressing -gown. - -Moscow society, from the old women down to the children, received -Pierre like a long-expected guest whose place was always ready -awaiting him. For Moscow society Pierre was the nicest, kindest, -most intellectual, merriest, and most magnanimous of cranks, a -heedless, genial nobleman of the old Russian type. His purse was -always empty because it was open to everyone. - -Benefit performances, poor pictures, statues, benevolent -societies, gypsy choirs, schools, subscription dinners, sprees, -Freemasons, churches, and books--no one and nothing met with a refusal -from him, and had it not been for two friends who had borrowed large -sums from him and taken him under their protection, he would have -given everything away. There was never a dinner or soiree at the -Club without him. As soon as he sank into his place on the sofa -after two bottles of Margaux he was surrounded, and talking, -disputing, and joking began. When there were quarrels, his kindly -smile and well-timed jests reconciled the antagonists. The Masonic -dinners were dull and dreary when he was not there. - -When after a bachelor supper he rose with his amiable and kindly -smile, yielding to the entreaties of the festive company to drive -off somewhere with them, shouts of delight and triumph arose among the -young men. At balls he danced if a partner was needed. Young ladies, -married and unmarried, liked him because without making love to any of -them, he was equally amiable to all, especially after supper. "Il -est charmant; il n'a pas de sexe,"* they said of him. - - -*"He is charming; he has no sex." - - -Pierre was one of those retired gentlemen-in-waiting of whom there -were hundreds good-humoredly ending their days in Moscow. - -How horrified he would have been seven years before, when he first -arrived from abroad, had he been told that there was no need for him -to seek or plan anything, that his rut had long been shaped, eternally -predetermined, and that wriggle as he might, he would be what all in -his position were. He could not have believed it! Had he not at one -time longed with all his heart to establish a republic in Russia; then -himself to be a Napoleon; then to be a philosopher; and then a -strategist and the conqueror of Napoleon? Had he not seen the -possibility of, and passionately desired, the regeneration of the -sinful human race, and his own progress to the highest degree of -perfection? Had he not established schools and hospitals and liberated -his serfs? - -But instead of all that--here he was, the wealthy husband of an -unfaithful wife, a retired gentleman-in-waiting, fond of eating and -drinking and, as he unbuttoned his waistcoat, of abusing the -government a bit, a member of the Moscow English Club, and a universal -favorite in Moscow society. For a long time he could not reconcile -himself to the idea that he was one of those same retired Moscow -gentlemen-in-waiting he had so despised seven years before. - -Sometimes he consoled himself with the thought that he was only -living this life temporarily; but then he was shocked by the thought -of how many, like himself, had entered that life and that Club -temporarily, with all their teeth and hair, and had only left it -when not a single tooth or hair remained. - -In moments of pride, when he thought of his position it seemed to -him that he was quite different and distinct from those other -retired gentlemen-in-waiting he had formerly despised: they were -empty, stupid, contented fellows, satisfied with their position, -"while I am still discontented and want to do something for mankind. -But perhaps all these comrades of mine struggled just like me and -sought something new, a path in life of their own, and like me were -brought by force of circumstances, society, and race--by that -elemental force against which man is powerless--to the condition I -am in," said he to himself in moments of humility; and after living -some time in Moscow he no longer despised, but began to grow fond -of, to respect, and to pity his comrades in destiny, as he pitied -himself. - -Pierre longer suffered moments of despair, hypochondria, and disgust -with life, but the malady that had formerly found expression in such -acute attacks was driven inwards and never left him for a moment. -"What for? Why? What is going on in the world?" he would ask himself -in perplexity several times a day, involuntarily beginning to -reflect anew on the meaning of the phenomena of life; but knowing by -experience that there were no answers to these questions he made haste -to turn away from them, and took up a book, or hurried of to the -Club or to Apollon Nikolaevich's, to exchange the gossip of the town. - -"Helene, who has never cared for anything but her own body and is -one of the stupidest women in the world," thought Pierre, "is regarded -by people as the acme of intelligence and refinement, and they pay -homage to her. Napoleon Bonaparte was despised by all as long as he -was great, but now that he has become a wretched comedian the -Emperor Francis wants to offer him his daughter in an illegal -marriage. The Spaniards, through the Catholic clergy, offer praise -to God for their victory over the French on the fourteenth of June, -and the French, also through the Catholic clergy, offer praise because -on that same fourteenth of June they defeated the Spaniards. My -brother Masons swear by the blood that they are ready to sacrifice -everything for their neighbor, but they do not give a ruble each to -the collections for the poor, and they intrigue, the Astraea Lodge -against the Manna Seekers, and fuss about an authentic Scotch carpet -and a charter that nobody needs, and the meaning of which the very man -who wrote it does not understand. We all profess the Christian law -of forgiveness of injuries and love of our neighbors, the law in honor -of which we have built in Moscow forty times forty churches--but -yesterday a deserter was knouted to death and a minister of that -same law of love and forgiveness, a priest, gave the soldier a cross -to kiss before his execution." So thought Pierre, and the whole of -this general deception which everyone accepts, accustomed as he was to -it, astonished him each time as if it were something new. "I -understand the deception and confusion," he thought, "but how am I -to tell them all that I see? I have tried, and have always found -that they too in the depths of their souls understand it as I do, -and only try not to see it. So it appears that it must be so! But I- -what is to become of me?" thought he. He had the unfortunate -capacity many men, especially Russians, have of seeing and believing -in the possibility of goodness and truth, but of seeing the evil and -falsehood of life too clearly to be able to take a serious part in it. -Every sphere of work was connected, in his eyes, with evil and -deception. Whatever he tried to be, whatever he engaged in, the evil -and falsehood of it repulsed him and blocked every path of activity. -Yet he had to live and to find occupation. It was too dreadful to be -under the burden of these insoluble problems, so he abandoned -himself to any distraction in order to forget them. He frequented -every kind of society, drank much, bought pictures, engaged in -building, and above all--read. - -He read, and read everything that came to hand. On coming home, -while his valets were still taking off his things, he picked up a book -and began to read. From reading he passed to sleeping, from sleeping -to gossip in drawing rooms of the Club, from gossip to carousals and -women; from carousals back to gossip, reading, and wine. Drinking -became more and more a physical and also a moral necessity. Though the -doctors warned him that with his corpulence wine was dangerous for -him, he drank a great deal. He was only quite at ease when having -poured several glasses of wine mechanically into his large mouth he -felt a pleasant warmth in his body, an amiability toward all his -fellows, and a readiness to respond superficially to every idea -without probing it deeply. Only after emptying a bottle or two did -he feel dimly that the terribly tangled skein of life which previously -had terrified him was not as dreadful as he had thought. He was always -conscious of some aspect of that skein, as with a buzzing in his -head after dinner or supper he chatted or listened to conversation -or read. But under the influence of wine he said to himself: "It -doesn't matter. I'll get it unraveled. I have a solution ready, but -have no time now--I'll think it all out later on!" But the later on -never came. - -In the morning, on an empty stomach, all the old questions -appeared as insoluble and terrible as ever, and Pierre hastily -picked up a book, and if anyone came to see him he was glad. - -Sometimes he remembered how he had heard that soldiers in war when -entrenched under the enemy's fire, if they have nothing to do, try -hard to find some occupation the more easily to bear the danger. To -Pierre all men seemed like those soldiers, seeking refuge from life: -some in ambition, some in cards, some in framing laws, some in -women, some in toys, some in horses, some in politics, some in -sport, some in wine, and some in governmental affairs. "Nothing is -trivial, and nothing is important, it's all the same--only to save -oneself from it as best one can," thought Pierre. "Only not to see it, -that dreadful it!" - - - - - -CHAPTER II - - -At the beginning of winter Prince Nicholas Bolkonski and his -daughter moved to Moscow. At that time enthusiasm for the Emperor -Alexander's regime had weakened and a patriotic and anti-French -tendency prevailed there, and this, together with his past and his -intellect and his originality, at once made Prince Nicholas -Bolkonski an object of particular respect to the Moscovites and the -center of the Moscow opposition to the government. - -The prince had aged very much that year. He showed marked signs of -senility by a tendency to fall asleep, forgetfulness of quite recent -events, remembrance of remote ones, and the childish vanity with which -he accepted the role of head of the Moscow opposition. In spite of -this the old man inspired in all his visitors alike a feeling of -respectful veneration--especially of an evening when he came in to tea -in his old-fashioned coat and powdered wig and, aroused by anyone, -told his abrupt stories of the past, or uttered yet more abrupt and -scathing criticisms of the present. For them all, that old-fashioned -house with its gigantic mirrors, pre-Revolution furniture, powdered -footmen, and the stern shrewd old man (himself a relic of the past -century) with his gentle daughter and the pretty Frenchwoman who -were reverently devoted to him presented a majestic and agreeable -spectacle. But the visitors did not reflect that besides the couple of -hours during which they saw their host, there were also twenty-two -hours in the day during which the private and intimate life of the -house continued. - -Latterly that private life had become very trying for Princess Mary. -There in Moscow she was deprived of her greatest pleasures--talks with -the pilgrims and the solitude which refreshed her at Bald Hills--and -she had none of the advantages and pleasures of city life. She did not -go out into society; everyone knew that her father would not let her -go anywhere without him, and his failing health prevented his going -out himself, so that she was not invited to dinners and evening -parties. She had quite abandoned the hope of getting married. She -saw the coldness and malevolence with which the old prince received -and dismissed the young men, possible suitors, who sometimes -appeared at their house. She had no friends: during this visit to -Moscow she had been disappointed in the two who had been nearest to -her. Mademoiselle Bourienne, with whom she had never been able to be -quite frank, had now become unpleasant to her, and for various reasons -Princess Mary avoided her. Julie, with whom she had corresponded for -the last five years, was in Moscow, but proved to be quite alien to -her when they met. Just then Julie, who by the death of her brothers -had become one of the richest heiresses in Moscow, was in the full -whirl of society pleasures. She was surrounded by young men who, she -fancied, had suddenly learned to appreciate her worth. Julie was at -that stage in the life of a society woman when she feels that her last -chance of marrying has come and that her fate must be decided now or -never. On Thursdays Princess Mary remembered with a mournful smile -that she now had no one to write to, since Julie--whose presence -gave her no pleasure was here and they met every week. Like the old -emigre who declined to marry the lady with whom he had spent his -evenings for years, she regretted Julie's presence and having no one -to write to. In Moscow Princess Mary had no one to talk to, no one -to whom to confide her sorrow, and much sorrow fell to her lot just -then. The time for Prince Andrew's return and marriage was -approaching, but his request to her to prepare his father for it had -not been carried out; in fact, it seemed as if matters were quite -hopeless, for at every mention of the young Countess Rostova the old -prince (who apart from that was usually in a bad temper) lost -control of himself. Another lately added sorrow arose from the lessons -she gave her six year-old nephew. To her consternation she detected in -herself in relation to little Nicholas some symptoms of her father's -irritability. However often she told herself that she must not get -irritable when teaching her nephew, almost every time that, pointer in -hand, she sat down to show him the French alphabet, she so longed to -pour her own knowledge quickly and easily into the child--who was -already afraid that Auntie might at any moment get angry--that at -his slightest inattention she trembled, became flustered and heated, -raised her voice, and sometimes pulled him by the arm and put him in -the corner. Having put him in the corner she would herself begin to -cry over her cruel, evil nature, and little Nicholas, following her -example, would sob, and without permission would leave his corner, -come to her, pull her wet hands from her face, and comfort her. But -what distressed the princess most of all was her father's -irritability, which was always directed against her and had of late -amounted to cruelty. Had he forced her to prostrate herself to the -ground all night, had he beaten her or made her fetch wood or water, -it would never have entered her mind to think her position hard; but -this loving despot--the more cruel because he loved her and for that -reason tormented himself and her--knew how not merely to hurt and -humiliate her deliberately, but to show her that she was always to -blame for everything. Of late he had exhibited a new trait that -tormented Princess Mary more than anything else; this was his -ever-increasing intimacy with Mademoiselle Bourienne. The idea that at -the first moment of receiving the news of his son's intentions had -occurred to him in jest--that if Andrew got married he himself would -marry Bourienne--had evidently pleased him, and latterly he had -persistently, and as it seemed to Princess Mary merely to offend -her, shown special endearments to the companion and expressed his -dissatisfaction with his daughter by demonstrations of love of -Bourienne. - -One day in Moscow in Princess Mary's presence (she thought her -father did it purposely when she was there) the old prince kissed -Mademoiselle Bourienne's hand and, drawing her to him, embraced her -affectionately. Princess Mary flushed and ran out of the room. A few -minutes later Mademoiselle Bourienne came into Princess Mary's room -smiling and making cheerful remarks in her agreeable voice. Princess -Mary hastily wiped away her tears, went resolutely up to -Mademoiselle Bourienne, and evidently unconscious of what she was -doing began shouting in angry haste at the Frenchwoman, her voice -breaking: "It's horrible, vile, inhuman, to take advantage of the -weakness..." She did not finish. "Leave my room," she exclaimed, and -burst into sobs. - -Next day the prince did not say a word to his daughter, but she -noticed that at dinner he gave orders that Mademoiselle Bourienne -should be served first. After dinner, when the footman handed coffee -and from habit began with the princess, the prince suddenly grew -furious, threw his stick at Philip, and instantly gave instructions to -have him conscripted for the army. - -"He doesn't obey... I said it twice... and he doesn't obey! She is -the first person in this house; she's my best friend," cried the -prince. "And if you allow yourself," he screamed in a fury, addressing -Princess Mary for the first time, "to forget yourself again before her -as you dared to do yesterday, I will show you who is master in this -house. Go! Don't let me set eyes on you; beg her pardon!" - -Princess Mary asked Mademoiselle Bourienne's pardon, and also her -father's pardon for herself and for Philip the footman, who had begged -for her intervention. - -At such moments something like a pride of sacrifice gathered in -her soul. And suddenly that father whom she had judged would look -for his spectacles in her presence, fumbling near them and not -seeing them, or would forget something that had just occurred, or take -a false step with his failing legs and turn to see if anyone had -noticed his feebleness, or, worst of all, at dinner when there were no -visitors to excite him would suddenly fall asleep, letting his -napkin drop and his shaking head sink over his plate. "He is old and -feeble, and I dare to condemn him!" she thought at such moments, -with a feeling of revulsion against herself. - - - - - -CHAPTER III - - -In 1811 there was living in Moscow a French doctor--Metivier--who -had rapidly become the fashion. He was enormously tall, handsome, -amiable as Frenchmen are, and was, as all Moscow said, an -extraordinarily clever doctor. He was received in the best houses -not merely as a doctor, but as an equal. - -Prince Nicholas had always ridiculed medicine, but latterly on -Mademoiselle Bourienne's advice had allowed this doctor to visit him -and had grown accustomed to him. Metivier came to see the prince about -twice a week. - -On December 6--St. Nicholas' Day and the prince's name day--all -Moscow came to the prince's front door but he gave orders to admit -no one and to invite to dinner only a small number, a list of whom -he gave to Princess Mary. - -Metivier, who came in the morning with his felicitations, considered -it proper in his quality of doctor de forcer la consigne,* as he -told Princess Mary, and went in to see the prince. It happened that on -that morning of his name day the prince was in one of his worst moods. -He had been going about the house all the morning finding fault with -everyone and pretending not to understand what was said to him and not -to be understood himself. Princess Mary well knew this mood of quiet -absorbed querulousness, which generally culminated in a burst of rage, -and she went about all that morning as though facing a cocked and -loaded gun and awaited the inevitable explosion. Until the doctor's -arrival the morning had passed off safely. After admitting the doctor, -Princess Mary sat down with a book in the drawing room near the door -through which she could hear all that passed in the study. - - -*To force the guard. - - -At first she heard only Metivier's voice, then her father's, then -both voices began speaking at the same time, the door was flung -open, and on the threshold appeared the handsome figure of the -terrified Metivier with his shock of black hair, and the prince in his -dressing gown and fez, his face distorted with fury and the pupils -of his eyes rolled downwards. - -"You don't understand?" shouted the prince, "but I do! French spy, -slave of Buonaparte, spy, get out of my house! Be off, I tell you..." - -Metivier, shrugging his shoulders, went up to Mademoiselle Bourienne -who at the sound of shouting had run in from an adjoining room. - -"The prince is not very well: bile and rush of blood to the head. -Keep calm, I will call again tomorrow," said Metivier; and putting his -fingers to his lips he hastened away. - -Through the study door came the sound of slippered feet and the cry: -"Spies, traitors, traitors everywhere! Not a moment's peace in my -own house!" - -After Metivier's departure the old prince called his daughter in, -and the whole weight of his wrath fell on her. She was to blame that a -spy had been admitted. Had he not told her, yes, told her to make a -list, and not to admit anyone who was not on that list? Then why was -that scoundrel admitted? She was the cause of it all. With her, he -said, he could not have a moment's peace and could not die quietly. - -"No, ma'am! We must part, we must part! Understand that, -understand it! I cannot endure any more," he said, and left the -room. Then, as if afraid she might find some means of consolation, -he returned and trying to appear calm added: "And don't imagine I have -said this in a moment of anger. I am calm. I have thought it over, and -it will be carried out--we must part; so find some place for -yourself...." But he could not restrain himself and with the virulence -of which only one who loves is capable, evidently suffering himself, -he shook his fists at her and screamed: - -"If only some fool would marry her!" Then he slammed the door, -sent for Mademoiselle Bourienne, and subsided into his study. - -At two o'clock the six chosen guests assembled for dinner. - -These guests--the famous Count Rostopchin, Prince Lopukhin with -his nephew, General Chatrov an old war comrade of the prince's, and of -the younger generation Pierre and Boris Drubetskoy--awaited the prince -in the drawing room. - -Boris, who had come to Moscow on leave a few days before, had been -anxious to be presented to Prince Nicholas Bolkonski, and had -contrived to ingratiate himself so well that the old prince in his -case made an exception to the rule of not receiving bachelors in his -house. - -The prince's house did not belong to what is known as fashionable -society, but his little circle--though not much talked about in -town--was one it was more flattering to be received in than any other. -Boris had realized this the week before when the commander in chief in -his presence invited Rostopchin to dinner on St. Nicholas' Day, and -Rostopchin had replied that he could not come: - -"On that day I always go to pay my devotions to the relics of Prince -Nicholas Bolkonski." - -"Oh, yes, yes!" replied the commander in chief. "How is he?..." - -The small group that assembled before dinner in the lofty -old-fashioned drawing room with its old furniture resembled the solemn -gathering of a court of justice. All were silent or talked in low -tones. Prince Nicholas came in serious and taciturn. Princess Mary -seemed even quieter and more diffident than usual. The guests were -reluctant to address her, feeling that she was in no mood for their -conversation. Count Rostopchin alone kept the conversation going, -now relating the latest town news, and now the latest political -gossip. - -Lopukhin and the old general occasionally took part in the -conversation. Prince Bolkonski listened as a presiding judge -receives a report, only now and then, silently or by a brief word, -showing that he took heed of what was being reported to him. The -tone of the conversation was such as indicated that no one approved of -what was being done in the political world. Incidents were related -evidently confirming the opinion that everything was going from bad to -worse, but whether telling a story or giving an opinion the speaker -always stopped, or was stopped, at the point beyond which his -criticism might touch the sovereign himself. - -At dinner the talk turned on the latest political news: Napoleon's -seizure of the Duke of Oldenburg's territory, and the Russian Note, -hostile to Napoleon, which had been sent to all the European courts. - -"Bonaparte treats Europe as a pirate does a captured vessel," said -Count Rostopchin, repeating a phrase he had uttered several times -before. "One only wonders at the long-suffering or blindness of the -crowned heads. Now the Pope's turn has come and Bonaparte doesn't -scruple to depose the head of the Catholic Church--yet all keep -silent! Our sovereign alone has protested against the seizure of the -Duke of Oldenburg's territory, and even..." Count Rostopchin paused, -feeling that he had reached the limit beyond which censure was -impossible. - -"Other territories have been offered in exchange for the Duchy of -Oldenburg," said Prince Bolkonski. "He shifts the Dukes about as I -might move my serfs from Bald Hills to Bogucharovo or my Ryazan -estates." - -"The Duke of Oldenburg bears his misfortunes with admirable strength -of character and resignation," remarked Boris, joining in -respectfully. - -He said this because on his journey from Petersburg he had had the -honor of being presented to the Duke. Prince Bolkonski glanced at -the young man as if about to say something in reply, but changed his -mind, evidently considering him too young. - -"I have read our protests about the Oldenburg affair and was -surprised how badly the Note was worded," remarked Count Rostopchin in -the casual tone of a man dealing with a subject quite familiar to him. - -Pierre looked at Rostopchin with naive astonishment, not -understanding why he should be disturbed by the bad composition of the -Note. - -"Does it matter, Count, how the Note is worded," he asked, "so -long as its substance is forcible?" - -"My dear fellow, with our five hundred thousand troops it should -be easy to have a good style," returned Count Rostopchin. - -Pierre now understood the count's dissatisfaction with the wording -of the Note. - -"One would have thought quill drivers enough had sprung up," -remarked the old prince. "There in Petersburg they are always writing- -not notes only but even new laws. My Andrew there has written a -whole volume of laws for Russia. Nowadays they are always writing!" -and he laughed unnaturally. - -There was a momentary pause in the conversation; the old general -cleared his throat to draw attention. - -"Did you hear of the last event at the review in Petersburg? The -figure cut by the new French ambassador." - -"Eh? Yes, I heard something: he said something awkward in His -Majesty's presence." - -"His Majesty drew attention to the Grenadier division and to the -march past," continued the general, "and it seems the ambassador -took no notice and allowed himself to reply that: 'We in France pay no -attention to such trifles!' The Emperor did not condescend to reply. -At the next review, they say, the Emperor did not once deign to -address him." - -All were silent. On this fact relating to the Emperor personally, it -was impossible to pass any judgment. - -"Impudent fellows!" said the prince. "You know Metivier? I turned -him out of my house this morning. He was here; they admitted him spite -of my request that they should let no one in," he went on, glancing -angrily at his daughter. - -And he narrated his whole conversation with the French doctor and -the reasons that convinced him that Metivier was a spy. Though these -reasons were very insufficient and obscure, no one made any rejoinder. - -After the roast, champagne was served. The guests rose to -congratulate the old prince. Princess Mary, too, went round to him. - -He gave her a cold, angry look and offered her his wrinkled, -clean-shaven cheek to kiss. The whole expression of his face told -her that he had not forgotten the morning's talk, that his decision -remained in force, and only the presence of visitors hindered his -speaking of it to her now. - -When they went into the drawing room where coffee was served, the -old men sat together. - -Prince Nicholas grew more animated and expressed his views on the -impending war. - -He said that our wars with Bonaparte would be disastrous so long -as we sought alliances with the Germans and thrust ourselves into -European affairs, into which we had been drawn by the Peace of Tilsit. -"We ought not to fight either for or against Austria. Our political -interests are all in the East, and in regard to Bonaparte the only -thing is to have an armed frontier and a firm policy, and he will -never dare to cross the Russian frontier, as was the case in 1807!" - -"How can we fight the French, Prince?" said Count Rostopchin. "Can -we arm ourselves against our teachers and divinities? Look at our -youths, look at our ladies! The French are our Gods: Paris is our -Kingdom of Heaven." - -He began speaking louder, evidently to be heard by everyone. - -"French dresses, French ideas, French feelings! There now, you -turned Metivier out by the scruff of his neck because he is a -Frenchman and a scoundrel, but our ladies crawl after him on their -knees. I went to a party last night, and there out of five ladies -three were Roman Catholics and had the Pope's indulgence for doing -woolwork on Sundays. And they themselves sit there nearly naked, -like the signboards at our Public Baths if I may say so. Ah, when -one looks at our young people, Prince, one would like to take Peter -the Great's old cudgel out of the museum and belabor them in the -Russian way till all the nonsense jumps out of them." - -All were silent. The old prince looked at Rostopchin with a smile -and wagged his head approvingly. - -"Well, good-by, your excellency, keep well!" said Rostopchin, -getting up with characteristic briskness and holding out his hand to -the prince. - -"Good-by, my dear fellow.... His words are music, I never tire of -hearing him!" said the old prince, keeping hold of the hand and -offering his cheek to be kissed. - -Following Rostopchin's example the others also rose. - - - - - -CHAPTER IV - - -Princess Mary as she sat listening to the old men's talk and -faultfinding, understood nothing of what she heard; she only -wondered whether the guests had all observed her father's hostile -attitude toward her. She did not even notice the special attentions -and amiabilities shown her during dinner by Boris Drubetskoy, who -was visiting them for the third time already. - -Princess Mary turned with absent-minded questioning look to -Pierre, who hat in hand and with a smile on his face was the last of -the guests to approach her after the old prince had gone out and -they were left alone in the drawing room. - -"May I stay a little longer?" he said, letting his stout body sink -into an armchair beside her. - -"Oh yes," she answered. "You noticed nothing?" her look asked. - -Pierre was in an agreeable after-dinner mood. He looked straight -before him and smiled quietly. - -"Have you known that young man long, Princess?" he asked. - -"Who?" - -"Drubetskoy." - -"No, not long..." - -"Do you like him?" - -"Yes, he is an agreeable young man.... Why do you ask me that?" said -Princess Mary, still thinking of that morning's conversation with -her father. - -"Because I have noticed that when a young man comes on leave from -Petersburg to Moscow it is usually with the object of marrying an -heiress." - -"You have observed that?" said Princess Mary. - -"Yes," returned Pierre with a smile, "and this young man now manages -matters so that where there is a wealthy heiress there he is too. I -can read him like a book. At present he is hesitating whom to lay -siege to--you or Mademoiselle Julie Karagina. He is very attentive -to her." - -"He visits them?" - -"Yes, very often. And do you know the new way of courting?" said -Pierre with an amused smile, evidently in that cheerful mood of good -humored raillery for which he so often reproached himself in his -diary. - -"No," replied Princess Mary. - -"To please Moscow girls nowadays one has to be melancholy. He is -very melancholy with Mademoiselle Karagina," said Pierre. - -"Really?" asked Princess Mary, looking into Pierre's kindly face and -still thinking of her own sorrow. "It would be a relief," thought she, -"if I ventured to confide what I am feeling to someone. I should -like to tell everything to Pierre. He is kind and generous. It would -be a relief. He would give me advice." - -"Would you marry him?" - -"Oh, my God, Count, there are moments when I would marry anybody!" -she cried suddenly to her own surprise and with tears in her voice. -"Ah, how bitter it is to love someone near to you and to feel that..." -she went on in a trembling voice, "that you can do nothing for him but -grieve him, and to know that you cannot alter this. Then there is only -one thing left--to go away, but where could I go?" - -"What is wrong? What is it, Princess?" - -But without finishing what she was saying, Princess Mary burst -into tears. - -"I don't know what is the matter with me today. Don't take any -notice--forget what I have said!" - -Pierre's gaiety vanished completely. He anxiously questioned the -princess, asked her to speak out fully and confide her grief to him; -but she only repeated that she begged him to forget what she had said, -that she did not remember what she had said, and that she had no -trouble except the one he knew of--that Prince Andrew's marriage -threatened to cause a rupture between father and son. - -"Have you any news of the Rostovs?" she asked, to change the -subject. "I was told they are coming soon. I am also expecting -Andrew any day. I should like them to meet here." - -"And how does he now regard the matter?" asked Pierre, referring -to the old prince. - -Princess Mary shook her head. - -"What is to be done? In a few months the year will be up. The -thing is impossible. I only wish I could spare my brother the first -moments. I wish they would come sooner. I hope to be friends with her. -You have known them a long time," said Princess Mary. "Tell me -honestly the whole truth: what sort of girl is she, and what do you -think of her?--The real truth, because you know Andrew is risking so -much doing this against his father's will that I should like to -know..." - -An undefined instinct told Pierre that these explanations, and -repeated requests to be told the whole truth, expressed ill-will on -the princess' part toward her future sister-in-law and a wish that -he should disapprove of Andrew's choice; but in reply he said what -he felt rather than what he thought. - -"I don't know how to answer your question," he said, blushing -without knowing why. "I really don't know what sort of girl she is; -I can't analyze her at all. She is enchanting, but what makes her so I -don't know. That is all one can say about her." - -Princess Mary sighed, and the expression on her face said: "Yes, -that's what I expected and feared." - -"Is she clever?" she asked. - -Pierre considered. - -"I think not," he said, "and yet--yes. She does not deign to be -clever.... Oh no, she is simply enchanting, and that is all." - -Princess Mary again shook her head disapprovingly. - -"Ah, I so long to like her! Tell her so if you see her before I do." - -"I hear they are expected very soon," said Pierre. - -Princess Mary told Pierre of her plan to become intimate with her -future sister-in-law as soon as the Rostovs arrived and to try to -accustom the old prince to her. - - - - - -CHAPTER V - - -Boris had not succeeded in making a wealthy match in Petersburg, -so with the same object in view he came to Moscow. There he wavered -between the two richest heiresses, Julie and Princess Mary. Though -Princess Mary despite her plainness seemed to him more attractive than -Julie, he, without knowing why, felt awkward about paying court to -her. When they had last met on the old prince's name day, she had -answered at random all his attempts to talk sentimentally, evidently -not listening to what he was saying. - -Julie on the contrary accepted his attentions readily, though in a -manner peculiar to herself. - -She was twenty-seven. After the death of her brothers she had become -very wealthy. She was by now decidedly plain, but thought herself -not merely as good-looking as before but even far more attractive. She -was confirmed in this delusion by the fact that she had become a -very wealthy heiress and also by the fact that the older she grew -the less dangerous she became to men, and the more freely they could -associate with her and avail themselves of her suppers, soirees, and -the animated company that assembled at her house, without incurring -any obligation. A man who would have been afraid ten years before of -going every day to the house when there was a girl of seventeen there, -for fear of compromising her and committing himself, would now go -boldly every day and treat her not as a marriageable girl but as a -sexless acquaintance. - -That winter the Karagins' house was the most agreeable and -hospitable in Moscow. In addition to the formal evening and dinner -parties, a large company, chiefly of men, gathered there every day, -supping at midnight and staying till three in the morning. Julie never -missed a ball, a promenade, or a play. Her dresses were always of -the latest fashion. But in spite of that she seemed to be -disillusioned about everything and told everyone that she did not -believe either in friendship or in love, or any of the joys of life, -and expected peace only "yonder." She adopted the tone of one who -has suffered a great disappointment, like a girl who has either lost -the man she loved or been cruelly deceived by him. Though nothing of -the kind had happened to her she was regarded in that light, and had -even herself come to believe that she had suffered much in life. -This melancholy, which did not prevent her amusing herself, did not -hinder the young people who came to her house from passing the time -pleasantly. Every visitor who came to the house paid his tribute to -the melancholy mood of the hostess, and then amused himself with -society gossip, dancing, intellectual games, and bouts rimes, which -were in vogue at the Karagins'. Only a few of these young men, among -them Boris, entered more deeply into Julie's melancholy, and with -these she had prolonged conversations in private on the vanity of -all worldly things, and to them she showed her albums filled with -mournful sketches, maxims, and verses. - -To Boris, Julie was particularly gracious: she regretted his early -disillusionment with life, offered him such consolation of -friendship as she who had herself suffered so much could render, and -showed him her album. Boris sketched two trees in the album and wrote: -"Rustic trees, your dark branches shed gloom and melancholy upon me." - -On another page he drew a tomb, and wrote: - - La mort est secourable et la mort est tranquille. - Ah! contre les douleurs il n'y a pas d'autre asile.* - - -*Death gives relief and death is peaceful. - - Ah! from suffering there is no other refuge. - -Julia said this was charming - -"There is something so enchanting in the smile of melancholy," she -said to Boris, repeating word for word a passage she had copied from a -book. "It is a ray of light in the darkness, a shade between sadness -and despair, showing the possibility of consolation." - -In reply Boris wrote these lines: - - Aliment de poison d'une ame trop sensible, - Toi, sans qui le bonheur me serait impossible, - Tendre melancholie, ah, viens me consoler, - Viens calmer les tourments de ma sombre retraite, - Et mele une douceur secrete - A ces pleurs que je sens couler.* - - -*Poisonous nourishment of a too sensitive soul, - - Thou, without whom happiness would for me be impossible, - - Tender melancholy, ah, come to console me, - - Come to calm the torments of my gloomy retreat, - - And mingle a secret sweetness - - With these tears that I feel to be flowing. - - -For Boris, Julie played most doleful nocturnes on her harp. Boris -read Poor Liza aloud to her, and more than once interrupted the -reading because of the emotions that choked him. Meeting at large -gatherings Julie and Boris looked on one another as the only souls who -understood one another in a world of indifferent people. - -Anna Mikhaylovna, who often visited the Karagins, while playing -cards with the mother made careful inquiries as to Julie's dowry -(she was to have two estates in Penza and the Nizhegorod forests). -Anna Mikhaylovna regarded the refined sadness that united her son to -the wealthy Julie with emotion, and resignation to the Divine will. - -"You are always charming and melancholy, my dear Julie," she said to -the daughter. "Boris says his soul finds repose at your house. He -has suffered so many disappointments and is so sensitive," said she to -the mother. "Ah, my dear, I can't tell you how fond I have grown of -Julie latterly," she said to her son. "But who could help loving -her? She is an angelic being! Ah, Boris, Boris!"--she paused. "And how -I pity her mother," she went on; "today she showed me her accounts and -letters from Penza (they have enormous estates there), and she, poor -thing, has no one to help her, and they do cheat her so!" - -Boris smiled almost imperceptibly while listening to his mother. -He laughed blandly at her naive diplomacy but listened to what she had -to say, and sometimes questioned her carefully about the Penza and -Nizhegorod estates. - -Julie had long been expecting a proposal from her melancholy -adorer and was ready to accept it; but some secret feeling of -repulsion for her, for her passionate desire to get married, for her -artificiality, and a feeling of horror at renouncing the possibility -of real love still restrained Boris. His leave was expiring. He -spent every day and whole days at the Karagins', and every day on -thinking the matter over told himself that he would propose -tomorrow. But in Julie's presence, looking at her red face and chin -(nearly always powdered), her moist eyes, and her expression of -continual readiness to pass at once from melancholy to an unnatural -rapture of married bliss, Boris could not utter the decisive words, -though in imagination he had long regarded himself as the possessor of -those Penza and Nizhegorod estates and had apportioned the use of -the income from them. Julie saw Boris' indecision, and sometimes the -thought occurred to her that she was repulsive to him, but her -feminine self-deception immediately supplied her with consolation, and -she told herself that he was only shy from love. Her melancholy, -however, began to turn to irritability, and not long before Boris' -departure she formed a definite plan of action. Just as Boris' leave -of absence was expiring, Anatole Kuragin made his appearance in -Moscow, and of course in the Karagins' drawing room, and Julie, -suddenly abandoning her melancholy, became cheerful and very attentive -to Kuragin. - -"My dear," said Anna Mikhaylovna to her son, "I know from a reliable -source that Prince Vasili has sent his son to Moscow to get him -married to Julie. I am so fond of Julie that I should be sorry for -her. What do you think of it, my dear?" - -The idea of being made a fool of and of having thrown away that -whole month of arduous melancholy service to Julie, and of seeing -all the revenue from the Penza estates which he had already mentally -apportioned and put to proper use fall into the hands of another, -and especially into the hands of that idiot Anatole, pained Boris. -He drove to the Karagins' with the firm intention of proposing. -Julie met him in a gay, careless manner, spoke casually of how she had -enjoyed yesterday's ball, and asked when he was leaving. Though -Boris had come intentionally to speak of his love and therefore -meant to be tender, he began speaking irritably of feminine -inconstancy, of how easily women can turn from sadness to joy, and how -their moods depend solely on who happens to be paying court to them. -Julie was offended and replied that it was true that a woman needs -variety, and the same thing over and over again would weary anyone. - -"Then I should advise you..." Boris began, wishing to sting her; but -at that instant the galling thought occurred to him that he might have -to leave Moscow without having accomplished his aim, and have vainly -wasted his efforts--which was a thing he never allowed to happen. - -He checked himself in the middle of the sentence, lowered his eyes -to avoid seeing her unpleasantly irritated and irresolute face, and -said: - -"I did not come here at all to quarrel with you. On the contrary..." - -He glanced at her to make sure that he might go on. Her irritability -had suddenly quite vanished, and her anxious, imploring eyes were -fixed on him with greedy expectation. "I can always arrange so as -not to see her often," thought Boris. "The affair has been begun and -must be finished!" He blushed hotly, raised his eyes to hers, and -said: - -"You know my feelings for you!" - -There was no need to say more: Julie's face shone with triumph and -self-satisfaction; but she forced Boris to say all that is said on -such occasions--that he loved her and had never loved any other -woman more than her. She knew that for the Penza estates and -Nizhegorod forests she could demand this, and she received what she -demanded. - -The affianced couple, no longer alluding to trees that shed gloom -and melancholy upon them, planned the arrangements of a splendid house -in Petersburg, paid calls, and prepared everything for a brilliant -wedding. - - - - - -CHAPTER VI - - -At the end of January old Count Rostov went to Moscow with Natasha -and Sonya. The countess was still unwell and unable to travel but it -was impossible to wait for her recovery. Prince Andrew was expected in -Moscow any day, the trousseau had to be ordered and the estate near -Moscow had to be sold, besides which the opportunity of presenting his -future daughter-in-law to old Prince Bolkonski while he was in -Moscow could not be missed. The Rostovs' Moscow house had not been -heated that winter and, as they had come only for a short time and the -countess was not with them, the count decided to stay with Marya -Dmitrievna Akhrosimova, who had long been pressing her hospitality -on them. - -Late one evening the Rostovs' four sleighs drove into Marya -Dmitrievna's courtyard in the old Konyusheny street. Marya -Dmitrievna lived alone. She had already married off her daughter, -and her sons were all in the service. - -She held herself as erect, told everyone her opinion as candidly, -loudly, and bluntly as ever, and her whole bearing seemed a reproach -to others for any weakness, passion, or temptation--the possibility of -which she did not admit. From early in the morning, wearing a dressing -jacket, she attended to her household affairs, and then she drove out: -on holy days to church and after the service to jails and prisons on -affairs of which she never spoke to anyone. On ordinary days, after -dressing, she received petitioners of various classes, of whom there -were always some. Then she had dinner, a substantial and appetizing -meal at which there were always three or four guests; after dinner she -played a game of boston, and at night she had the newspapers or a -new book read to her while she knitted. She rarely made an exception -and went out to pay visits, and then only to the most important -persons in the town. - -She had not yet gone to bed when the Rostovs arrived and the -pulley of the hall door squeaked from the cold as it let in the -Rostovs and their servants. Marya Dmitrievna, with her spectacles -hanging down on her nose and her head flung back, stood in the hall -doorway looking with a stern, grim face at the new arrivals. One might -have thought she was angry with the travelers and would immediately -turn them out, had she not at the same time been giving careful -instructions to the servants for the accommodation of the visitors and -their belongings. - -"The count's things? Bring them here," she said, pointing to the -portmanteaus and not greeting anyone. "The young ladies'? There to the -left. Now what are you dawdling for?" she cried to the maids. "Get the -samovar ready!... You've grown plumper and prettier," she remarked, -drawing Natasha (whose cheeks were glowing from the cold) to her by -the hood. "Foo! You are cold! Now take off your things, quick!" she -shouted to the count who was going to kiss her hand. "You're half -frozen, I'm sure! Bring some rum for tea!... Bonjour, Sonya dear!" she -added, turning to Sonya and indicating by this French greeting her -slightly contemptuous though affectionate attitude toward her. - -When they came in to tea, having taken off their outdoor things -and tidied themselves up after their journey, Marya Dmitrievna -kissed them all in due order. - -"I'm heartily glad you have come and are staying with me. It was -high time," she said, giving Natasha a significant look. "The old -man is here and his son's expected any day. You'll have to make his -acquaintance. But we'll speak of that later on," she added, glancing at -Sonya with a look that showed she did not want to speak of it in her -presence. "Now listen," she said to the count. "What do you want -tomorrow? Whom will you send for? Shinshin?" she crooked one of her -fingers. "The sniveling Anna Mikhaylovna? That's two. She's here -with her son. The son is getting married! Then Bezukhov, eh? He is -here too, with his wife. He ran away from her and she came galloping -after him. He dined with me on Wednesday. As for them"--and she -pointed to the girls--"tomorrow I'll take them first to the Iberian -shrine of the Mother of God, and then we'll drive to the -Super-Rogue's. I suppose you'll have everything new. Don't judge by -me: sleeves nowadays are this size! The other day young Princess Irina -Vasilevna came to see me; she was an awful sight--looked as if she had -put two barrels on her arms. You know not a day passes now without -some new fashion.... And what have you to do yourself?" she asked -the count sternly. - -"One thing has come on top of another: her rags to buy, and now a -purchaser has turned up for the Moscow estate and for the house. If -you will be so kind, I'll fix a time and go down to the estate just -for a day, and leave my lassies with you." - -"All right. All right. They'll be safe with me, as safe as in -Chancery! I'll take them where they must go, scold them a bit, and pet -them a bit," said Marya Dmitrievna, touching her goddaughter and -favorite, Natasha, on the cheek with her large hand. - -Next morning Marya Dmitrievna took the young ladies to the Iberian -shrine of the Mother of God and to Madame Suppert-Roguet, who was so -afraid of Marya Dmitrievna that she always let her have costumes at -a loss merely to get rid of her. Marya Dmitrievna ordered almost the -whole trousseau. When they got home she turned everybody out of the -room except Nataisha, and then called her pet to her armchair. - -"Well, now we'll talk. I congratulate you on your betrothed. -You've hooked a fine fellow! I am glad for your sake and I've known -him since he was so high." She held her hand a couple of feet from the -ground. Natasha blushed happily. "I like him and all his family. Now -listen! You know that old Prince Nicholas much dislikes his son's -marrying. The old fellow's crotchety! Of course Prince Andrew is not a -child and can shift without him, but it's not nice to enter a family -against a father's will. One wants to do it peacefully and lovingly. -You're a clever girl and you'll know how to manage. Be kind, and use -your wits. Then all will be well." - -Natasha remained silent, from shyness Marya Dmitrievna supposed, but -really because she disliked anyone interfering in what touched her -love of Prince Andrew, which seemed to her so apart from all human -affairs that no one could understand it. She loved and knew Prince -Andrew, he loved her only, and was to come one of these days and -take her. She wanted nothing more. - -"You see I have known him a long time and am also fond of Mary, your -future sister-in-law. 'Husbands' sisters bring up blisters,' but -this one wouldn't hurt a fly. She has asked me to bring you two -together. Tomorrow you'll go with your father to see her. Be very nice -and affectionate to her: you're younger than she. When he comes, he'll -find you already know his sister and father and are liked by them. -Am I right or not? Won't that be best?" - -"Yes, it will," Natasha answered reluctantly. - - - - - -CHAPTER VII - - -Next day, by Marya Dmitrievna's advice, Count Rostov took Natasha to -call on Prince Nicholas Bolkonski. The count did not set out -cheerfully on this visit, at heart he felt afraid. He well -remembered the last interview he had had with the old prince at the -time of the enrollment, when in reply to an invitation to dinner he -had had to listen to an angry reprimand for not having provided his -full quota of men. Natasha, on the other hand, having put on her -best gown, was in the highest spirits. "They can't help liking me," -she thought. "Everybody always has liked me, and I am so willing to do -anything they wish, so ready to be fond of him--for being his -father--and of her--for being his sister--that there is no reason -for them not to like me..." - -They drove up to the gloomy old house on the Vozdvizhenka and -entered the vestibule. - -"Well, the Lord have mercy on us!" said the count, half in jest, -half in earnest; but Natasha noticed that her father was flurried on -entering the anteroom and inquired timidly and softly whether the -prince and princess were at home. - -When they had been announced a perturbation was noticeable among the -servants. The footman who had gone to announce them was stopped by -another in the large hall and they whispered to one another. Then a -maidservant ran into the hall and hurriedly said something, mentioning -the princess. At last an old, cross looking footman came and announced -to the Rostovs that the prince was not receiving, but that the -princess begged them to walk up. The first person who came to meet the -visitors was Mademoiselle Bourienne. She greeted the father and -daughter with special politeness and showed them to the princess' -room. The princess, looking excited and nervous, her face flushed in -patches, ran in to meet the visitors, treading heavily, and vainly -trying to appear cordial and at ease. From the first glance Princess -Mary did not like Natasha. She thought her too fashionably dressed, -frivolously gay and vain. She did not at all realize that before -having seen her future sister-in-law she was prejudiced against her by -involuntary envy of her beauty, youth, and happiness, as well as by -jealousy of her brother's love for her. Apart from this insuperable -antipathy to her, Princess Mary was agitated just then because on -the Rostovs' being announced, the old prince had shouted that he did -not wish to see them, that Princess Mary might do so if she chose, but -they were not to be admitted to him. She had decided to receive -them, but feared lest the prince might at any moment indulge in some -freak, as he seemed much upset by the Rostovs' visit. - -"There, my dear princess, I've brought you my songstress," said -the count, bowing and looking round uneasily as if afraid the old -prince might appear. "I am so glad you should get to know one -another... very sorry the prince is still ailing," and after a few -more commonplace remarks he rose. "If you'll allow me to leave my -Natasha in your hands for a quarter of an hour, Princess, I'll drive -round to see Anna Semenovna, it's quite near in the Dogs' Square, -and then I'll come back for her." - -The count had devised this diplomatic ruse (as he afterwards told -his daughter) to give the future sisters-in-law an opportunity to talk -to one another freely, but another motive was to avoid the danger of -encountering the old prince, of whom he was afraid. He did not mention -this to his daughter, but Natasha noticed her father's nervousness and -anxiety and felt mortified by it. She blushed for him, grew still -angrier at having blushed, and looked at the princess with a bold -and defiant expression which said that she was not afraid of -anybody. The princess told the count that she would be delighted, -and only begged him to stay longer at Anna Semenovna's, and he -departed. - -Despite the uneasy glances thrown at her by Princess Mary--who -wished to have a tete-a-tete with Natasha--Mademoiselle Bourienne -remained in the room and persistently talked about Moscow amusements -and theaters. Natasha felt offended by the hesitation she had -noticed in the anteroom, by her father's nervousness, and by the -unnatural manner of the princess who--she thought--was making a -favor of receiving her, and so everything displeased her. She did -not like Princess Mary, whom she thought very plain, affected, and -dry. Natasha suddenly shrank into herself and involuntarily assumed an -offhand air which alienated Princess Mary still more. After five -minutes of irksome, constrained conversation, they heard the sound -of slippered feet rapidly approaching. Princess Mary looked -frightened. - -The door opened and the old prince, in a dress, ing gown and a white -nightcap, came in. - -"Ah, madam!" he began. "Madam, Countess... Countess Rostova, if I am -not mistaken... I beg you to excuse me, to excuse me... I did not -know, madam. God is my witness, I did not know you had honored us with -a visit, and I came in such a costume only to see my daughter. I beg -you to excuse me... God is my witness, I didn't know-" he repeated, -stressing the word "God" so unnaturally and so unpleasantly that -Princess Mary stood with downcast eyes not daring to look either at -her father or at Natasha. - -Nor did the latter, having risen and curtsied, know what to do. -Mademoiselle Bourienne alone smiled agreeably. - -"I beg you to excuse me, excuse me! God is my witness, I did not -know," muttered the old man, and after looking Natasha over from -head to foot he went out. - -Mademoiselle Bourienne was the first to recover herself after this -apparition and began speaking about the prince's indisposition. -Natasha and Princess Mary looked at one another in silence, and the -longer they did so without saying what they wanted to say, the greater -grew their antipathy to one another. - -When the count returned, Natasha was impolitely pleased and hastened -to get away: at that moment she hated the stiff, elderly princess, who -could place her in such an embarrassing position and had spent half an -hour with her without once mentioning Prince Andrew. "I couldn't begin -talking about him in the presence of that Frenchwoman," thought -Natasha. The same thought was meanwhile tormenting Princess Mary. -She knew what she ought to have said to Natasha, but she had been -unable to say it because Mademoiselle Bourienne was in the way, and -because, without knowing why, she felt it very difficult to speak of -the marriage. When the count was already leaving the room, Princess -Mary went up hurriedly to Natasha, took her by the hand, and said with -a deep sigh: - -"Wait, I must..." - -Natasha glanced at her ironically without knowing why. - -"Dear Natalie," said Princess Mary, "I want you to know that I am -glad my brother has found happiness...." - -She paused, feeling that she was not telling the truth. Natasha -noticed this and guessed its reason. - -"I think, Princess, it is not convenient to speak of that now," -she said with external dignity and coldness, though she felt the tears -choking her. - -"What have I said and what have I done?" thought she, as soon as she -was out of the room. - -They waited a long time for Natasha to come to dinner that day. -She sat in her room crying like a child, blowing her nose and sobbing. -Sonya stood beside her, kissing her hair. - -"Natasha, what is it about?" she asked. "What do they matter to you? -It will all pass, Natasha." - -"But if you only knew how offensive it was... as if I..." - -"Don't talk about it, Natasha. It wasn't your fault so why should -you mind? Kiss me," said Sonya. - -Natasha raised her head and, kissing her friend on the lips, pressed -her wet face against her. - -"I can't tell you, I don't know. No one's to blame," said Natasha- -"It's my fault. But it all hurts terribly. Oh, why doesn't he -come?..." - -She came in to dinner with red eyes. Marya Dmitrievna, who knew -how the prince had received the Rostovs, pretended not to notice how -upset Natasha was and jested resolutely and loudly at table with the -count and the other guests. - - - - - -CHAPTER VIII - - -That evening the Rostovs went to the Opera, for which Marya -Dmitrievna had taken a box. - -Natasha did not want to go, but could not refuse Marya -Dmitrievna's kind offer which was intended expressly for her. When she -came ready dressed into the ballroom to await her father, and -looking in the large mirror there saw that she was pretty, very -pretty, she felt even more sad, but it was a sweet, tender sadness. - -"O God, if he were here now I would not behave as I did then, but -differently. I would not be silly and afraid of things, I would simply -embrace him, cling to him, and make him look at me with those -searching inquiring eyes with which he has so often looked at me, -and then I would make him laugh as he used to laugh. And his eyes--how -I see those eyes!" thought Natasha. "And what do his father and sister -matter to me? I love him alone, him, him, with that face and those -eyes, with his smile, manly and yet childlike.... No, I had better not -think of him; not think of him but forget him, quite forget him for -the present. I can't bear this waiting and I shall cry in a minute!" -and she turned away from the glass, making an effort not to cry. -"And how can Sonya love Nicholas so calmly and quietly and wait so -long and so patiently?" thought she, looking at Sonya, who also came -in quite ready, with a fan in her hand. "No, she's altogether -different. I can't!" - -Natasha at that moment felt so softened and tender that it was not -enough for her to love and know she was beloved, she wanted now, at -once, to embrace the man she loved, to speak and hear from him words -of love such as filled her heart. While she sat in the carriage beside -her father, pensively watching the lights of the street lamps -flickering on the frozen window, she felt still sadder and more in -love, and forgot where she was going and with whom. Having fallen into -the line of carriages, the Rostovs' carriage drove up to the -theater, its wheels squeaking over the snow. Natasha and Sonya, -holding up their dresses, jumped out quickly. The count got out helped -by the footmen, and, passing among men and women who were entering and -the program sellers, they all three went along the corridor to the -first row of boxes. Through the closed doors the music was already -audible. - -"Natasha, your hair!..." whispered Sonya. - -An attendant deferentially and quickly slipped before the ladies and -opened the door of their box. The music sounded louder and through the -door rows of brightly lit boxes in which ladies sat with bare arms and -shoulders, and noisy stalls brilliant with uniforms, glittered -before their eyes. A lady entering the next box shot a glance of -feminine envy at Natasha. The curtain had not yet risen and the -overture was being played. Natasha, smoothing her gown, went in with -Sonya and sat down, scanning the brilliant tiers of boxes opposite. -A sensation she had not experienced for a long time--that of -hundreds of eyes looking at her bare arms and neck--suddenly -affected her both agreeably and disagreeably and called up a whole -crowd of memories, desires and emotions associated with that feeling. - -The two remarkably pretty girls, Natasha and Sonya, with Count -Rostov who had not been seen in Moscow for a long time, attracted -general attention. Moreover, everybody knew vaguely of Natasha's -engagement to Prince Andrew, and knew that the Rostovs had lived in -the country ever since, and all looked with curiosity at a fiancee who -was making one of the best matches in Russia. - -Natasha's looks, as everyone told her, had improved in the -country, and that evening thanks to her agitation she was particularly -pretty. She struck those who saw her by her fullness of life and -beauty, combined with her indifference to everything about her. Her -black eyes looked at the crowd without seeking anyone, and her -delicate arm, bare to above the elbow, lay on the velvet edge of the -box, while, evidently unconsciously, she opened and closed her hand in -time to the music, crumpling her program. "Look, there's Alenina," -said Sonya, "with her mother, isn't it?" - -"Dear me, Michael Kirilovich has grown still stouter!" remarked -the count. - -"Look at our Anna Mikhaylovna--what a headdress she has on!" - -"The Karagins, Julie--and Boris with them. One can see at once -that they're engaged...." - -"Drubetskoy has proposed?" - -"Oh yes, I heard it today," said Shinshin, coming into the -Rostovs' box. - -Natasha looked in the direction in which her father's eyes were -turned and saw Julie sitting beside her mother with a happy look on -her face and a string of pearls round her thick red neck--which -Natasha knew was covered with powder. Behind them, wearing a smile and -leaning over with an ear to Julie's mouth, was Boris' handsome -smoothly brushed head. He looked the Rostovs from under his brows -and said something, smiling, to his betrothed. - -"They are talking about us, about me and him!" thought Natasha. "And -he no doubt is calming her jealousy of me. They needn't trouble -themselves! If only they knew how little I am concerned about any of -them." - -Behind them sat Anna Mikhaylovna wearing a green headdress and -with a happy look of resignation to the will of God on her face. Their -box was pervaded by that atmosphere of an affianced couple which -Natasha knew so well and liked so much. She turned away and suddenly -remembered all that had been so humiliating in her morning's visit. - -"What right has he not to wish to receive me into his family? Oh, -better not think of it--not till he comes back!" she told herself, and -began looking at the faces, some strange and some familiar, in the -stalls. In the front, in the very center, leaning back against the -orchestra rail, stood Dolokhov in a Persian dress, his curly hair -brushed up into a huge shock. He stood in full view of the audience, -well aware that he was attracting everyone's attention, yet as much at -ease as though he were in his own room. Around him thronged Moscow's -most brilliant young men, whom he evidently dominated. - -The count, laughing, nudged the blushing Sonya and pointed to her -former adorer. - -"Do you recognize him?" said he. "And where has he sprung from?" -he asked, turning to Shinshin. "Didn't he vanish somewhere?" - -"He did," replied Shinshin. "He was in the Caucasus and ran away -from there. They say he has been acting as minister to some ruling -prince in Persia, where he killed the Shah's brother. Now all the -Moscow ladies are mad about him! It's 'Dolokhov the Persian' that does -it! We never hear a word but Dolokhov is mentioned. They swear by him, -they offer him to you as they would a dish of choice sterlet. Dolokhov -and Anatole Kuragin have turned all our ladies' heads." - -A tall, beautiful woman with a mass of plaited hair and much exposed -plump white shoulders and neck, round which she wore a double string -of large pearls, entered the adjoining box rustling her heavy silk -dress and took a long time settling into her place. - -Natasha involuntarily gazed at that neck, those shoulders, and -pearls and coiffure, and admired the beauty of the shoulders and the -pearls. While Natasha was fixing her gaze on her for the second time -the lady looked round and, meeting the count's eyes, nodded to him and -smiled. She was the Countess Bezukhova, Pierre's wife, and the -count, who knew everyone in society, leaned over and spoke to her. - -"Have you been here long, Countess?" he inquired. "I'll call, I'll -call to kiss your hand. I'm here on business and have brought my girls -with me. They say Semenova acts marvelously. Count Pierre never used -to forget us. Is he here?" - -"Yes, he meant to look in," answered Helene, and glanced attentively -at Natasha. - -Count Rostov resumed his seat. - -"Handsome, isn't she?" he whispered to Natasha. - -"Wonderful!" answered Natasha. "She's a woman one could easily -fall in love with." - -Just then the last chords of the overture were heard and the -conductor tapped with his stick. Some latecomers took their seats in -the stalls, and the curtain rose. - -As soon as it rose everyone in the boxes and stalls became silent, -and all the men, old and young, in uniform and evening dress, and -all the women with gems on their bare flesh, turned their whole -attention with eager curiosity to the stage. Natasha too began to look -at it. - - - - - -CHAPTER IX - - -The floor of the stage consisted of smooth boards, at the sides -was some painted cardboard representing trees, and at the back was a -cloth stretched over boards. In the center of the stage sat some girls -in red bodices and white skirts. One very fat girl in a white silk -dress sat apart on a low bench, to the back of which a piece of -green cardboard was glued. They all sang something. When they had -finished their song the girl in white went up to the prompter's box -and a man with tight silk trousers over his stout legs, and holding -a plume and a dagger, went up to her and began singing, waving his -arms about. - -First the man in the tight trousers sang alone, then she sang, -then they both paused while the orchestra played and the man -fingered the hand of the girl in white, obviously awaiting the beat to -start singing with her. They sang together and everyone in the theater -began clapping and shouting, while the man and woman on the stage--who -represented lovers--began smiling, spreading out their arms, and -bowing. - -After her life in the country, and in her present serious mood, -all this seemed grotesque and amazing to Natasha. She could not follow -the opera nor even listen to the music; she saw only the painted -cardboard and the queerly dressed men and women who moved, spoke, -and sang so strangely in that brilliant light. She knew what it was -all meant to represent, but it was so pretentiously false and -unnatural that she first felt ashamed for the actors and then amused -at them. She looked at the faces of the audience, seeking in them -the same sense of ridicule and perplexity she herself experienced, but -they all seemed attentive to what was happening on the stage, and -expressed delight which to Natasha seemed feigned. "I suppose it has -to be like this!" she thought. She kept looking round in turn at the -rows of pomaded heads in the stalls and then at the seminude women -in the boxes, especially at Helene in the next box, who--apparently -quite unclothed--sat with a quiet tranquil smile, not taking her -eyes off the stage. And feeling the bright light that flooded the -whole place and the warm air heated by the crowd, Natasha little by -little began to pass into a state of intoxication she had not -experienced for a long while. She did not realize who and where she -was, nor what was going on before her. As she looked and thought, -the strangest fancies unexpectedly and disconnectedly passed through -her mind: the idea occurred to her of jumping onto the edge of the box -and singing the air the actress was singing, then she wished to -touch with her fan an old gentleman sitting not far from her, then -to lean over to Helene and tickle her. - -At a moment when all was quiet before the commencement of a song, -a door leading to the stalls on the side nearest the Rostovs' box -creaked, and the steps of a belated arrival were heard. "There's -Kuragin!" whispered Shinshin. Countess Bezukhova turned smiling to the -newcomer, and Natasha, following the direction of that look, saw an -exceptionally handsome adjutant approaching their box with a -self-assured yet courteous bearing. This was Anatole Kuragin whom -she had seen and noticed long ago at the ball in Petersburg. He was -now in an adjutant's uniform with one epaulet and a shoulder knot. -He moved with a restrained swagger which would have been ridiculous -had he not been so good-looking and had his handsome face not worn -such an expression of good-humored complacency and gaiety. Though -the performance was proceeding, he walked deliberately down the -carpeted gangway, his sword and spurs slightly jingling and his -handsome perfumed head held high. Having looked at Natasha he -approached his sister, laid his well gloved hand on the edge of her -box, nodded to her, and leaning forward asked a question, with a -motion toward Natasha. - -"Mais charmante!" said he, evidently referring to Natasha, who did -not exactly hear his words but understood them from the movement of -his lips. Then he took his place in the first row of the stalls and -sat down beside Dolokhov, nudging with his elbow in a friendly and -offhand way that Dolokhov whom others treated so fawningly. He -winked at him gaily, smiled, and rested his foot against the orchestra -screen. - -"How like the brother is to the sister," remarked the count. "And -how handsome they both are!" - -Shinshin, lowering his voice, began to tell the count of some -intrigue of Kuragin's in Moscow, and Natasha tried to overhear it just -because he had said she was "charmante." - -The first act was over. In the stalls everyone began moving about, -going out and coming in. - -Boris came to the Rostovs' box, received their congratulations -very simply, and raising his eyebrows with an absent-minded smile -conveyed to Natasha and Sonya his fiancee's invitation to her wedding, -and went away. Natasha with a gay, coquettish smile talked to him, and -congratulated on his approaching wedding that same Boris with whom she -had formerly been in love. In the state of intoxication she was in, -everything seemed simple and natural. - -The scantily clad Helene smiled at everyone in the same way, and -Natasha gave Boris a similar smile. - -Helene's box was filled and surrounded from the stalls by the most -distinguished and intellectual men, who seemed to vie with one another -in their wish to let everyone see that they knew her. - -During the whole of that entr'acte Kuragin stood with Dolokhov in -front of the orchestra partition, looking at the Rostovs' box. Natasha -knew he was talking about her and this afforded her pleasure. She even -turned so that he should see her profile in what she thought was its -most becoming aspect. Before the beginning of the second act Pierre -appeared in the stalls. The Rostovs had not seen him since their -arrival. His face looked sad, and he had grown still stouter since -Natasha last saw him. He passed up to the front rows, not noticing -anyone. Anatole went up to him and began speaking to him, looking at -and indicating the Rostovs' box. On seeing Natasha Pierre grew -animated and, hastily passing between the rows, came toward their box. -When he got there he leaned on his elbows and, smiling, talked to -her for a long time. While conversing with Pierre, Natasha heard a -man's voice in Countess Bezukhova's box and something told her it -was Kuragin. She turned and their eyes met. Almost smiling, he gazed -straight into her eyes with such an enraptured caressing look that -it seemed strange to be so near him, to look at him like that, to be -so sure he admired her, and not to be acquainted with him. - -In the second act there was scenery representing tombstones, there -was a round hole in the canvas to represent the moon, shades were -raised over the footlights, and from horns and contrabass came deep -notes while many people appeared from right and left wearing black -cloaks and holding things like daggers in their hands. They began -waving their arms. Then some other people ran in and began dragging -away the maiden who had been in white and was now in light blue. -They did not drag her away at once, but sang with her for a long -time and then at last dragged her off, and behind the scenes something -metallic was struck three times and everyone knelt down and sang a -prayer. All these things were repeatedly interrupted by the -enthusiastic shouts of the audience. - -During this act every time Natasha looked toward the stalls she -saw Anatole Kuragin with an arm thrown across the back of his chair, -staring at her. She was pleased to see that he was captivated by her -and it did not occur to her that there was anything wrong in it. - -When the second act was over Countess Bezukhova rose, turned to -the Rostovs' box--her whole bosom completely exposed--beckoned the old -count with a gloved finger, and paying no attention to those who had -entered her box began talking to him with an amiable smile. - -"Do make me acquainted with your charming daughters," said she. "The -whole town is singing their praises and I don't even know then!" - -Natasha rose and curtsied to the splendid countess. She was so -pleased by praise from this brilliant beauty that she blushed with -pleasure. - -"I want to become a Moscovite too, now," said Helene. "How is it -you're not ashamed to bury such pearls in the country?" - -Countess Bezukhova quite deserved her reputation of being a -fascinating woman. She could say what she did not think--especially -what was flattering--quite simply and naturally. - -"Dear count, you must let me look after your daughters! Though I -am not staying here long this time--nor are you--I will try to amuse -them. I have already heard much of you in Petersburg and wanted to get -to know you," said she to Natasha with her stereotyped and lovely -smile. "I had heard about you from my page, Drubetskoy. Have you heard -he is getting married? And also from my husband's friend Bolkonski, -Prince Andrew Bolkonski," she went on with special emphasis, -implying that she knew of his relation to Natasha. To get better -acquainted she asked that one of the young ladies should come into her -box for the rest of the performance, and Natasha moved over to it. - -The scene of the third act represented a palace in which many -candles were burning and pictures of knights with short beards hung on -the walls. In the middle stood what were probably a king and a -queen. The king waved his right arm and, evidently nervous, sang -something badly and sat down on a crimson throne. The maiden who had -been first in white and then in light blue, now wore only a smock, and -stood beside the throne with her hair down. She sang something -mournfully, addressing the queen, but the king waved his arm severely, -and men and women with bare legs came in from both sides and began -dancing all together. Then the violins played very shrilly and merrily -and one of the women with thick bare legs and thin arms, separating -from the others, went behind the wings, adjusted her bodice, -returned to the middle of the stage, and began jumping and striking -one foot rapidly against the other. In the stalls everyone clapped and -shouted "bravo!" Then one of the men went into a corner of the -stage. The cymbals and horns in the orchestra struck up more loudly, -and this man with bare legs jumped very high and waved his feet -about very rapidly. (He was Duport, who received sixty thousand rubles -a year for this art.) Everybody in the stalls, boxes, and galleries -began clapping and shouting with all their might, and the man -stopped and began smiling and bowing to all sides. Then other men -and women danced with bare legs. Then the king again shouted to the -sound of music, and they all began singing. But suddenly a storm -came on, chromatic scales and diminished sevenths were heard in the -orchestra, everyone ran off, again dragging one of their number -away, and the curtain dropped. Once more there was a terrible noise -and clatter among the audience, and with rapturous faces everyone -began shouting: "Duport! Duport! Duport!" Natasha no longer thought -this strange. She look about with pleasure, smiling joyfully. - -"Isn't Duport delightful?" Helene asked her. - -"Oh, yes," replied Natasha. - - - - - -CHAPTER X - - -During the entr'acte a whiff of cold air came into Helene's box, the -door opened, and Anatole entered, stooping and trying not to brush -against anyone. - -"Let me introduce my brother to you," said Helene, her eyes shifting -uneasily from Natasha to Anatole. - -Natasha turned her pretty little head toward the elegant young -officer and smiled at him over her bare shoulder. Anatole, who was -as handsome at close quarters as at a distance, sat down beside her -and told her he had long wished to have this happiness--ever since the -Naryshkins' ball in fact, at which he had had the well-remembered -pleasure of seeing her. Kuragin was much more sensible and simple with -women than among men. He talked boldly and naturally, and Natasha -was strangely and agreeably struck by the fact that there was -nothing formidable in this man about whom there was so much talk, -but that on the contrary his smile was most naive, cheerful, and -good-natured. - -Kuragin asked her opinion of the performance and told her how at a -previous performance Semenova had fallen down on the stage. - -"And do you know, Countess," he said, suddenly addressing her as -an old, familiar acquaintance, "we are getting up a costume -tournament; you ought to take part in it! It will be great fun. We -shall all meet at the Karagins'! Please come! No! Really, eh?" said -he. - -While saying this he never removed his smiling eyes from her face, -her neck, and her bare arms. Natasha knew for certain that he was -enraptured by her. This pleased her, yet his presence made her feel -constrained and oppressed. When she was not looking at him she felt -that he was looking at her shoulders, and she involuntarily caught his -eye so that he should look into hers rather than this. But looking -into his eyes she was frightened, realizing that there was not that -barrier of modesty she had always felt between herself and other -men. She did not know how it was that within five minutes she had come -to feel herself terribly near to this man. When she turned away she -feared he might seize her from behind by her bare arm and kiss her -on the neck. They spoke of most ordinary things, yet she felt that -they were closer to one another than she had ever been to any man. -Natasha kept turning to Helene and to her father, as if asking what it -all meant, but Helene was engaged in conversation with a general and -did not answer her look, and her father's eyes said nothing but what -they always said: "Having a good time? Well, I'm glad of it!" - -During one of these moments of awkward silence when Anatole's -prominent eyes were gazing calmly and fixedly at her, Natasha, to -break the silence, asked him how he liked Moscow. She asked the -question and blushed. She felt all the time that by talking to him she -was doing something improper. Anatole smiled as though to encourage -her. - -"At first I did not like it much, because what makes a town pleasant -ce sont les jolies femmes,* isn't that so? But now I like it very much -indeed," he said, looking at her significantly. "You'll come to the -costume tournament, Countess? Do come!" and putting out his hand to -her bouquet and dropping his voice, he added, "You will be the -prettiest there. Do come, dear countess, and give me this flower as -a pledge!" - - -*Are the pretty women. - - -Natasha did not understand what he was saying any more than he did -himself, but she felt that his incomprehensible words had an -improper intention. She did not know what to say and turned away as if -she had not heard his remark. But as soon as she had turned away she -felt that he was there, behind, so close behind her. - -"How is he now? Confused? Angry? Ought I to put it right?" she asked -herself, and she could not refrain from turning round. She looked -straight into his eyes, and his nearness, self-assurance, and the -good-natured tenderness of his smile vanquished her. She smiled just -as he was doing, gazing straight into his eyes. And again she felt -with horror that no barrier lay between him and her. - -The curtain rose again. Anatole left the box, serene and gay. -Natasha went back to her father in the other box, now quite submissive -to the world she found herself in. All that was going on before her -now seemed quite natural, but on the other hand all her previous -thoughts of her betrothed, of Princess Mary, or of life in the country -did not once recur to her mind and were as if belonging to a remote -past. - -In the fourth act there was some sort of devil who sang waving his -arm about, till the boards were withdrawn from under him and he -disappeared down below. That was the only part of the fourth act -that Natasha saw. She felt agitated and tormented, and the cause of -this was Kuragin whom she could not help watching. As they were -leaving the theater Anatole came up to them, called their carriage, -and helped them in. As he was putting Natasha in he pressed her arm -above the elbow. Agitated and flushed she turned round. He was looking -at her with glittering eyes, smiling tenderly. - - -Only after she had reached home was Natasha able clearly to think -over what had happened to her, and suddenly remembering Prince -Andrew she was horrified, and at tea to which all had sat down after -the opera, she gave a loud exclamation, flushed, and ran out of the -room. - -"O God! I am lost!" she said to herself. "How could I let him?" -She sat for a long time hiding her flushed face in her hands trying to -realize what had happened to her, but was unable either to -understand what had happened or what she felt. Everything seemed dark, -obscure, and terrible. There in that enormous, illuminated theater -where the bare-legged Duport, in a tinsel-decorated jacket, jumped -about to the music on wet boards, and young girls and old men, and the -nearly naked Helene with her proud, calm smile, rapturously cried -"bravo!"--there in the presence of that Helene it had all seemed clear -and simple; but now, alone by herself, it was incomprehensible. -"What is it? What was that terror I felt of him? What is this -gnawing of conscience I am feeling now?" she thought. - -Only to the old countess at night in bed could Natasha have told all -she was feeling. She knew that Sonya with her severe and simple -views would either not understand it at all or would be horrified at -such a confession. So Natasha tried to solve what was torturing her by -herself. - -"Am I spoiled for Andrew's love or not?" she asked herself, and with -soothing irony replied: "What a fool I am to ask that! What did happen -to me? Nothing! I have done nothing, I didn't lead him on at all. -Nobody will know and I shall never see him again," she told herself. -"So it is plain that nothing has happened and there is nothing to -repent of, and Andrew can love me still. But why 'still?' O God, why -isn't he here?" Natasha quieted herself for a moment, but again some -instinct told her that though all this was true, and though nothing -had happened, yet the former purity of her love for Prince Andrew -had perished. And again in imagination she went over her whole -conversation with Kuragin, and again saw the face, gestures, and -tender smile of that bold handsome man when he pressed her arm. - - - - - -CHAPTER XI - -Anatole Kuragin was staying in Moscow because his father had sent -him away from Petersburg, where he had been spending twenty thousand -rubles a year in cash, besides running up debts for as much more, -which his creditors demanded from his father. - -His father announced to him that he would now pay half his debts for -the last time, but only on condition that he went to Moscow as -adjutant to the commander in chief--a post his father had procured for -him--and would at last try to make a good match there. He indicated to -him Princess Mary and Julie Karagina. - -Anatole consented and went to Moscow, where he put up at Pierre's -house. Pierre received him unwillingly at first, but got used to him -after a while, sometimes even accompanied him on his carousals, and -gave him money under the guise of loans. - -As Shinshin had remarked, from the time of his arrival Anatole had -turned the heads of the Moscow ladies, especially by the fact that -he slighted them and plainly preferred the gypsy girls and French -actresses--with the chief of whom, Mademoiselle George, he was said to -be on intimate relations. He had never missed a carousal at -Danilov's or other Moscow revelers', drank whole nights through, -outvying everyone else, and was at all the balls and parties of the -best society. There was talk of his intrigues with some of the ladies, -and he flirted with a few of them at the balls. But he did not run -after the unmarried girls, especially the rich heiresses who were most -of them plain. There was a special reason for this, as he had got -married two years before--a fact known only to his most intimate -friends. At that time while with his regiment in Poland, a Polish -landowner of small means had forced him to marry his daughter. Anatole -had very soon abandoned his wife and, for a payment which he agreed to -send to his father-in-law, had arranged to be free to pass himself off -as a bachelor. - -Anatole was always content with his position, with himself, and with -others. He was instinctively and thoroughly convinced that was -impossible for him to live otherwise than as he did and that he had -never in his life done anything base. He was incapable of -considering how his actions might affect others or what the -consequences of this or that action of his might be. He was -convinced that, as a duck is so made that it must live in water, so -God had made him such that he must spend thirty thousand rubles a year -and always occupy a prominent position in society. He believed this so -firmly that others, looking at him, were persuaded of it too and did -not refuse him either a leading place in society or money, which he -borrowed from anyone and everyone and evidently would not repay. - -He was not a gambler, at any rate he did not care about winning. -He was not vain. He did not mind what people thought of him. Still -less could he be accused of ambition. More than once he had vexed -his father by spoiling his own career, and he laughed at -distinctions of all kinds. He was not mean, and did not refuse -anyone who asked of him. All he cared about was gaiety and women, -and as according to his ideas there was nothing dishonorable in -these tastes, and he was incapable of considering what the -gratification of his tastes entailed for others, he honestly -considered himself irreproachable, sincerely despised rogues and bad -people, and with a tranquil conscience carried his head high. - -Rakes, those male Magdalenes, have a secret feeling of innocence -similar to that which female Magdalenes have, based on the same hope -of forgiveness. "All will be forgiven her, for she loved much; and all -will be forgiven him, for he enjoyed much." - -Dolokhov, who had reappeared that year in Moscow after his exile and -his Persian adventures, and was leading a life of luxury, gambling, -and dissipation, associated with his old Petersburg comrade Kuragin -and made use of him for his own ends. - -Anatole was sincerely fond of Dolokhov for his cleverness and -audacity. Dolokhov, who needed Anatole Kuragin's name, position, and -connections as a bait to draw rich young men into his gambling set, -made use of him and amused himself at his expense without letting -the other feel it. Apart from the advantage he derived from Anatole, -the very process of dominating another's will was in itself a -pleasure, a habit, and a necessity to Dolokhov. - -Natasha had made a strong impression on Kuragin. At supper after the -opera he described to Dolokhov with the air of a connoisseur the -attractions of her arms, shoulders, feet, and hair and expressed his -intention of making love to her. Anatole had no notion and was -incapable of considering what might come of such love-making, as he -never had any notion of the outcome of any of his actions. - -"She's first-rate, my dear fellow, but not for us," replied -Dolokhov. - -"I will tell my sister to ask her to dinner," said Anatole. "Eh?" - -"You'd better wait till she's married...." - -"You know, I adore little girls, they lose their heads at once," -pursued Anatole. - -"You have been caught once already by a 'little girl,'" said -Dolokhov who knew of Kuragin's marriage. "Take care!" - -"Well, that can't happen twice! Eh?" said Anatole, with a -good-humored laugh. - - - - - -CHAPTER XII - - -The day after the opera the Rostovs went nowhere and nobody came -to see them. Marya Dmitrievna talked to the count about something -which they concealed from Natasha. Natasha guessed they were talking -about the old prince and planning something, and this disquieted and -offended her. She was expecting Prince Andrew any moment and twice -that day sent a manservant to the Vozdvizhenka to ascertain whether he -had come. He had not arrived. She suffered more now than during her -first days in Moscow. To her impatience and pining for him were now -added the unpleasant recollection of her interview with Princess -Mary and the old prince, and a fear and anxiety of which she did not -understand the cause. She continually fancied that either he would -never come or that something would happen to her before he came. She -could no longer think of him by herself calmly and continuously as she -had done before. As soon as she began to think of him, the -recollection of the old prince, of Princess Mary, of the theater, -and of Kuragin mingled with her thoughts. The question again presented -itself whether she was not guilty, whether she had not already -broken faith with Prince Andrew, and again she found herself recalling -to the minutest detail every word, every gesture, and every shade in -the play of expression on the face of the man who had been able to -arouse in her such an incomprehensible and terrifying feeling. To -the family Natasha seemed livelier than usual, but she was far less -tranquil and happy than before. - -On Sunday morning Marya Dmitrievna invited her visitors to Mass at -her parish church--the Church of the Assumption built over the -graves of victims of the plague. - -"I don't like those fashionable churches," she said, evidently -priding herself on her independence of thought. "God is the same every -where. We have an excellent priest, he conducts the service decently -and with dignity, and the deacon is the same. What holiness is there -in giving concerts in the choir? I don't like it, it's just -self-indulgence!" - -Marya Dmitrievna liked Sundays and knew how to keep them. Her -whole house was scrubbed and cleaned on Saturdays; neither she nor the -servants worked, and they all wore holiday dress and went to church. -At her table there were extra dishes at dinner, and the servants had -vodka and roast goose or suckling pig. But in nothing in the house was -the holiday so noticeable as in Marya Dmitrievna's broad, stern -face, which on that day wore an invariable look of solemn festivity. - -After Mass, when they had finished their coffee in the dining room -where the loose covers had been removed from the furniture, a -servant announced that the carriage was ready, and Marya Dmitrievna -rose with a stern air. She wore her holiday shawl, in which she paid -calls, and announced that she was going to see Prince Nicholas -Bolkonski to have an explanation with him about Natasha. - -After she had gone, a dressmaker from Madame Suppert-Roguet waited -on the Rostovs, and Natasha, very glad of this diversion, having -shut herself into a room adjoining the drawing room, occupied -herself trying on the new dresses. Just as she had put on a bodice -without sleeves and only tacked together, and was turning her head -to see in the glass how the back fitted, she heard in the drawing room -the animated sounds of her father's voice and another's--a woman's- -that made her flush. It was Helene. Natasha had not time to take off -the bodice before the door opened and Countess Bezukhova, dressed in a -purple velvet gown with a high collar, came into the room beaming with -good-humored amiable smiles. - -"Oh, my enchantress!" she cried to the blushing Natasha. -"Charming! No, this is really beyond anything, my dear count," said -she to Count Rostov who had followed her in. "How can you live in -Moscow and go nowhere? No, I won't let you off! Mademoiselle George -will recite at my house tonight and there'll be some people, and if -you don't bring your lovely girls--who are prettier than -Mademoiselle George--I won't know you! My husband is away in Tver or I -would send him to fetch you. You must come. You positively must! -Between eight and nine." - -She nodded to the dressmaker, whom she knew and who had curtsied -respectfully to her, and seated herself in an armchair beside the -looking glass, draping the folds of her velvet dress picturesquely. -She did not cease chattering good-naturedly and gaily, continually -praising Natasha's beauty. She looked at Natasha's dresses and praised -them, as well as a new dress of her own made of "metallic gauze," -which she had received from Paris, and advised Natasha to have one -like it. - -"But anything suits you, my charmer!" she remarked. - -A smile of pleasure never left Natasha's face. She felt happy and as -if she were blossoming under the praise of this dear Countess -Bezukhova who had formerly seemed to her so unapproachable and -important and was now so kind to her. Natasha brightened up and felt -almost in love with this woman, who was so beautiful and so kind. -Helene for her part was sincerely delighted with Natasha and wished to -give her a good time. Anatole had asked her to bring him and Natasha -together, and she was calling on the Rostovs for that purpose. The -idea of throwing her brother and Natasha together amused her. - -Though at one time, in Petersburg, she had been annoyed with Natasha -for drawing Boris away, she did not think of that now, and in her -own way heartily wished Natasha well. As she was leaving the Rostovs -she called her protegee aside. - -"My brother dined with me yesterday--we nearly died of laughter- -he ate nothing and kept sighing for you, my charmer! He is madly, -quite madly, in love with you, my dear." - -Natasha blushed scarlet when she heard this. - -"How she blushes, how she blushes, my pretty!" said Helene. "You -must certainly come. If you love somebody, my charmer, that is not a -reason to shut yourself up. Even if you are engaged, I am sure your -fiance would wish you to go into society rather than be bored to -death." - -"So she knows I am engaged, and she and her husband Pierre--that -good Pierre--have talked and laughed about this. So it's all right." -And again, under Helene's influence, what had seemed terrible now -seemed simple and natural. "And she is such a grande dame, so kind, -and evidently likes me so much. And why not enjoy myself?" thought -Natasha, gazing at Helene with wide-open, wondering eyes. - -Marya Dmitrievna came back to dinner taciturn and serious, having -evidently suffered a defeat at the old prince's. She was still too -agitated by the encounter to be able to talk of the affair calmly. -In answer to the count's inquiries she replied that things were all -right and that she would tell about it next day. On hearing of -Countess Bezukhova's visit and the invitation for that evening, -Marya Dmitrievna remarked: - -"I don't care to have anything to do with Bezukhova and don't advise -you to; however, if you've promised--go. It will divert your -thoughts," she added, addressing Natasha. - - - - - -CHAPTER XIII - - -Count Rostov took the girls to Countess Bezukhova's. There were a -good many people there, but nearly all strangers to Natasha. Count -Rostov was displeased to see that the company consisted almost -entirely of men and women known for the freedom of their conduct. -Mademoiselle George was standing in a corner of the drawing room -surrounded by young men. There were several Frenchmen present, among -them Metivier who from the time Helene reached Moscow had been an -intimate in her house. The count decided not to sit down to cards or -let his girls out of his sight and to get away as soon as Mademoiselle -George's performance was over. - -Anatole was at the door, evidently on the lookout for the Rostovs. -Immediately after greeting the count he went up to Natasha and -followed her. As soon as she saw him she was seized by the same -feeling she had had at the opera--gratified vanity at his admiration -of her and fear at the absence of a moral barrier between them. - -Helene welcomed Natasha delightedly and was loud in admiration of -her beauty and her dress. Soon after their arrival Mademoiselle George -went out of the room to change her costume. In the drawing room people -began arranging the chairs and taking their seats. Anatole moved a -chair for Natasha and was about to sit down beside her, but the count, -who never lost sight of her, took the seat himself. Anatole sat down -behind her. - -Mademoiselle George, with her bare, fat, dimpled arms, and a red -shawl draped over one shoulder, came into the space left vacant for -her, and assumed an unnatural pose. Enthusiastic whispering was -audible. - -Mademoiselle George looked sternly and gloomily at the audience -and began reciting some French verses describing her guilty love for -her son. In some places she raised her voice, in others she whispered, -lifting her head triumphantly; sometimes she paused and uttered hoarse -sounds, rolling her eyes. - -"Adorable! divine! delicious!" was heard from every side. - -Natasha looked at the fat actress, but neither saw nor heard nor -understood anything of what went on before her. She only felt -herself again completely borne away into this strange senseless world- -so remote from her old world--a world in which it was impossible to -know what was good or bad, reasonable or senseless. Behind her sat -Anatole, and conscious of his proximity she experienced a frightened -sense of expectancy. - -After the first monologue the whole company rose and surrounded -Mademoiselle George, expressing their enthusiasm. - -"How beautiful she is!" Natasha remarked to her father who had -also risen and was moving through the crowd toward the actress. - -"I don't think so when I look at you!" said Anatole, following -Natasha. He said this at a moment when she alone could hear him. -"You are enchanting... from the moment I saw you I have never -ceased..." - -"Come, come, Natasha!" said the count, as he turned back for his -daughter. "How beautiful she is!" Natasha without saying anything -stepped up to her father and looked at him with surprised inquiring -eyes. - -After giving several recitations, Mademoiselle George left, and -Countess Bezukhova asked her visitors into the ballroom. - -The count wished to go home, but Helene entreated him not to spoil -her improvised ball, and the Rostovs stayed on. Anatole asked -Natasha for a valse and as they danced he pressed her waist and hand -and told her she was bewitching and that he loved her. During the -ecossaise, which she also danced with him, Anatole said nothing when -they happened to be by themselves, but merely gazed at her. Natasha -lifted her frightened eyes to him, but there was such confident -tenderness in his affectionate look and smile that she could not, -whilst looking at him, say what she had to say. She lowered her eyes. - -"Don't say such things to me. I am betrothed and love another," -she said rapidly.... She glanced at him. - -Anatole was not upset or pained by what she had said. - -"Don't speak to me of that! What can I do?" said he. "I tell you I -am madly, madly, in love with you! Is it my fault that you are -enchanting?... It's our turn to begin." - -Natasha, animated and excited, looked about her with wide-open -frightened eyes and seemed merrier than usual. She understood hardly -anything that went on that evening. They danced the ecossaise and -the Grossvater. Her father asked her to come home, but she begged to -remain. Wherever she went and whomever she was speaking to, she felt -his eyes upon her. Later on she recalled how she had asked her -father to let her go to the dressing room to rearrange her dress, that -Helene had followed her and spoken laughingly of her brother's love, -and that she again met Anatole in the little sitting room. Helene -had disappeared leaving them alone, and Anatole had taken her hand and -said in a tender voice: - -"I cannot come to visit you but is it possible that I shall never -see you? I love you madly. Can I never...?" and, blocking her path, he -brought his face close to hers. - -His large, glittering, masculine eyes were so close to hers that she -saw nothing but them. - -"Natalie?" he whispered inquiringly while she felt her hands being -painfully pressed. "Natalie?" - -"I don't understand. I have nothing to say," her eyes replied. - -Burning lips were pressed to hers, and at the same instant she -felt herself released, and Helene's footsteps and the rustle of her -dress were heard in the room. Natasha looked round at her, and then, -red and trembling, threw a frightened look of inquiry at Anatole and -moved toward the door. - -"One word, just one, for God's sake!" cried Anatole. - -She paused. She so wanted a word from him that would explain to -her what had happened and to which she could find no answer. - -"Natalie, just a word, only one!" he kept repeating, evidently not -knowing what to say and he repeated it till Helene came up to them. - -Helene returned with Natasha to the drawing room. The Rostovs went -away without staying for supper. - -After reaching home Natasha did not sleep all night. She was -tormented by the insoluble question whether she loved Anatole or -Prince Andrew. She loved Prince Andrew--she remembered distinctly -how deeply she loved him. But she also loved Anatole, of that there -was no doubt. "Else how could all this have happened?" thought she. -"If, after that, I could return his smile when saying good-by, if I -was able to let it come to that, it means that I loved him from the -first. It means that he is kind, noble, and splendid, and I could -not help loving him. What am I to do if I love him and the other one -too?" she asked herself, unable to find an answer to these terrible -questions. - - - - - -CHAPTER XIV - - -Morning came with its cares and bustle. Everyone got up and began to -move about and talk, dressmakers came again. Marya Dmitrievna -appeared, and they were called to breakfast. Natasha kept looking -uneasily at everybody with wide-open eyes, as if wishing to -intercept every glance directed toward her, and tried to appear the -same as usual. - -After breakfast, which was her best time, Marya Dmitrievna sat -down in her armchair and called Natasha and the count to her. - -"Well, friends, I have now thought the whole matter over and this is -my advice," she began. "Yesterday, as you know, I went to see Prince -Bolkonski. Well, I had a talk with him.... He took it into his head to -begin shouting, but I am not one to be shouted down. I said what I had -to say!" - -"Well, and he?" asked the count. - -"He? He's crazy... he did not want to listen. But what's the use -of talking? As it is we have worn the poor girl out," said Marya -Dmitrievna. "My advice to you is finish your business and go back home -to Otradnoe... and wait there." - -"Oh, no!" exclaimed Natasha. - -"Yes, go back," said Marya Dmitrievna, "and wait there. If your -betrothed comes here now--there will be no avoiding a quarrel; but -alone with the old man he will talk things over and then come on to -you." - -Count Rostov approved of this suggestion, appreciating its -reasonableness. If the old man came round it would be all the better -to visit him in Moscow or at Bald Hills later on; and if not, the -wedding, against his wishes, could only be arranged at Otradnoe. - -"That is perfectly true. And I am sorry I went to see him and took -her," said the old count. - -"No, why be sorry? Being here, you had to pay your respects. But -if he won't--that's his affair," said Marya Dmitrievna, looking for -something in her reticule. "Besides, the trousseau is ready, so -there is nothing to wait for; and what is not ready I'll send after -you. Though I don't like letting you go, it is the best way. So go, -with God's blessing!" - -Having found what she was looking for in the reticule she handed -it to Natasha. It was a letter from Princess Mary. - -"She has written to you. How she torments herself, poor thing! She's -afraid you might think that she does not like you." - -"But she doesn't like me," said Natasha. - -"Don't talk nonsense!" cried Marya Dmitrievna. - -"I shan't believe anyone, I know she doesn't like me," replied -Natasha boldly as she took the letter, and her face expressed a cold -and angry resolution that caused Marya Dmitrievna to look at her -more intently and to frown. - -"Don't answer like that, my good girl!" she said. "What I say is -true! Write an answer!" Natasha did not reply and went to her own room -to read Princess Mary's letter. - -Princess Mary wrote that she was in despair at the -misunderstanding that had occurred between them. Whatever her father's -feelings might be, she begged Natasha to believe that she could not -help loving her as the one chosen by her brother, for whose -happiness she was ready to sacrifice everything. - -"Do not think, however," she wrote, "that my father is -ill-disposed toward you. He is an invalid and an old man who must be -forgiven; but he is good and magnanimous and will love her who makes -his son happy." Princess Mary went on to ask Natasha to fix a time -when she could see her again. - -After reading the letter Natasha sat down at the writing table to -answer it. "Dear Princess," she wrote in French quickly and -mechanically, and then paused. What more could she write after all -that had happened the evening before? "Yes, yes! All that has -happened, and now all is changed," she thought as she sat with the -letter she had begun before her. "Must I break off with him? Must I -really? That's awful..." and to escape from these dreadful thoughts -she went to Sonya and began sorting patterns with her. - -After dinner Natasha went to her room and again took up Princess -Mary's letter. "Can it be that it is all over?" she thought. "Can it -be that all this has happened so quickly and has destroyed all that -went before?" She recalled her love for Prince Andrew in all its -former strength, and at the same time felt that she loved Kuragin. She -vividly pictured herself as Prince Andrew's wife, and the scenes of -happiness with him she had so often repeated in her imagination, and -at the same time, aglow with excitement, recalled every detail of -yesterday's interview with Anatole. - -"Why could that not be as well?" she sometimes asked herself in -complete bewilderment. "Only so could I be completely happy; but now I -have to choose, and I can't be happy without either of them. Only," -she thought, "to tell Prince Andrew what has happened or to hide it -from him are both equally impossible. But with that one nothing is -spoiled. But am I really to abandon forever the joy of Prince Andrew's -love, in which I have lived so long?" - -"Please, Miss!" whispered a maid entering the room with a mysterious -air. "A man told me to give you this-" and she handed Natasha a -letter. - -"Only, for Christ's sake..." the girl went on, as Natasha, without -thinking, mechanically broke the seal and read a love letter from -Anatole, of which, without taking in a word, she understood only -that it was a letter from him--from the man she loved. Yes, she -loved him, or else how could that have happened which had happened? -And how could she have a love letter from him in her hand? - -With trembling hands Natasha held that passionate love letter -which Dolokhov had composed for Anatole, and as she read it she -found in it an echo of all that she herself imagined she was feeling. - -"Since yesterday evening my fate has been sealed; to be loved by you -or to die. There is no other way for me," the letter began. Then he -went on to say that he knew her parents would not give her to him--for -this there were secret reasons he could reveal only to her--but that -if she loved him she need only say the word yes, and no human power -could hinder their bliss. Love would conquer all. He would steal her -away and carry her off to the ends of the earth. - -"Yes, yes! I love him!" thought Natasha, reading the letter for -the twentieth time and finding some peculiarly deep meaning in each -word of it. - -That evening Marya Dmitrievna was going to the Akharovs' and -proposed to take the girls with her. Natasha, pleading a headache, -remained at home. - - - - - -CHAPTER XV - - -On returning late in the evening Sonya went to Natasha's room, and -to her surprise found her still dressed and asleep on the sofa. Open -on the table, beside her lay Anatole's letter. Sonya picked it up -and read it. - -As she read she glanced at the sleeping Natasha, trying to find in -her face an explanation of what she was reading, but did not find -it. Her face was calm, gentle, and happy. Clutching her breast to keep -herself from choking, Sonya, pale and trembling with fear and -agitation, sat down in an armchair and burst into tears. - -"How was it I noticed nothing? How could it go so far? Can she -have left off loving Prince Andrew? And how could she let Kuragin go -to such lengths? He is a deceiver and a villain, that's plain! What -will Nicholas, dear noble Nicholas, do when he hears of it? So this is -the meaning of her excited, resolute, unnatural look the day before -yesterday, yesterday, and today," thought Sonya. "But it can't be that -she loves him! She probably opened the letter without knowing who it -was from. Probably she is offended by it. She could not do such a -thing!" - -Sonya wiped away her tears and went up to Natasha, again scanning -her face. - -"Natasha!" she said, just audibly. - -Natasha awoke and saw Sonya. - -"Ah, you're back?" - -And with the decision and tenderness that often come at the moment -of awakening, she embraced her friend, but noticing Sonya's look of -embarrassment, her own face expressed confusion and suspicion. - -"Sonya, you've read that letter?" she demanded. - -"Yes," answered Sonya softly. - -Natasha smiled rapturously. - -"No, Sonya, I can't any longer!" she said. "I can't hide it from you -any longer. You know, we love one another! Sonya, darling, he -writes... Sonya..." - -Sonya stared open-eyed at Natasha, unable to believe her ears. - -"And Bolkonski?" she asked. - -"Ah, Sonya, if you only knew how happy I am!" cried Natasha. "You -don't know what love is...." - -"But, Natasha, can that be all over?" - -Natasha looked at Sonya with wide-open eyes as if she could not -grasp the question. - -"Well, then, are you refusing Prince Andrew?" said Sonya. - -"Oh, you don't understand anything! Don't talk nonsense, just -listen!" said Natasha, with momentary vexation. - -"But I can't believe it," insisted Sonya. "I don't understand. How -is it you have loved a man for a whole year and suddenly... Why, you -have only seen him three times! Natasha, I don't believe you, you're -joking! In three days to forget everything and so..." - -"Three days?" said Natasha. "It seems to me I've loved him a hundred -years. It seems to me that I have never loved anyone before. You can't -understand it.... Sonya, wait a bit, sit here," and Natasha embraced -and kissed her. - -"I had heard that it happens like this, and you must have heard it -too, but it's only now that I feel such love. It's not the same as -before. As soon as I saw him I felt he was my master and I his -slave, and that I could not help loving him. Yes, his slave! -Whatever he orders I shall do. You don't understand that. What can I -do? What can I do, Sonya?" cried Natasha with a happy yet frightened -expression. - -"But think what you are doing," cried Sonya. "I can't leave it -like this. This secret correspondence... How could you let him go so -far?" she went on, with a horror and disgust she could hardly conceal. - -"I told you that I have no will," Natasha replied. "Why can't you -understand? I love him!" - -"Then I won't let it come to that... I shall tell!" cried Sonya, -bursting into tears. - -"What do you mean? For God's sake... If you tell, you are my enemy!" -declared Natasha. "You want me to be miserable, you want us to be -separated...." - -When she saw Natasha's fright, Sonya shed tears of shame and pity -for her friend. - -"But what has happened between you?" she asked. "What has he said to -you? Why doesn't he come to the house?" - -Natasha did not answer her questions. - -"For God's sake, Sonya, don't tell anyone, don't torture me," -Natasha entreated. "Remember no one ought to interfere in such -matters! I have confided in you...." - -"But why this secrecy? Why doesn't he come to the house?" asked -Sonya. "Why doesn't he openly ask for your hand? You know Prince -Andrew gave you complete freedom--if it is really so; but I don't -believe it! Natasha, have you considered what these secret reasons can -be?" - -Natasha looked at Sonya with astonishment. Evidently this question -presented itself to her mind for the first time and she did not know -how to answer it. - -"I don't know what the reasons are. But there must be reasons!" - -Sonya sighed and shook her head incredulously. - -"If there were reasons..." she began. - -But Natasha, guessing her doubts, interrupted her in alarm. - -"Sonya, one can't doubt him! One can't, one can't! Don't you -understand?" she cried. - -"Does he love you?" - -"Does he love me?" Natasha repeated with a smile of pity at her -friend's lack of comprehension. "Why, you have read his letter and you -have seen him." - -"But if he is dishonorable?" - -"He! dishonorable? If you only knew!" exclaimed Natasha. - -"If he is an honorable man he should either declare his intentions -or cease seeing you; and if you won't do this, I will. I will write to -him, and I will tell Papa!" said Sonya resolutely. - -"But I can't live without him!" cried Natasha. - -"Natasha, I don't understand you. And what are you saying! Think -of your father and of Nicholas." - -"I don't want anyone, I don't love anyone but him. How dare you -say he is dishonorable? Don't you know that I love him?" screamed -Natasha. "Go away, Sonya! I don't want to quarrel with you, but go, -for God's sake go! You see how I am suffering!" Natasha cried angrily, -in a voice of despair and repressed irritation. Sonya burst into -sobs and ran from the room. - -Natasha went to the table and without a moment's reflection wrote -that answer to Princess Mary which she had been unable to write all -the morning. In this letter she said briefly that all their -misunderstandings were at an end; that availing herself of the -magnanimity of Prince Andrew who when he went abroad had given her her -freedom, she begged Princess Mary to forget everything and forgive her -if she had been to blame toward her, but that she could not be his wife. -At that moment this all seemed quite easy, simple, and clear to Natasha. - - -On Friday the Rostovs were to return to the country, but on -Wednesday the count went with the prospective purchaser to his -estate near Moscow. - -On the day the count left, Sonya and Natasha were invited to a big -dinner party at the Karagins', and Marya Dmitrievna took them there. -At that party Natasha again met Anatole, and Sonya noticed that she -spoke to him, trying not to be overheard, and that all through -dinner she was more agitated than ever. When they got home Natasha was -the first to begin the explanation Sonya expected. - -"There, Sonya, you were talking all sorts of nonsense about him," -Natasha began in a mild voice such as children use when they wish to -be praised. "We have had an explanation today." - -"Well, what happened? What did he say? Natasha, how glad I am you're -not angry with me! Tell me everything--the whole truth. What did he -say?" - -Natasha became thoughtful. - -"Oh, Sonya, if you knew him as I do! He said... He asked me what I -had promised Bolkonski. He was glad I was free to refuse him." - -Sonya sighed sorrowfully. - -"But you haven't refused Bolkonski?" said she. - -"Perhaps I have. Perhaps all is over between me and Bolkonski. Why -do you think so badly of me?" - -"I don't think anything, only I don't understand this..." - -"Wait a bit, Sonya, you'll understand everything. You'll see what -a man he is! Now don't think badly of me or of him. I don't think -badly of anyone: I love and pity everybody. But what am I to do?" - -Sonya did not succumb to the tender tone Natasha used toward her. -The more emotional and ingratiating the expression of Natasha's face -became, the more serious and stern grew Sonya's. - -"Natasha," said she, "you asked me not to speak to you, and I -haven't spoken, but now you yourself have begun. I don't trust him, -Natasha. Why this secrecy?" - -"Again, again!" interrupted Natasha. - -"Natasha, I am afraid for you!" - -"Afraid of what?" - -"I am afraid you're going to your ruin," said Sonya resolutely, -and was herself horrified at what she had said. - -Anger again showed in Natasha's face. - -"And I'll go to my ruin, I will, as soon as possible! It's not -your business! It won't be you, but I, who'll suffer. Leave me -alone, leave me alone! I hate you!" - -"Natasha!" moaned Sonya, aghast. - -"I hate you, I hate you! You're my enemy forever!" And Natasha ran -out of the room. - -Natasha did not speak to Sonya again and avoided her. With the -same expression of agitated surprise and guilt she went about the -house, taking up now one occupation, now another, and at once -abandoning them. - -Hard as it was for Sonya, she watched her friend and did not let her -out of her sight. - -The day before the count was to return, Sonya noticed that Natasha -sat by the drawingroom window all the morning as if expecting -something and that she made a sign to an officer who drove past, -whom Sonya took to be Anatole. - -Sonya began watching her friend still more attentively and noticed -that at dinner and all that evening Natasha was in a strange and -unnatural state. She answered questions at random, began sentences she -did not finish, and laughed at everything. - -After tea Sonya noticed a housemaid at Natasha's door timidly -waiting to let her pass. She let the girl go in, and then listening at -the door learned that another letter had been delivered. - -Then suddenly it became clear to Sonya that Natasha had some -dreadful plan for that evening. Sonya knocked at her door. Natasha did -not let her in. - -"She will run away with him!" thought Sonya. "She is capable of -anything. There was something particularly pathetic and resolute in -her face today. She cried as she said good-by to Uncle," Sonya -remembered. "Yes, that's it, she means to elope with him, but what -am I to do?" thought she, recalling all the signs that clearly -indicated that Natasha had some terrible intention. "The count is -away. What am I to do? Write to Kuragin demanding an explanation? -But what is there to oblige him to reply? Write to Pierre, as Prince -Andrew asked me to in case of some misfortune?... But perhaps she -really has already refused Bolkonski--she sent a letter to Princess -Mary yesterday. And Uncle is away...." To tell Marya Dmitrievna who -had such faith in Natasha seemed to Sonya terrible. "Well, anyway," -thought Sonya as she stood in the dark passage, "now or never I must -prove that I remember the family's goodness to me and that I love -Nicholas. Yes! If I don't sleep for three nights I'll not leave this -passage and will hold her back by force and will and not let the -family be disgraced," thought she. - - - - - -CHAPTER XVI - - -Anatole had lately moved to Dolokhov's. The plan for Natalie -Rostova's abduction had been arranged and the preparations made by -Dolokhov a few days before, and on the day that Sonya, after listening -at Natasha's door, resolved to safeguard her, it was to have been -put into execution. Natasha had promised to come out to Kuragin at the -back porch at ten that evening. Kuragin was to put her into a troyka -he would have ready and to drive her forty miles to the village of -Kamenka, where an unfrocked priest was in readiness to perform a -marriage ceremony over them. At Kamenka a relay of horses was to -wait which would take them to the Warsaw highroad, and from there they -would hasten abroad with post horses. - -Anatole had a passport, an order for post horses, ten thousand -rubles he had taken from his sister and another ten thousand -borrowed with Dolokhov's help. - -Two witnesses for the mock marriage--Khvostikov, a retired petty -official whom Dolokhov made use of in his gambling transactions, and -Makarin, a retired hussar, a kindly, weak fellow who had an -unbounded affection for Kuragin--were sitting at tea in Dolokhov's -front room. - -In his large study, the walls of which were hung to the ceiling with -Persian rugs, bearskins, and weapons, sat Dolokhov in a traveling -cloak and high boots, at an open desk on which lay abacus and some -bundles of paper money. Anatole, with uniform unbuttoned, walked to -and fro from the room where the witnesses were sitting, through the -study to the room behind, where his French valet and others were -packing the last of his things. Dolokhov was counting the money and -noting something down. - -"Well," he said, "Khvostikov must have two thousand." - -"Give it to him, then," said Anatole. - -"Makarka" (their name for Makarin) "will go through fire and water -for you for nothing. So here are our accounts all settled," said -Dolokhov, showing him the memorandum. "Is that right?" - -"Yes, of course," returned Anatole, evidently not listening to -Dolokhov and looking straight before him with a smile that did not -leave his face. - -Dolokhov banged down the or of his and turned to Anatole with an -ironic smile: - -"Do you know? You'd really better drop it all. There's still time!" - -"Fool," retorted Anatole. "Don't talk nonsense! If you only -knew... it's the devil knows what!" - -"No, really, give it up!" said Dolokhov. "I am speaking seriously. -It's no joke, this plot you've hatched." - -"What, teasing again? Go to the devil! Eh?" said Anatole, making a -grimace. "Really it's no time for your stupid jokes," and he left -the room. - -Dolokhov smiled contemptuously and condescendingly when Anatole -had gone out. - -"You wait a bit," he called after him. "I'm not joking, I'm -talking sense. Come here, come here!" - -Anatole returned and looked at Dolokhov, trying to give him his -attention and evidently submitting to him involuntarily. - -"Now listen to me. I'm telling you this for the last time. Why -should I joke about it? Did I hinder you? Who arranged everything -for you? Who found the priest and got the passport? Who raised the -money? I did it all." - -"Well, thank you for it. Do you think I am not grateful?" And -Anatole sighed and embraced Dolokhov. - -"I helped you, but all the same I must tell you the truth; it is a -dangerous business, and if you think about it--a stupid business. -Well, you'll carry her off--all right! Will they let it stop at -that? It will come out that you're already married. Why, they'll -have you in the criminal court...." - -"Oh, nonsense, nonsense!" Anatole ejaculated and again made a -grimace. "Didn't I explain to you? What?" And Anatole, with the -partiality dull-witted people have for any conclusion they have -reached by their own reasoning, repeated the argument he had already -put to Dolokhov a hundred times. "Didn't I explain to you that I -have come to this conclusion: if this marriage is invalid," he went -on, crooking one finger, "then I have nothing to answer for; but if it -is valid, no matter! Abroad no one will know anything about it. -Isn't that so? And don't talk to me, don't, don't." - -"Seriously, you'd better drop it! You'll only get yourself into a -mess!" - -"Go to the devil!" cried Anatole and, clutching his hair, left the -room, but returned at once and dropped into an armchair in front of -Dolokhov with his feet turned under him. "It's the very devil! What? -Feel how it beats!" He took Dolokhov's hand and put it on his heart. -"What a foot, my dear fellow! What a glance! A goddess!" he added in -French. "What?" - -Dolokhov with a cold smile and a gleam in his handsome insolent eyes -looked at him--evidently wishing to get some more amusement out of -him. - -"Well and when the money's gone, what then?" - -"What then? Eh?" repeated Anatole, sincerely perplexed by a -thought of the future. "What then?... Then, I don't know.... But why -talk nonsense!" He glanced at his watch. "It's time!" - -Anatole went into the back room. - -"Now then! Nearly ready? You're dawdling!" he shouted to the -servants. - -Dolokhov put away the money, called a footman whom he ordered to -bring something for them to eat and drink before the journey, and went -into the room where Khvostikov and Makarin were sitting. - -Anatole lay on the sofa in the study leaning on his elbow and -smiling pensively, while his handsome lips muttered tenderly to -himself. - -"Come and eat something. Have a drink!" Dolokhov shouted to him from -the other room. - -"I don't want to," answered Anatole continuing to smile. - -"Come! Balaga is here." - -Anatole rose and went into the dining room. Balaga was a famous -troyka driver who had known Dolokhov and Anatole some six years and -had given them good service with his troykas. More than once when -Anatole's regiment was stationed at Tver he had taken him from Tver in -the evening, brought him to Moscow by daybreak, and driven him back -again the next night. More than once he had enabled Dolokhov to escape -when pursued. More than once he had driven them through the town -with gypsies and "ladykins" as he called the cocottes. More than -once in their service he had run over pedestrians and upset vehicles -in the streets of Moscow and had always been protected from the -consequences by "my gentlemen" as he called them. He had ruined more -than one horse in their service. More than once they had beaten him, -and more than once they had made him drunk on champagne and Madeira, -which he loved; and he knew more than one thing about each of them -which would long ago have sent an ordinary man to Siberia. They -often called Balaga into their orgies and made him drink and dance -at the gypsies', and more than one thousand rubles of their money -had passed through his hands. In their service he risked his skin -and his life twenty times a year, and in their service had lost more -horses than the money he had from them would buy. But he liked them; -liked that mad driving at twelve miles an hour, liked upsetting a -driver or running down a pedestrian, and flying at full gallop through -the Moscow streets. He liked to hear those wild, tipsy shouts behind -him: "Get on! Get on!" when it was impossible to go any faster. He -liked giving a painful lash on the neck to some peasant who, more dead -than alive, was already hurrying out of his way. "Real gentlemen!" -he considered them. - -Anatole and Dolokhov liked Balaga too for his masterly driving and -because he liked the things they liked. With others Balaga -bargained, charging twenty-five rubles for a two hours' drive, and -rarely drove himself, generally letting his young men do so. But -with "his gentlemen" he always drove himself and never demanded -anything for his work. Only a couple of times a year--when he knew -from their valets that they had money in hand--he would turn up of a -morning quite sober and with a deep bow would ask them to help him. -The gentlemen always made him sit down. - -"Do help me out, Theodore Ivanych, sir," or "your excellency," he -would say. "I am quite out of horses. Let me have what you can to go -to the fair." - -And Anatole and Dolokhov, when they had money, would give him a -thousand or a couple of thousand rubles. - -Balaga was a fair-haired, short, and snub-nosed peasant of about -twenty-seven; red-faced, with a particularly red thick neck, -glittering little eyes, and a small beard. He wore a fine, -dark-blue, silk-lined cloth coat over a sheepskin. - -On entering the room now he crossed himself, turning toward the -front corner of the room, and went up to Dolokhov, holding out a -small, black hand. - -"Theodore Ivanych!" he said, bowing. - -"How d'you do, friend? Well, here he is!" - -"Good day, your excellency!" he said, again holding out his hand -to Anatole who had just come in. - -"I say, Balaga," said Anatole, putting his hands on the man's -shoulders, "do you care for me or not? Eh? Now, do me a service.... -What horses have you come with? Eh?" - -"As your messenger ordered, your special beasts," replied Balaga. - -"Well, listen, Balaga! Drive all three to death but get me there -in three hours. Eh?" - -"When they are dead, what shall I drive?" said Balaga with a wink. - -"Mind, I'll smash your face in! Don't make jokes!" cried Anatole, -suddenly rolling his eyes. - -"Why joke?" said the driver, laughing. "As if I'd grudge my -gentlemen anything! As fast as ever the horses can gallop, so fast -we'll go!" - -"Ah!" said Anatole. "Well, sit down." - -"Yes, sit down!" said Dolokhov. - -"I'll stand, Theodore Ivanych." - -"Sit down; nonsense! Have a drink!" said Anatole, and filled a large -glass of Madeira for him. - -The driver's eyes sparkled at the sight of the wine. After -refusing it for manners' sake, he drank it and wiped his mouth with -a red silk handkerchief he took out of his cap. - -"And when are we to start, your excellency?" - -"Well..." Anatole looked at his watch. "We'll start at once. Mind, -Balaga! You'll get there in time? Eh?" - -"That depends on our luck in starting, else why shouldn't we be -there in time?" replied Balaga. "Didn't we get you to Tver in seven -hours? I think you remember that, your excellency?" - -"Do you know, one Christmas I drove from Tver," said Anatole, -smilingly at the recollection and turning to Makarin who gazed -rapturously at him with wide-open eyes. "Will you believe it, Makarka, -it took one's breath away, the rate we flew. We came across a train of -loaded sleighs and drove right over two of them. Eh?" - -"Those were horses!" Balaga continued the tale. "That time I'd -harnessed two young side horses with the bay in the shafts," he went -on, turning to Dolokhov. "Will you believe it, Theodore Ivanych, those -animals flew forty miles? I couldn't hold them in, my hands grew -numb in the sharp frost so that I threw down the reins--'Catch hold -yourself, your excellency!' says I, and I just tumbled on the bottom -of the sleigh and sprawled there. It wasn't a case of urging them -on, there was no holding them in till we reached the place. The devils -took us there in three hours! Only the near one died of it." - - - - - -CHAPTER XVII - - -Anatole went out of the room and returned a few minutes later -wearing a fur coat girt with a silver belt, and a sable cap jauntily -set on one side and very becoming to his handsome face. Having -looked in a mirror, and standing before Dolokhov in the same pose he -had assumed before it, he lifted a glass of wine. - -"Well, good-by, Theodore. Thank you for everything and farewell!" -said Anatole. "Well, comrades and friends..." he considered for a -moment "...of my youth, farewell!" he said, turning to Makarin and the -others. - -Though they were all going with him, Anatole evidently wished to -make something touching and solemn out of this address to his -comrades. He spoke slowly in a loud voice and throwing out his chest -slightly swayed one leg. - -"All take glasses; you too, Balaga. Well, comrades and friends of my -youth, we've had our fling and lived and reveled. Eh? And now, when -shall we meet again? I am going abroad. We have had a good time--now -farewell, lads! To our health! Hurrah!..." he cried, and emptying -his glass flung it on the floor. - -"To your health!" said Balaga who also emptied his glass, and -wiped his mouth with his handkerchief. - -Makarin embraced Anatole with tears in his eyes. - -"Ah, Prince, how sorry I am to part from you! - -"Let's go. Let's go!" cried Anatole. - -Balaga was about to leave the room. - -"No, stop!" said Anatole. "Shut the door; we have first to sit down. -That's the way." - -They shut the door and all sat down. - -"Now, quick march, lads!" said Anatole, rising. - -Joseph, his valet, handed him his sabretache and saber, and they all -went out into the vestibule. - -"And where's the fur cloak?" asked Dolokhov. "Hey, Ignatka! Go to -Matrena Matrevna and ask her for the sable cloak. I have heard what -elopements are like," continued Dolokhov with a wink. "Why, she'll -rush out more dead than alive just in the things she is wearing; if -you delay at all there'll be tears and 'Papa' and 'Mamma,' and she's -frozen in a minute and must go back--but you wrap the fur cloak -round her first thing and carry her to the sleigh." - -The valet brought a woman's fox-lined cloak. - -"Fool, I told you the sable one! Hey, Matrena, the sable!" he -shouted so that his voice rang far through the rooms. - -A handsome, slim, and pale-faced gypsy girl with glittering black -eyes and curly blue-black hair, wearing a red shawl, ran out with a -sable mantle on her arm. - -"Here, I don't grudge it--take it!" she said, evidently afraid of -her master and yet regretful of her cloak. - -Dolokhov, without answering, took the cloak, threw it over -Matrena, and wrapped her up in it. - -"That's the way," said Dolokhov, "and then so!" and he turned the -collar up round her head, leaving only a little of the face uncovered. -"And then so, do you see?" and he pushed Anatole's head forward to -meet the gap left by the collar, through which Matrena's brilliant -smile was seen. - -"Well, good-by, Matrena," said Anatole, kissing her. "Ah, my -revels here are over. Remember me to Steshka. There, good-by! Good-by, -Matrena, wish me luck!" - -"Well, Prince, may God give you great luck!" said Matrena in her -gypsy accent. - -Two troykas were standing before the porch and two young drivers -were holding the horses. Balaga took his seat in the front one and -holding his elbows high arranged the reins deliberately. Anatole and -Dolokhov got in with him. Makarin, Khvostikov, and a valet seated -themselves in the other sleigh. - -"Well, are you ready?" asked Balaga. - -"Go!" he cried, twisting the reins round his hands, and the troyka -tore down the Nikitski Boulevard. - -"Tproo! Get out of the way! Hi!... Tproo!..." The shouting of Balaga -and of the sturdy young fellow seated on the box was all that could be -heard. On the Arbat Square the troyka caught against a carriage; -something cracked, shouts were heard, and the troyka flew along the -Arbat Street. - -After taking a turn along the Podnovinski Boulevard, Balaga began to -rein in, and turning back drew up at the crossing of the old -Konyusheny Street. - -The young fellow on the box jumped down to hold the horses and -Anatole and Dolokhov went along the pavement. When they reached the -gate Dolokhov whistled. The whistle was answered, and a maidservant -ran out. - -"Come into the courtyard or you'll be seen; she'll come out -directly," said she. - -Dolokhov stayed by the gate. Anatole followed the maid into the -courtyard, turned the corner, and ran up into the porch. - -He was met by Gabriel, Marya Dmitrievna's gigantic footman. - -"Come to the mistress, please," said the footman in his deep bass, -intercepting any retreat. - -"To what Mistress? Who are you?" asked Anatole in a breathless -whisper. - -"Kindly step in, my orders are to bring you in." - -"Kuragin! Come back!" shouted Dolokhov. "Betrayed! Back!" - -Dolokhov, after Anatole entered, had remained at the wicket gate and -was struggling with the yard porter who was trying to lock it. With -a last desperate effort Dolokhov pushed the porter aside, and when -Anatole ran back seized him by the arm, pulled him through the wicket, -and ran back with him to the troyka. - - - - - -CHAPTER XVIII - - -Marya Dmitrievna, having found Sonya weeping in the corridor, made -her confess everything, and intercepting the note to Natasha she -read it and went into Natasha's room with it in her hand. - -"You shameless good-for-nothing!" said she. "I won't hear a word." - -Pushing back Natasha who looked at her with astonished but -tearless eyes, she locked her in; and having given orders to the -yard porter to admit the persons who would be coming that evening, but -not to let them out again, and having told the footman to bring them -up to her, she seated herself in the drawing room to await the -abductors. - -When Gabriel came to inform her that the men who had come had run -away again, she rose frowning, and clasping her hands behind her paced -through the rooms a long time considering what she should do. Toward -midnight she went to Natasha's room fingering the key in her pocket. -Sonya was sitting sobbing in the corridor. "Marya Dmitrievna, for -God's sake let me in to her!" she pleaded, but Marya Dmitrievna -unlocked the door and went in without giving her an answer.... -"Disgusting, abominable... In my house... horrid girl, hussy! I'm only -sorry for her father!" thought she, trying to restrain her wrath. -"Hard as it may be, I'll tell them all to hold their tongues and -will hide it from the count." She entered the room with resolute -steps. Natasha lying on the sofa, her head hidden in her hands, and -she did not stir. She was in just the same position in which Marya -Dmitrievna had left her. - -"A nice girl! Very nice!" said Marya Dmitrievna. "Arranging meetings -with lovers in my house! It's no use pretending: you listen when I -speak to you!" And Marya Dmitrievna touched her arm. "Listen when when -I speak! You've disgraced yourself like the lowest of hussies. I'd -treat you differently, but I'm sorry for your father, so I will -conceal it." - -Natasha did not change her position, but her whole body heaved -with noiseless, convulsive sobs which choked her. Marya Dmitrievna -glanced round at Sonya and seated herself on the sofa beside Natasha. - -"It's lucky for him that he escaped me; but I'll find him!" she said -in her rough voice. "Do you hear what I am saying or not?" she added. - -She put her large hand under Natasha's face and turned it toward -her. Both Marya Dmitrievna and Sonya were amazed when they saw how -Natasha looked. Her eyes were dry and glistening, her lips compressed, -her cheeks sunken. - -"Let me be!... What is it to me?... I shall die!" she muttered, -wrenching herself from Marya Dmitrievna's hands with a vicious -effort and sinking down again into her former position. - -"Natalie!" said Marya Dmitrievna. "I wish for your good. Lie -still, stay like that then, I won't touch you. But listen. I won't -tell you how guilty you are. You know that yourself. But when your -father comes back tomorrow what am I to tell him? Eh?" - -Again Natasha's body shook with sobs. - -"Suppose he finds out, and your brother, and your betrothed?" - -"I have no betrothed: I have refused him!" cried Natasha. - -"That's all the same," continued Dmitrievna. "If they hear of -this, will they let it pass? He, your father, I know him... if he -challenges him to a duel will that be all right? Eh?" - -"Oh, let me be! Why have you interfered at all? Why? Why? Who -asked you to?" shouted Natasha, raising herself on the sofa and -looking malignantly at Marya Dmitrievna. - -"But what did you want?" cried Marya Dmitrievna, growing angry -again. "Were you kept under lock and key? Who hindered his coming to -the house? Why carry you off as if you were some gypsy singing -girl?... Well, if he had carried you off... do you think they wouldn't -have found him? Your father, or brother, or your betrothed? And he's a -scoundrel, a wretch--that's a fact!" - -"He is better than any of you!" exclaimed Natasha getting up. "If -you hadn't interfered... Oh, my God! What is it all? What is it? -Sonya, why?... Go away!" - -And she burst into sobs with the despairing vehemence with which -people bewail disasters they feel they have themselves occasioned. -Marya Dmitrievna was to speak again but Natasha cried out: - -"Go away! Go away! You all hate and despise me!" and she threw -herself back on the sofa. - -Marya Dmitrievna went on admonishing her for some time, enjoining on -her that it must all be kept from her father and assuring her that -nobody would know anything about it if only Natasha herself would -undertake to forget it all and not let anyone see that something had -happened. Natasha did not reply, nor did she sob any longer, but she -grew cold and had a shivering fit. Marya Dmitrievna put a pillow under -her head, covered her with two quilts, and herself brought her some -lime-flower water, but Natasha did not respond to her. - -"Well, let her sleep," said Marya Dmitrievna as she went of the room -supposing Natasha to be asleep. - -But Natasha was not asleep; with pale face and fixed wide-open -eyes she looked straight before her. All that night she did not -sleep or weep and did not speak to Sonya who got up and went to her -several times. - -Next day Count Rostov returned from his estate near Moscow in time -for lunch as he had promised. He was in very good spirits; the -affair with the purchaser was going on satisfactorily, and there was -nothing to keep him any longer in Moscow, away from the countess -whom he missed. Marya Dmitrievna met him and told him that Natasha had -been very unwell the day before and that they had sent for the doctor, -but that she was better now. Natasha had not left her room that -morning. With compressed and parched lips and dry fixed eyes, she -sat at the window, uneasily watching the people who drove past and -hurriedly glancing round at anyone who entered the room. She was -evidently expecting news of him and that he would come or would -write to her. - -When the count came to see her she turned anxiously round at the -sound of a man's footstep, and then her face resumed its cold and -malevolent expression. She did not even get up to greet him. "What -is the matter with you, my angel? Are you ill?" asked the count. - -After a moment's silence Natasha answered: "Yes, ill." - -In reply to the count's anxious inquiries as to why she was so -dejected and whether anything had happened to her betrothed, she -assured him that nothing had happened and asked him not to worry. -Marya Dmitrievna confirmed Natasha's assurances that nothing had -happened. From the pretense of illness, from his daughter's -distress, and by the embarrassed faces of Sonya and Marya -Dmitrievna, the count saw clearly that something had gone wrong during -his absence, but it was so terrible for him to think that anything -disgraceful had happened to his beloved daughter, and he so prized his -own cheerful tranquillity, that he avoided inquiries and tried to -assure himself that nothing particularly had happened; and he was only -dissatisfied that her indisposition delayed their return to the -country. - - - - - -CHAPTER XIX - - -From the day his wife arrived in Moscow Pierre had been intending to -go away somewhere, so as not to be near her. Soon after the Rostovs -came to Moscow the effect Natasha had on him made him hasten to -carry out his intention. He went to Tver to see Joseph Alexeevich's -widow, who had long since promised to hand over to him some papers -of her deceased husband's. - -When he returned to Moscow Pierre was handed a letter from Marya -Dmitrievna asking him to come and see her on a matter of great -importance relating to Andrew Bolkonski and his betrothed. Pierre -had been avoiding Natasha because it seemed to him that his feeling -for her was stronger than a married man's should be for his friend's -fiancee. Yet some fate constantly threw them together. - -"What can have happened? And what can they want with me?" thought he -as he dressed to go to Marya Dmitrievna's. "If only Prince Andrew -would hurry up and come and marry her!" thought he on his way to the -house. - -On the Tverskoy Boulevard a familiar voice called to him. - -"Pierre! Been back long?" someone shouted. Pierre raised his head. -In a sleigh drawn by two gray trotting-horses that were bespattering -the dashboard with snow, Anatole and his constant companion Makarin -dashed past. Anatole was sitting upright in the classic pose of -military dandies, the lower part of his face hidden by his beaver -collar and his head slightly bent. His face was fresh and rosy, his -white-plumed hat, tilted to one side, disclosed his curled and pomaded -hair besprinkled with powdery snow. - -"Yes, indeed, that's a true sage," thought Pierre. "He sees -nothing beyond the pleasure of the moment, nothing troubles him and so -he is always cheerful, satisfied, and serene. What wouldn't I give -to be like him!" he thought enviously. - -In Marya Dmitrievna's anteroom the footman who helped him off with -his fur coat said that the mistress asked him to come to her bedroom. - -When he opened the ballroom door Pierre saw Natasha sitting at the -window, with a thin, pale, and spiteful face. She glanced round at -him, frowned, and left the room with an expression of cold dignity. - -"What has happened?" asked Pierre, entering Marya Dmitrievna's room. - -"Fine doings!" answered Dmitrievna. "For fifty-eight years have I -lived in this world and never known anything so disgraceful!" - -And having put him on his honor not to repeat anything she told him, -Marya Dmitrievna informed him that Natasha had refused Prince Andrew -without her parents' knowledge and that the cause of this was -Anatole Kuragin into whose society Pierre's wife had thrown her and -with whom Natasha had tried to elope during her father's absence, in -order to be married secretly. - -Pierre raised his shoulders and listened open-mouthed to what was -told him, scarcely able to believe his own ears. That Prince -Andrew's deeply loved affianced wife--the same Natasha Rostova who -used to be so charming--should give up Bolkonski for that fool Anatole -who was already secretly married (as Pierre knew), and should be so in -love with him as to agree to run away with him, was something Pierre -could not conceive and could not imagine. - -He could not reconcile the charming impression he had of Natasha, -whom he had known from a child, with this new conception of her -baseness, folly, and cruelty. He thought of his wife. "They are all -alike!" he said to himself, reflecting that he was not the only man -unfortunate enough to be tied to a bad woman. But still he pitied -Prince Andrew to the point of tears and sympathized with his wounded -pride, and the more he pitied his friend the more did he think with -contempt and even with disgust of that Natasha who had just passed him -in the ballroom with such a look of cold dignity. He did not know that -Natasha's soul was overflowing with despair, shame, and humiliation, -and that it was not her fault that her face happened to assume an -expression of calm dignity and severity. - -"But how get married?" said Pierre, in answer to Marya Dmitrievna. -"He could not marry--he is married!" - -"Things get worse from hour to hour!" ejaculated Marya Dmitrievna. -"A nice youth! What a scoundrel! And she's expecting him--expecting -him since yesterday. She must be told! Then at least she won't go on -expecting him." - -After hearing the details of Anatole's marriage from Pierre, and -giving vent to her anger against Anatole in words of abuse, Marya -Dmitrievna told Pierre why she had sent for him. She was afraid that -the count or Bolkonski, who might arrive at any moment, if they knew -of this affair (which she hoped to hide from them) might challenge -Anatole to a duel, and she therefore asked Pierre to tell his -brother-in-law in her name to leave Moscow and not dare to let her set -eyes on him again. Pierre--only now realizing the danger to the old -count, Nicholas, and Prince Andrew--promised to do as she wished. -Having briefly and exactly explained her wishes to him, she let him go -to the drawing room. - -"Mind, the count knows nothing. Behave as if you know nothing -either," she said. "And I will go and tell her it is no use -expecting him! And stay to dinner if you care to!" she called after -Pierre. - -Pierre met the old count, who seemed nervous and upset. That morning -Natasha had told him that she had rejected Bolkonski. - -"Troubles, troubles, my dear fellow!" he said to Pierre. "What -troubles one has with these girls without their mother! I do so regret -having come here.... I will be frank with you. Have you heard she -has broken off her engagement without consulting anybody? It's true -this engagement never was much to my liking. Of course he is an -excellent man, but still, with his father's disapproval they -wouldn't have been happy, and Natasha won't lack suitors. Still, it -has been going on so long, and to take such a step without father's or -mother's consent! And now she's ill, and God knows what! It's hard, -Count, hard to manage daughters in their mother's absence...." - -Pierre saw that the count was much upset and tried to change the -subject, but the count returned to his troubles. - -Sonya entered the room with an agitated face. - -"Natasha is not quite well; she's in her room and would like to -see you. Marya Dmitrievna is with her and she too asks you to come." - -"Yes, you are a great friend of Bolkonski's, no doubt she wants to -send him a message," said the count. "Oh dear! Oh dear! How happy it -all was!" - -And clutching the spare gray locks on his temples the count left the -room. - -When Marya Dmitrievna told Natasha that Anatole was married, Natasha -did not wish to believe it and insisted on having it confirmed by -Pierre himself. Sonya told Pierre this as she led him along the -corridor to Natasha's room. - -Natasha, pale and stern, was sitting beside Marya Dmitrievna, and -her eyes, glittering feverishly, met Pierre with a questioning look -the moment he entered. She did not smile or nod, but only gazed -fixedly at him, and her look asked only one thing: was he a friend, or -like the others an enemy in regard to Anatole? As for Pierre, he -evidently did not exist for her. - -"He knows all about it," said Marya Dmitrievna pointing to Pierre -and addressing Natasha. "Let him tell you whether I have told the -truth." - -Natasha looked from one to the other as a hunted and wounded -animal looks at the approaching dogs and sportsmen. - -"Natalya Ilynichna," Pierre began, dropping his eyes with a -feeling of pity for her and loathing for the thing he had to do, -"whether it is true or not should make no difference to you, -because..." - -"Then it is not true that he's married!" - -"Yes, it is true." - -"Has he been married long?" she asked. "On your honor?..." - -Pierre gave his word of honor. - -"Is he still here?" she asked, quickly. - -"Yes, I have just seen him." - -She was evidently unable to speak and made a sign with her hands -that they should leave her alone. - - - - - -CHAPTER XX - - -Pierre did not stay for dinner, but left the room and went away at -once. He drove through the town seeking Anatole Kuragin, at the -thought of whom now the blood rushed to his heart and he felt a -difficulty in breathing. He was not at the ice hills, nor at the -gypsies', nor at Komoneno's. Pierre drove to the Club. In the Club all -was going on as usual. The members who were assembling for dinner were -sitting about in groups; they greeted Pierre and spoke of the town -news. The footman having greeted him, knowing his habits and his -acquaintances, told him there was a place left for him in the small -dining room and that Prince Michael Zakharych was in the library, -but Paul Timofeevich had not yet arrived. One of Pierre's -acquaintances, while they were talking about the weather, asked if -he had heard of Kuragin's abduction of Rostova which was talked of -in the town, and was it true? Pierre laughed and said it was -nonsense for he had just come from the Rostovs'. He asked everyone -about Anatole. One man told him he had not come yet, and another -that he was coming to dinner. Pierre felt it strange to see this calm, -indifferent crowd of people unaware of what was going on in his -soul. He paced through the ballroom, waited till everyone had come, -and as Anatole had not turned up did not stay for dinner but drove -home. - -Anatole, for whom Pierre was looking, dined that day with -Dolokhov, consulting him as to how to remedy this unfortunate -affair. It seemed to him essential to see Natasha. In the evening he -drove to his sister's to discuss with her how to arrange a meeting. -When Pierre returned home after vainly hunting all over Moscow, his -valet informed him that Prince Anatole was with the countess. The -countess' drawing room was full of guests. - -Pierre without greeting his wife whom he had not seen since his -return--at that moment she was more repulsive to him than ever- -entered the drawing room and seeing Anatole went up to him. - -"Ah, Pierre," said the countess going up to her husband. "You -don't know what a plight our Anatole..." - -She stopped, seeing in the forward thrust of her husband's head, -in his glowing eyes and his resolute gait, the terrible indications of -that rage and strength which she knew and had herself experienced -after his duel with Dolokhov. - -"Where you are, there is vice and evil!" said Pierre to his wife. -"Anatole, come with me! I must speak to you," he added in French. - -Anatole glanced round at his sister and rose submissively, ready -to follow Pierre. Pierre, taking him by the arm, pulled him toward -himself and was leading him from the room. - -"If you allow yourself in my drawing room..." whispered Helene, -but Pierre did not reply and went out of the room. - -Anatole followed him with his usual jaunty step but his face -betrayed anxiety. - -Having entered his study Pierre closed the door and addressed -Anatole without looking at him. - -"You promised Countess Rostova to marry her and were about to -elope with her, is that so?" - -"Mon cher," answered Anatole (their whole conversation was in -French), "I don't consider myself bound to answer questions put to -me in that tone." - -Pierre's face, already pale, became distorted by fury. He seized -Anatole by the collar of his uniform with his big hand and shook him -from side to side till Anatole's face showed a sufficient degree of -terror. - -"When I tell you that I must talk to you!..." repeated Pierre. - -"Come now, this is stupid. What?" said Anatole, fingering a button -of his collar that had been wrenched loose with a bit of the cloth. - -"You're a scoundrel and a blackguard, and I don't know what deprives -me from the pleasure of smashing your head with this!" said Pierre, -expressing himself so artificially because he was talking French. - -He took a heavy paperweight and lifted it threateningly, but at once -put it back in its place. - -"Did you promise to marry her?" - -"I... I didn't think of it. I never promised, because..." - -Pierre interrupted him. - -"Have you any letters of hers? Any letters?" he said, moving -toward Anatole. - -Anatole glanced at him and immediately thrust his hand into his -pocket and drew out his pocketbook. - -Pierre took the letter Anatole handed him and, pushing aside a table -that stood in his way, threw himself on the sofa. - -"I shan't be violent, don't be afraid!" said Pierre in answer to a -frightened gesture of Anatole's. "First, the letters," said he, as -if repeating a lesson to himself. "Secondly," he continued after a -short pause, again rising and again pacing the room, "tomorrow you -must get out of Moscow." - -"But how can I?..." - -"Thirdly," Pierre continued without listening to him, "you must -never breathe a word of what has passed between you and Countess -Rostova. I know I can't prevent your doing so, but if you have a spark -of conscience..." Pierre paced the room several times in silence. - -Anatole sat at a table frowning and biting his lips. - -"After all, you must understand that besides your pleasure there -is such a thing as other people's happiness and peace, and that you -are ruining a whole life for the sake of amusing yourself! Amuse -yourself with women like my wife--with them you are within your -rights, for they know what you want of them. They are armed against -you by the same experience of debauchery; but to promise a maid to -marry her... to deceive, to kidnap.... Don't you understand that it is -as mean as beating an old man or a child?..." - -Pierre paused and looked at Anatole no longer with an angry but with -a questioning look. - -"I don't know about that, eh?" said Anatole, growing more -confident as Pierre mastered his wrath. "I don't know that and don't -want to," he said, not looking at Pierre and with a slight tremor of -his lower jaw, "but you have used such words to me--'mean' and so -on--which as a man of honor I can't allow anyone to use." - -Pierre glanced at him with amazement, unable to understand what he -wanted. - -"Though it was tete-a-tete," Anatole continued, "still I can't..." - -"Is it satisfaction you want?" said Pierre ironically. - -"You could at least take back your words. What? If you want me to do -as you wish, eh?" - -"I take them back, I take them back!" said Pierre, "and I ask you to -forgive me." Pierre involuntarily glanced at the loose button. "And if -you require money for your journey..." - -Anatole smiled. The expression of that base and cringing smile, -which Pierre knew so well in his wife, revolted him. - -"Oh, vile and heartless brood!" he exclaimed, and left the room. - -Next day Anatole left for Petersburg. - - - - - -CHAPTER XXI - - -Pierre drove to Marya Dmitrievna's to tell her of the fulfillment of -her wish that Kuragin should be banished from Moscow. The whole -house was in a state of alarm and commotion. Natasha was very ill, -having, as Marya Dmitrievna told him in secret, poisoned herself the -night after she had been told that Anatole was married, with some -arsenic she had stealthily procured. After swallowing a little she had -been so frightened that she woke Sonya and told her what she had done. -The necessary antidotes had been administered in time and she was -now out of danger, though still so weak that it was out of the -question to move her to the country, and so the countess had been sent -for. Pierre saw the distracted count, and Sonya, who had a -tear-stained face, but he could not see Natasha. - -Pierre dined at the club that day and heard on all sides gossip -about the attempted abduction of Rostova. He resolutely denied these -rumors, assuring everyone that nothing had happened except that his -brother-in-law had proposed to her and been refused. It seemed to -Pierre that it was his duty to conceal the whole affair and -re-establish Natasha's reputation. - -He was awaiting Prince Andrew's return with dread and went every day -to the old prince's for news of him. - -Old Prince Bolkonski heard all the rumors current in the town from -Mademoiselle Bourienne and had read the note to Princess Mary in which -Natasha had broken off her engagement. He seemed in better spirits -than usual and awaited his son with great impatience. - -Some days after Anatole's departure Pierre received a note from -Prince Andrew, informing him of his arrival and asking him to come -to see him. - -As soon as he reached Moscow, Prince Andrew had received from his -father Natasha's note to Princess Mary breaking off her engagement -(Mademoiselle Bourienne had purloined it from Princess Mary and -given it to the old prince), and he heard from him the story of -Natasha's elopement, with additions. - -Prince Andrew had arrived in the evening and Pierre came to see -him next morning. Pierre expected to find Prince Andrew in almost -the same state as Natasha and was therefore surprised on entering -the drawing room to hear him in the study talking in a loud animated -voice about some intrigue going on in Petersburg. The old prince's -voice and another now and then interrupted him. Princess Mary came out -to meet Pierre. She sighed, looking toward the door of the room -where Prince Andrew was, evidently intending to express her sympathy -with his sorrow, but Pierre saw by her face that she was glad both -at what had happened and at the way her brother had taken the news -of Natasha's faithlessness. - -"He says he expected it," she remarked. "I know his pride will not -let him express his feelings, but still he has taken it better, far -better, than I expected. Evidently it had to be...." - -"But is it possible that all is really ended?" asked Pierre. - -Princess Mary looked at him with astonishment. She did not -understand how he could ask such a question. Pierre went into the -study. Prince Andrew, greatly changed and plainly in better health, -but with a fresh horizontal wrinkle between his brows, stood in -civilian dress facing his father and Prince Meshcherski, warmly -disputing and vigorously gesticulating. The conversation was about -Speranski--the news of whose sudden exile and alleged treachery had -just reached Moscow. - -"Now he is censured and accused by all who were enthusiastic about -him a month ago," Prince Andrew was saying, "and by those who were -unable to understand his aims. To judge a man who is in disfavor and -to throw on him all the blame of other men's mistakes is very easy, -but I maintain that if anything good has been accomplished in this -reign it was done by him, by him alone." - -He paused at the sight of Pierre. His face quivered and -immediately assumed a vindictive expression. - -"Posterity will do him justice," he concluded, and at once turned to -Pierre. - -"Well, how are you? Still getting stouter?" he said with -animation, but the new wrinkle on his forehead deepened. "Yes, I am -well," he said in answer to Pierre's question, and smiled. - -To Pierre that smile said plainly: "I am well, but my health is -now of no use to anyone." - -After a few words to Pierre about the awful roads from the Polish -frontier, about people he had met in Switzerland who knew Pierre, -and about M. Dessalles, whom he had brought from abroad to be his -son's tutor, Prince Andrew again joined warmly in the conversation -about Speranski which was still going on between the two old men. - -"If there were treason, or proofs of secret relations with Napoleon, -they would have been made public," he said with warmth and haste. "I -do not, and never did, like Speranski personally, but I like justice!" - -Pierre now recognized in his friend a need with which he was only -too familiar, to get excited and to have arguments about extraneous -matters in order to stifle thoughts that were too oppressive and too -intimate. When Prince Meshcherski had left, Prince Andrew took -Pierre's arm and asked him into the room that had been assigned him. A -bed had been made up there, and some open portmanteaus and trunks -stood about. Prince Andrew went to one and took out a small casket, -from which he drew a packet wrapped in paper. He did it all silently -and very quickly. He stood up and coughed. His face was gloomy and his -lips compressed. - -"Forgive me for troubling you..." - -Pierre saw that Prince Andrew was going to speak of Natasha, and his -broad face expressed pity and sympathy. This expression irritated -Prince Andrew, and in a determined, ringing, and unpleasant tone he -continued: - -"I have received a refusal from Countess Rostova and have heard -reports of your brother-in-law having sought her hand, or something of -that kind. Is that true?" - -"Both true and untrue," Pierre began; but Prince Andrew -interrupted him. - -"Here are her letters and her portrait," said he. - -He took the packet from the table and handed it to Pierre. - -"Give this to the countess... if you see her." - -"She is very ill," said Pierre. - -"Then she is here still?" said Prince Andrew. "And Prince -Kuragin?" he added quickly. - -"He left long ago. She has been at death's door." - -"I much regret her illness," said Prince Andrew; and he smiled -like his father, coldly, maliciously, and unpleasantly. - -"So Monsieur Kuragin has not honored Countess Rostova with his -hand?" said Prince Andrew, and he snorted several times. - -"He could not marry, for he was married already," said Pierre. - -Prince Andrew laughed disagreeably, again reminding one of his -father. - -"And where is your brother-in-law now, if I may ask?" he said. - -"He has gone to Peters... But I don't know," said Pierre. - -"Well, it doesn't matter," said Prince Andrew. "Tell Countess -Rostova that she was and is perfectly free and that I wish her all -that is good." - -Pierre took the packet. Prince Andrew, as if trying to remember -whether he had something more to say, or waiting to see if Pierre -would say anything, looked fixedly at him. - -"I say, do you remember our discussion in Petersburg?" asked Pierre, -"about..." - -"Yes," returned Prince Andrew hastily. "I said that a fallen woman -should be forgiven, but I didn't say I could forgive her. I can't." - -"But can this be compared...?" said Pierre. - -Prince Andrew interrupted him and cried sharply: "Yes, ask her -hand again, be magnanimous, and so on?... Yes, that would be very -noble, but I am unable to follow in that gentleman's footsteps. If you -wish to be my friend never speak to me of that... of all that! Well, -good-by. So you'll give her the packet?" - -Pierre left the room and went to the old prince and Princess Mary. - -The old man seemed livelier than usual. Princess Mary was the same -as always, but beneath her sympathy for her brother, Pierre noticed -her satisfaction that the engagement had been broken off. Looking at -them Pierre realized what contempt and animosity they all felt for the -Rostovs, and that it was impossible in their presence even to -mention the name of her who could give up Prince Andrew for anyone -else. - -At dinner the talk turned on the war, the approach of which was -becoming evident. Prince Andrew talked incessantly, arguing now with -his father, now with the Swiss tutor Dessalles, and showing an -unnatural animation, the cause of which Pierre so well understood. - - - - - -CHAPTER XXII - - -That same evening Pierre went to the Rostovs' to fulfill the -commission entrusted to him. Natasha was in bed, the count at the -Club, and Pierre, after giving the letters to Sonya, went to Marya -Dmitrievna who was interested to know how Prince Andrew had taken -the news. Ten minutes later Sonya came to Marya Dmitrievna. - -"Natasha insists on seeing Count Peter Kirilovich," said she. - -"But how? Are we to take him up to her? The room there has not -been tidied up." - -"No, she has dressed and gone into the drawing room," said Sonya. - -Marya Dmitrievna only shrugged her shoulders. - -"When will her mother come? She has worried me to death! Now mind, -don't tell her everything!" said she to Pierre. "One hasn't the -heart to scold her, she is so much to be pitied, so much to be -pitied." - -Natasha was standing in the middle of the drawing room, emaciated, -with a pale set face, but not at all shamefaced as Pierre expected -to find her. When he appeared at the door she grew flurried, evidently -undecided whether to go to meet him or to wait till he came up. - -Pierre hastened to her. He thought she would give him her hand as -usual; but she, stepping up to him, stopped, breathing heavily, her -arms hanging lifelessly just in the pose she used to stand in when she -went to the middle of the ballroom to sing, but with quite a different -expression of face. - -"Peter Kirilovich," she began rapidly, "Prince Bolkonski was your -friend--is your friend," she corrected herself. (It seemed to her that -everything that had once been must now be different.) "He told me once -to apply to you..." - -Pierre sniffed as he looked at her, but did not speak. Till then -he had reproached her in his heart and tried to despise her, but he -now felt so sorry for her that there was no room in his soul for -reproach. - -"He is here now: tell him... to for... forgive me!" She stopped -and breathed still more quickly, but did not shed tears. - -"Yes... I will tell him," answered Pierre; "but..." - -He did not know what to say. - -Natasha was evidently dismayed at the thought of what he might think -she had meant. - -"No, I know all is over," she said hurriedly. "No, that can never -be. I'm only tormented by the wrong I have done him. Tell him only -that I beg him to forgive, forgive, forgive me for everything...." - -She trembled all over and sat down on a chair. - -A sense of pity he had never before known overflowed Pierre's heart. - -"I will tell him, I will tell him everything once more," said -Pierre. "But... I should like to know one thing...." - -"Know what?" Natasha's eyes asked. - -"I should like to know, did you love..." Pierre did not know how -to refer to Anatole and flushed at the thought of him--"did you love -that bad man?" - -"Don't call him bad!" said Natasha. "But I don't know, don't know at -all...." - -She began to cry and a still greater sense of pity, tenderness, -and love welled up in Pierre. He felt the tears trickle under his -spectacles and hoped they would not be noticed. - -"We won't speak of it any more, my dear," said Pierre, and his -gentle, cordial tone suddenly seemed very strange to Natasha. - -"We won't speak of it, my dear--I'll tell him everything; but one -thing I beg of you, consider me your friend and if you want help, -advice, or simply to open your heart to someone--not now, but when -your mind is clearer think of me!" He took her hand and kissed it. -"I shall be happy if it's in my power..." - -Pierre grew confused. - -"Don't speak to me like that. I am not worth it!" exclaimed -Natasha and turned to leave the room, but Pierre held her hand. - -He knew he had something more to say to her. But when he said it -he was amazed at his own words. - -"Stop, stop! You have your whole life before you," said he to her. - -"Before me? No! All is over for me," she replied with shame and -self-abasement. - - "All over?" he repeated. "If I were not myself, but the handsomest, -cleverest, and best man in the world, and were free, I would this -moment ask on my knees for your hand and your love!" - -For the first time for many days Natasha wept tears of gratitude and -tenderness, and glancing at Pierre she went out of the room. - -Pierre too when she had gone almost ran into the anteroom, -restraining tears of tenderness and joy that choked him, and without -finding the sleeves of his fur cloak threw it on and got into his -sleigh. - -"Where to now, your excellency?" asked the coachman. - -"Where to?" Pierre asked himself. "Where can I go now? Surely not to -the Club or to pay calls?" All men seemed so pitiful, so poor, in -comparison with this feeling of tenderness and love he experienced: in -comparison with that softened, grateful, last look she had given him -through her tears. - -"Home!" said Pierre, and despite twenty-two degrees of frost -Fahrenheit he threw open the bearskin cloak from his broad chest and -inhaled the air with joy. - -It was clear and frosty. Above the dirty, ill-lit streets, above the -black roofs, stretched the dark starry sky. Only looking up at the sky -did Pierre cease to feel how sordid and humiliating were all mundane -things compared with the heights to which his soul had just been -raised. At the entrance to the Arbat Square an immense expanse of dark -starry sky presented itself to his eyes. Almost in the center of it, -above the Prechistenka Boulevard, surrounded and sprinkled on all -sides by stars but distinguished from them all by its nearness to -the earth, its white light, and its long uplifted tail, shone the -enormous and brilliant comet of 1812--the comet which was said to -portend all kinds of woes and the end of the world. In Pierre, -however, that comet with its long luminous tail aroused no feeling -of fear. On the contrary he gazed joyfully, his eyes moist with tears, -at this bright comet which, having traveled in its orbit with -inconceivable velocity through immeasurable space, seemed suddenly- -like an arrow piercing the earth--to remain fixed in a chosen spot, -vigorously holding its tail erect, shining and displaying its white -light amid countless other scintillating stars. It seemed to Pierre -that this comet fully responded to what was passing in his own -softened and uplifted soul, now blossoming into a new life. - - - - - -BOOK NINE: 1812 - - - - - -CHAPTER I - - -From the close of the year 1811 intensified arming and concentrating -of the forces of Western Europe began, and in 1812 these forces- -millions of men, reckoning those transporting and feeding the army- -moved from the west eastwards to the Russian frontier, toward which -since 1811 Russian forces had been similarly drawn. On the twelfth -of June, 1812, the forces of Western Europe crossed the Russian -frontier and war began, that is, an event took place opposed to -human reason and to human nature. Millions of men perpetrated -against one another such innumerable crimes, frauds, treacheries, -thefts, forgeries, issues of false money, burglaries, incendiarisms, -and murders as in whole centuries are not recorded in the annals of -all the law courts of the world, but which those who committed them -did not at the time regard as being crimes. - -What produced this extraordinary occurrence? What were its causes? -The historians tell us with naive assurance that its causes were the -wrongs inflicted on the Duke of Oldenburg, the nonobservance of the -Continental System, the ambition of Napoleon, the firmness of -Alexander, the mistakes of the diplomatists, and so on. - -Consequently, it would only have been necessary for Metternich, -Rumyantsev, or Talleyrand, between a levee and an evening party, to -have taken proper pains and written a more adroit note, or for -Napoleon to have written to Alexander: "My respected Brother, I -consent to restore the duchy to the Duke of Oldenburg"--and there -would have been no war. - -We can understand that the matter seemed like that to -contemporaries. It naturally seemed to Napoleon that the war was -caused by England's intrigues (as in fact he said on the island of St. -Helena). It naturally seemed to members of the English Parliament that -the cause of the war was Napoleon's ambition; to the Duke of -Oldenburg, that the cause of the war was the violence done to him; -to businessmen that the cause of the way was the Continental System -which was ruining Europe; to the generals and old soldiers that the -chief reason for the war was the necessity of giving them -employment; to the legitimists of that day that it was the need of -re-establishing les bons principes, and to the diplomatists of that -time that it all resulted from the fact that the alliance between -Russia and Austria in 1809 had not been sufficiently well concealed -from Napoleon, and from the awkward wording of Memorandum No. 178. -It is natural that these and a countless and infinite quantity of -other reasons, the number depending on the endless diversity of points -of view, presented themselves to the men of that day; but to us, to -posterity who view the thing that happened in all its magnitude and -perceive its plain and terrible meaning, these causes seem -insufficient. To us it is incomprehensible that millions of -Christian men killed and tortured each other either because Napoleon -was ambitious or Alexander was firm, or because England's policy was -astute or the Duke of Oldenburg wronged. We cannot grasp what -connection such circumstances have with the actual fact of slaughter -and violence: why because the Duke was wronged, thousands of men -from the other side of Europe killed and ruined the people of Smolensk -and Moscow and were killed by them. - -To us, their descendants, who are not historians and are not carried -away by the process of research and can therefore regard the event -with unclouded common sense, an incalculable number of causes -present themselves. The deeper we delve in search of these causes -the more of them we find; and each separate cause or whole series of -causes appears to us equally valid in itself and equally false by -its insignificance compared to the magnitude of the events, and by its -impotence--apart from the cooperation of all the other coincident -causes--to occasion the event. To us, the wish or objection of this or -that French corporal to serve a second term appears as much a cause as -Napoleon's refusal to withdraw his troops beyond the Vistula and to -restore the duchy of Oldenburg; for had he not wished to serve, and -had a second, a third, and a thousandth corporal and private also -refused, there would have been so many less men in Napoleon's army and -the war could not have occurred. - -Had Napoleon not taken offense at the demand that he should withdraw -beyond the Vistula, and not ordered his troops to advance, there would -have been no war; but had all his sergeants objected to serving a -second term then also there could have been no war. Nor could there -have been a war had there been no English intrigues and no Duke of -Oldenburg, and had Alexander not felt insulted, and had there not been -an autocratic government in Russia, or a Revolution in France and a -subsequent dictatorship and Empire, or all the things that produced -the French Revolution, and so on. Without each of these causes nothing -could have happened. So all these causes--myriads of causes--coincided -to bring it about. And so there was no one cause for that -occurrence, but it had to occur because it had to. Millions of men, -renouncing their human feelings and reason, had to go from west to -east to slay their fellows, just as some centuries previously hordes -of men had come from the east to the west, slaying their fellows. - -The actions of Napoleon and Alexander, on whose words the event -seemed to hang, were as little voluntary as the actions of any soldier -who was drawn into the campaign by lot or by conscription. This -could not be otherwise, for in order that the will of Napoleon and -Alexander (on whom the event seemed to depend) should be carried -out, the concurrence of innumerable circumstances was needed without -any one of which the event could not have taken place. It was -necessary that millions of men in whose hands lay the real power- -the soldiers who fired, or transported provisions and guns--should -consent to carry out the will of these weak individuals, and should -have been induced to do so by an infinite number of diverse and -complex causes. - -We are forced to fall back on fatalism as an explanation of -irrational events (that is to say, events the reasonableness of -which we do not understand). The more we try to explain such events in -history reasonably, the more unreasonable and incomprehensible do they -become to us. - -Each man lives for himself, using his freedom to attain his personal -aims, and feels with his whole being that he can now do or abstain -from doing this or that action; but as soon as he has done it, that -action performed at a certain moment in time becomes irrevocable and -belongs to history, in which it has not a free but a predestined -significance. - -There are two sides to the life of every man, his individual life, -which is the more free the more abstract its interests, and his -elemental hive life in which he inevitably obeys laws laid down for -him. - -Man lives consciously for himself, but is an unconscious -instrument in the attainment of the historic, universal, aims of -humanity. A deed done is irrevocable, and its result coinciding in -time with the actions of millions of other men assumes an historic -significance. The higher a man stands on the social ladder, the more -people he is connected with and the more power he has over others, the -more evident is the predestination and inevitability of his every -action. - -"The king's heart is in the hands of the Lord." - -A king is history's slave. - -History, that is, the unconscious, general, hive life of mankind, -uses every moment of the life of kings as a tool for its own purposes. - -Though Napoleon at that time, in 1812, was more convinced than -ever that it depended on him, verser (ou ne pas verser) le sang de ses -peuples*--as Alexander expressed it in the last letter he wrote him- -he had never been so much in the grip of inevitable laws, which -compelled him, while thinking that he was acting on his own -volition, to perform for the hive life--that is to say, for history- -whatever had to be performed. - - -*"To shed (or not to shed) the blood of his peoples." - - -The people of the west moved eastwards to slay their fellow men, and -by the law of coincidence thousands of minute causes fitted in and -co-ordinated to produce that movement and war: reproaches for the -nonobservance of the Continental System, the Duke of Oldenburg's -wrongs, the movement of troops into Prussia--undertaken (as it -seemed to Napoleon) only for the purpose of securing an armed peace, -the French Emperor's love and habit of war coinciding with his -people's inclinations, allurement by the grandeur of the preparations, -and the expenditure on those preparations and the need of obtaining -advantages to compensate for that expenditure, the intoxicating honors -he received in Dresden, the diplomatic negotiations which, in the -opinion of contemporaries, were carried on with a sincere desire to -attain peace, but which only wounded the self-love of both sides, -and millions of other causes that adapted themselves to -the event that was happening or coincided with it. - -When an apple has ripened and falls, why does it fall? Because of -its attraction to the earth, because its stalk withers, because it -is dried by the sun, because it grows heavier, because the wind shakes -it, or because the boy standing below wants to eat it? - -Nothing is the cause. All this is only the coincidence of conditions -in which all vital organic and elemental events occur. And the -botanist who finds that the apple falls because the cellular tissue -decays and so forth is equally right with the child who stands under -the tree and says the apple fell because he wanted to eat it and -prayed for it. Equally right or wrong is he who says that Napoleon -went to Moscow because he wanted to, and perished because Alexander -desired his destruction, and he who says that an undermined hill -weighing a million tons fell because the last navvy struck it for -the last time with his mattock. In historic events the so-called great -men are labels giving names to events, and like labels they have but -the smallest connection with the event itself. - -Every act of theirs, which appears to them an act of their own will, -is in an historical sense involuntary and is related to the whole -course of history and predestined from eternity. - - - - - -CHAPTER II - - -On the twenty-ninth of May Napoleon left Dresden, where he had spent -three weeks surrounded by a court that included princes, dukes, kings, -and even an emperor. Before leaving, Napoleon showed favor to the -emperor, kings, and princes who had deserved it, reprimanded the kings -and princes with whom he was dissatisfied, presented pearls and -diamonds of his own--that is, which he had taken from other kings- -to the Empress of Austria, and having, as his historian tells us, -tenderly embraced the Empress Marie Louise--who regarded him as her -husband, though he had left another wife in Paris--left her grieved by -the parting which she seemed hardly able to bear. Though the -diplomatists still firmly believed in the possibility of peace and -worked zealously to that end, and though the Emperor Napoleon -himself wrote a letter to Alexander, calling him Monsieur mon frere, -and sincerely assured him that he did not want war and would always -love and honor him--yet he set off to join his army, and at every -station gave fresh orders to accelerate the movement of his troops -from west to east. He went in a traveling coach with six horses, -surrounded by pages, aides-de-camp, and an escort, along the road to -Posen, Thorn, Danzig, and Konigsberg. At each of these towns thousands -of people met him with excitement and enthusiasm. - -The army was moving from west to east, and relays of six horses -carried him in the same direction. On the tenth of June,* coming up -with the army, he spent the night in apartments prepared for him on -the estate of a Polish count in the Vilkavisski forest. - - -*Old style. - - -Next day, overtaking the army, he went in a carriage to the -Niemen, and, changing into a Polish uniform, he drove to the riverbank -in order to select a place for the crossing. - -Seeing, on the other side, some Cossacks (les Cosaques) and the -wide-spreading steppes in the midst of which lay the holy city of -Moscow (Moscou, la ville sainte), the capital of a realm such as the -Scythia into which Alexander the Great had marched--Napoleon -unexpectedly, and contrary alike to strategic and diplomatic -considerations, ordered an advance, and the next day his army began to -cross the Niemen. - -Early in the morning of the twelfth of June he came out of his tent, -which was pitched that day on the steep left bank of the Niemen, and -looked through a spyglass at the streams of his troops pouring out -of the Vilkavisski forest and flowing over the three bridges thrown -across the river. The troops, knowing of the Emperor's presence, -were on the lookout for him, and when they caught sight of a figure in -an overcoat and a cocked hat standing apart from his suite in front of -his tent on the hill, they threw up their caps and shouted: "Vive -l'Empereur!" and one after another poured in a ceaseless stream out of -the vast forest that had concealed them and, separating, flowed on and -on by the three bridges to the other side. - -"Now we'll go into action. Oh, when he takes it in hand himself, -things get hot... by heaven!... There he is!... Vive l'Empereur! So -these are the steppes of Asia! It's a nasty country all the same. Au -revoir, Beauche; I'll keep the best palace in Moscow for you! Au -revoir. Good luck!... Did you see the Emperor? Vive l'Empereur!... -preur!--If they make me Governor of India, Gerard, I'll make you -Minister of Kashmir--that's settled. Vive l'Empereur! Hurrah! -hurrah! hurrah! The Cossacks--those rascals--see how they run! Vive -l'Empereur! There he is, do you see him? I've seen him twice, as I see -you now. The little corporal... I saw him give the cross to one of the -veterans.... Vive l'Empereur!" came the voices of men, old and -young, of most diverse characters and social positions. On the faces -of all was one common expression of joy at the commencement of the -long-expected campaign and of rapture and devotion to the man in the -gray coat who was standing on the hill. - -On the thirteenth of June a rather small, thoroughbred Arab horse -was brought to Napoleon. He mounted it and rode at a gallop to one -of the bridges over the Niemen, deafened continually by incessant -and rapturous acclamations which he evidently endured only because -it was impossible to forbid the soldiers to express their love of -him by such shouting, but the shouting which accompanied him -everywhere disturbed him and distracted him from the military cares -that had occupied him from the time he joined the army. He rode across -one of the swaying pontoon bridges to the farther side, turned sharply -to the left, and galloped in the direction of Kovno, preceded by -enraptured, mounted chasseurs of the Guard who, breathless with -delight, galloped ahead to clear a path for him through the troops. On -reaching the broad river Viliya, he stopped near a regiment of -Polish Uhlans stationed by the river. - -"Vivat!" shouted the Poles, ecstatically, breaking their ranks and -pressing against one another to see him. - -Napoleon looked up and down the river, dismounted, and sat down on a -log that lay on the bank. At a mute sign from him, a telescope was -handed him which he rested on the back of a happy page who had run -up to him, and he gazed at the opposite bank. Then he became -absorbed in a map laid out on the logs. Without lifting his head he -said something, and two of his aides-de-camp galloped off to the -Polish Uhlans. - -"What? What did he say?" was heard in the ranks of the Polish Uhlans -when one of the aides-de-camp rode up to them. - -The order was to find a ford and to cross the river. The colonel -of the Polish Uhlans, a handsome old man, flushed and, fumbling in his -speech from excitement, asked the aide-de-camp whether he would be -permitted to swim the river with his Uhlans instead of seeking a ford. -In evident fear of refusal, like a boy asking for permission to get on -a horse, he begged to be allowed to swim across the river before the -Emperor's eyes. The aide-de-camp replied that probably the Emperor -would not be displeased at this excess of zeal. - -As soon as the aide-de-camp had said this, the old mustached -officer, with happy face and sparkling eyes, raised his saber, shouted -"Vivat!" and, commanding the Uhlans to follow him, spurred his horse -and galloped into the river. He gave an angry thrust to his horse, -which had grown restive under him, and plunged into the water, heading -for the deepest part where the current was swift. Hundreds of Uhlans -galloped in after him. It was cold and uncanny in the rapid current in -the middle of the stream, and the Uhlans caught hold of one another as -they fell off their horses. Some of the horses were drowned and some -of the men; the others tried to swim on, some in the saddle and some -clinging to their horses' manes. They tried to make their way -forward to the opposite bank and, though there was a ford one third of -a mile away, were proud that they were swimming and drowning in this -river under the eyes of the man who sat on the log and was not even -looking at what they were doing. When the aide-de-camp, having -returned and choosing an opportune moment, ventured to draw the -Emperor's attention to the devotion of the Poles to his person, the -little man in the gray overcoat got up and, having summoned -Berthier, began pacing up and down the bank with him, giving him -instructions and occasionally glancing disapprovingly at the -drowning Uhlans who distracted his attention. - -For him it was no new conviction that his presence in any part of -the world, from Africa to the steppes of Muscovy alike, was enough -to dumfound people and impel them to insane self-oblivion. He called -for his horse and rode to his quarters. - -Some forty Uhlans were drowned in the river, though boats were -sent to their assistance. The majority struggled back to the bank from -which they had started. The colonel and some of his men got across and -with difficulty clambered out on the further bank. And as soon as they -had got out, in their soaked and streaming clothes, they shouted -"Vivat!" and looked ecstatically at the spot where Napoleon had been -but where he no longer was and at that moment considered themselves -happy. - -That evening, between issuing one order that the forged Russian -paper money prepared for use in Russia should be delivered as -quickly as possible and another that a Saxon should be shot, on whom a -letter containing information about the orders to the French army -had been found, Napoleon also gave instructions that the Polish -colonel who had needlessly plunged into the river should be enrolled -in the Legion d'honneur of which Napoleon was himself the head. - -Quos vult perdere dementat.* - - -*Those whom (God) wishes to destroy he drives mad. - - - - - -CHAPTER III - - -The Emperor of Russia had, meanwhile, been in Vilna for more than -a month, reviewing troops and holding maneuvers. Nothing was ready for -the war that everyone expected and to prepare for which the Emperor -had come from Petersburg. There was no general plan of action. The -vacillation between the various plans that were proposed had even -increased after the Emperor had been at headquarters for a month. Each -of the three armies had its own commander in chief, but there was no -supreme commander of all the forces, and the Emperor did not assume -that responsibility himself. - -The longer the Emperor remained in Vilna the less did everybody- -tired of waiting--prepare for the war. All the efforts of those who -surrounded the sovereign seemed directed merely to making him spend -his time pleasantly and forget that war was impending. - -In June, after many balls and fetes given by the Polish magnates, by -the courtiers, and by the Emperor himself, it occurred to one of the -Polish aides-de-camp in attendance that a dinner and ball should be -given for the Emperor by his aides-de-camp. This idea was eagerly -received. The Emperor gave his consent. The aides-de-camp collected -money by subscription. The lady who was thought to be most pleasing to -the Emperor was invited to act as hostess. Count Bennigsen, being a -landowner in the Vilna province, offered his country house for the -fete, and the thirteenth of June was fixed for a ball, dinner, -regatta, and fireworks at Zakret, Count Bennigsen's country seat. - - -The very day that Napoleon issued the order to cross the Niemen, and -his vanguard, driving off the Cossacks, crossed the Russian -frontier, Alexander spent the evening at the entertainment given by -his aides-de-camp at Bennigsen's country house. - -It was a gay and brilliant fete. Connoisseurs of such matters -declared that rarely had so many beautiful women been assembled in one -place. Countess Bezukhova was present among other Russian ladies who -had followed the sovereign from Petersburg to Vilna and eclipsed the -refined Polish ladies by her massive, so called Russian type of -beauty. The Emperor noticed her and honored her with a dance. - -Boris Drubetskoy, having left his wife in Moscow and being for the -present en garcon (as he phrased it), was also there and, though not -an aide-de-camp, had subscribed a large sum toward the expenses. Boris -was now a rich man who had risen to high honors and no longer sought -patronage but stood on an equal footing with the highest of those of -his own age. He was meeting Helene in Vilna after not having seen -her for a long time and did not recall the past, but as Helene was -enjoying the favors of a very important personage and Boris had only -recently married, they met as good friends of long standing. - -At midnight dancing was still going on. Helene, not having a -suitable partner, herself offered to dance the mazurka with Boris. -They were the third couple. Boris, coolly looking at Helene's dazzling -bare shoulders which emerged from a dark, gold-embroidered, gauze -gown, talked to her of old acquaintances and at the same time, unaware -of it himself and unnoticed by others, never for an instant ceased -to observe the Emperor who was in the same room. The Emperor was not -dancing, he stood in the doorway, stopping now one pair and now -another with gracious words which he alone knew how to utter. - -As the mazurka began, Boris saw that Adjutant General Balashev, -one of those in closest attendance on the Emperor, went up to him -and contrary to court etiquette stood near him while he was talking to -a Polish lady. Having finished speaking to her, the Emperor looked -inquiringly at Balashev and, evidently understanding that he only -acted thus because there were important reasons for so doing, nodded -slightly to the lady and turned to him. Hardly had Balashev begun to -speak before a look of amazement appeared on the Emperor's face. He -took Balashev by the arm and crossed the room with him, -unconsciously clearing a path seven yards wide as the people on both -sides made way for him. Boris noticed Arakcheev's excited face when -the sovereign went out with Balashev. Arakcheev looked at the -Emperor from under his brow and, sniffing with his red nose, stepped -forward from the crowd as if expecting the Emperor to address him. -(Boris understood that Arakcheev envied Balashev and was displeased -that evidently important news had reached the Emperor otherwise than -through himself.) - -But the Emperor and Balashev passed out into the illuminated -garden without noticing Arakcheev who, holding his sword and -glancing wrathfully around, followed some twenty paces behind them. - -All the time Boris was going through the figures of the mazurka, -he was worried by the question of what news Balashev had brought and -how he could find it out before others. In the figure in which he -had to choose two ladies, he whispered to Helene that he meant to -choose Countess Potocka who, he thought, had gone out onto the -veranda, and glided over the parquet to the door opening into the -garden, where, seeing Balashev and the Emperor returning to the -veranda, he stood still. They were moving toward the door. Boris, -fluttering as if he had not had time to withdraw, respectfully pressed -close to the doorpost with bowed head. - -The Emperor, with the agitation of one who has been personally -affronted, was finishing with these words: - -"To enter Russia without declaring war! I will not make peace as -long as a single armed enemy remains in my country!" It seemed to -Boris that it gave the Emperor pleasure to utter these words. He was -satisfied with the form in which he had expressed his thoughts, but -displeased that Boris had overheard it. - -"Let no one know of it!" the Emperor added with a frown. - -Boris understood that this was meant for him and, closing his -eyes, slightly bowed his head. The Emperor re-entered the ballroom and -remained there about another half-hour. - -Boris was thus the first to learn the news that the French army -had crossed the Niemen and, thanks to this, was able to show certain -important personages that much that was concealed from others was -usually known to him, and by this means he rose higher in their -estimation. - - -The unexpected news of the French having crossed the Niemen was -particularly startling after a month of unfulfilled expectations, -and at a ball. On first receiving the news, under the influence of -indignation and resentment the Emperor had found a phrase that pleased -him, fully expressed his feelings, and has since become famous. On -returning home at two o'clock that night he sent for his secretary, -Shishkov, and told him to write an order to the troops and a -rescript to Field Marshal Prince Saltykov, in which he insisted on the -words being inserted that he would not make peace so long as a -single armed Frenchman remained on Russian soil. - -Next day the following letter was sent to Napoleon: - - -Monsieur mon frere, - -Yesterday I learned that, despite the loyalty which I have kept my -engagements with Your Majesty, your troops have crossed the Russian -frontier, and I have this moment received from Petersburg a note, in -which Count Lauriston informs me, as a reason for this aggression, -that Your Majesty has considered yourself to be in a state of war with -me from the time Prince Kuragin asked for his passports. The reasons -on which the Duc de Bassano based his refusal to deliver them to him -would never have led me to suppose that that could serve as a -pretext for aggression. In fact, the ambassador, as he himself has -declared, was never authorized to make that demand, and as soon as I -was informed of it I let him know how much I disapproved of it and -ordered him to remain at his post. If Your Majesty does not intend -to shed the blood of our peoples for such a misunderstanding, and -consents to withdraw your troops from Russian territory, I will regard -what has passed as not having occurred and an understanding between us -will be possible. In the contrary case, Your Majesty, I shall see -myself forced to repel an attack that nothing on my part has provoked. -It still depends on Your Majesty to preserve humanity from the -calamity of another war. I am, etc., - (signed) Alexander - - - - - -CHAPTER IV - - -At two in the morning of the fourteenth of June, the Emperor, having -sent for Balashev and read him his letter to Napoleon, ordered him -to take it and hand it personally to the French Emperor. When -dispatching Balashev, the Emperor repeated to him the words that he -would not make peace so long as a single armed enemy remained on -Russian soil and told him to transmit those words to Napoleon. -Alexander did not insert them in his letter to Napoleon, because -with his characteristic tact he felt it would be injudicious to use -them at a moment when a last attempt at reconciliation was being made, -but he definitely instructed Balashev to repeat them personally to -Napoleon. - -Having set off in the small hours of the fourteenth, accompanied -by a bugler and two Cossacks, Balashev reached the French outposts -at the village of Rykonty, on the Russian side of the Niemen, by dawn. -There he was stopped by French cavalry sentinels. - -A French noncommissioned officer of hussars, in crimson uniform -and a shaggy cap, shouted to the approaching Balashev to halt. -Balashev did not do so at once, but continued to advance along the -road at a walking pace. - -The noncommissioned officer frowned and, muttering words of abuse, -advanced his horse's chest against Balashev, put his hand to his -saber, and shouted rudely at the Russian general, asking: was he -deaf that he did not do as he was told? Balashev mentioned who he was. -The noncommissioned officer began talking with his comrades about -regimental matters without looking at the Russian general. - -After living at the seat of the highest authority and power, after -conversing with the Emperor less than three hours before, and in -general being accustomed to the respect due to his rank in the -service, Balashev found it very strange here on Russian soil to -encounter this hostile, and still more this disrespectful, application -of brute force to himself. - -The sun was only just appearing from behind the clouds, the air -was fresh and dewy. A herd of cattle was being driven along the road -from the village, and over the fields the larks rose trilling, one -after another, like bubbles rising in water. - -Balashev looked around him, awaiting the arrival of an officer -from the village. The Russian Cossacks and bugler and the French -hussars looked silently at one another from time to time. - -A French colonel of hussars, who had evidently just left his bed, -came riding from the village on a handsome sleek gray horse, -accompanied by two hussars. The officer, the soldiers, and their -horses all looked smart and well kept. - -It was that first period of a campaign when troops are still in full -trim, almost like that of peacetime maneuvers, but with a shade of -martial swagger in their clothes, and a touch of the gaiety and spirit -of enterprise which always accompany the opening of a campaign. - -The French colonel with difficulty repressed a yawn, but was -polite and evidently understood Balashev's importance. He led him past -his soldiers and behind the outposts and told him that his wish to -be presented to the Emperor would most likely be satisfied -immediately, as the Emperor's quarters were, he believed, not far off. - -They rode through the village of Rykonty, past tethered French -hussar horses, past sentinels and men who saluted their colonel and -stared with curiosity at a Russian uniform, and came out at the -other end of the village. The colonel said that the commander of the -division was a mile and a quarter away and would receive Balashev -and conduct him to his destination. - -The sun had by now risen and shone gaily on the bright verdure. - -They had hardly ridden up a hill, past a tavern, before they saw a -group of horsemen coming toward them. In front of the group, on a -black horse with trappings that glittered in the sun, rode a tall -man with plumes in his hat and black hair curling down to his -shoulders. He wore a red mantle, and stretched his long legs forward -in French fashion. This man rode toward Balashev at a gallop, his -plumes flowing and his gems and gold lace glittering in the bright -June sunshine. - -Balashev was only two horses' length from the equestrian with the -bracelets, plunies, necklaces, and gold embroidery, who was -galloping toward him with a theatrically solemn countenance, when -Julner, the French colonel, whispered respectfully: "The King of -Naples!" It was, in fact, Murat, now called "King of Naples." Though -it was quite incomprehensible why he should be King of Naples, he -was called so, and was himself convinced that he was so, and therefore -assumed a more solemn and important air than formerly. He was so -sure that he really was the King of Naples that when, on the eve of -his departure from that city, while walking through the streets with -his wife, some Italians called out to him: "Viva il re!"* he turned to -his wife with a pensive smile and said: "Poor fellows, they don't know -that I am leaving them tomorrow!" - - -*"Long live the king." - - -But though he firmly believed himself to be King of Naples and -pitied the grief felt by the subjects he was abandoning, latterly, -after he had been ordered to return to military service--and -especially since his last interview with Napoleon in Danzig, when -his august brother-in-law had told him: "I made you King that you -should reign in my way, but not in yours!"--he had cheerfully taken up -his familiar business, and--like a well-fed but not overfat horse that -feels himself in harness and grows skittish between the shafts--he -dressed up in clothes as variegated and expensive as possible, and -gaily and contentedly galloped along the roads of Poland, without -himself knowing why or whither. - -On seeing the Russian general he threw back his head, with its -long hair curling to his shoulders, in a majestically royal manner, -and looked inquiringly at the French colonel. The colonel respectfully -informed His Majesty of Balashev's mission, whose name he could not -pronounce. - -"De Bal-macheve!" said the King (overcoming by his assurance the -difficulty that had presented itself to the colonel). "Charmed to make -your acquaintance, General!" he added, with a gesture of kingly -condescension. - -As soon as the King began to speak loud and fast his royal dignity -instantly forsook him, and without noticing it he passed into his -natural tone of good-natured familiarity. He laid his hand on the -withers of Balashev's horse and said: - -"Well, General, it all looks like war," as if regretting a -circumstance of which he was unable to judge. - -"Your Majesty," replied Balashev, "my master, the Emperor, does -not desire war and as Your Majesty sees..." said Balashev, using the -words Your Majesty at every opportunity, with the affectation -unavoidable in frequently addressing one to whom the title was still a -novelty. - -Murat's face beamed with stupid satisfaction as he listened to -"Monsieur de Bal-macheve." But royaute oblige!* and he felt it -incumbent on him, as a king and an ally, to confer on state affairs -with Alexander's envoy. He dismounted, took Balashev's arm, and moving -a few steps away from his suite, which waited respectfully, began to -pace up and down with him, trying to speak significantly. He -referred to the fact that the Emperor Napoleon had resented the demand -that he should withdraw his troops from Prussia, especially when -that demand became generally known and the dignity of France was -thereby offended. - - -*"Royalty has its obligations." - - -Balashev replied that there was "nothing offensive in the demand, -because..." but Murat interrupted him. - -"Then you don't consider the Emperor Alexander the aggressor?" he -asked unexpectedly, with a kindly and foolish smile. - -Balashev told him why he considered Napoleon to be the originator of -the war. - -"Oh, my dear general!" Murat again interrupted him, "with all my -heart I wish the Emperors may arrange the affair between them, and -that the war begun by no wish of mine may finish as quickly as -possible!" said he, in the tone of a servant who wants to remain -good friends with another despite a quarrel between their masters. - -And he went on to inquiries about the Grand Duke and the state of -his health, and to reminiscences of the gay and amusing times he had -spent with him in Naples. Then suddenly, as if remembering his royal -dignity, Murat solemnly drew himself up, assumed the pose in which -he had stood at his coronation, and, waving his right arm, said: - -"I won't detain you longer, General. I wish success to your -mission," and with his embroidered red mantle, his flowing feathers, -and his glittering ornaments, he rejoined his suite who were -respectfully awaiting him. - -Balashev rode on, supposing from Murat's words that he would very -soon be brought before Napoleon himself. But instead of that, at the -next village the sentinels of Davout's infantry corps detained him -as the pickets of the vanguard had done, and an adjutant of the -corps commander, who was fetched, conducted him into the village to -Marshal Davout. - - - - - -CHAPTER V - - -Davout was to Napoleon what Arakcheev was to Alexander--though not a -coward like Arakcheev, he was as precise, as cruel, and as unable to -express his devotion to his monarch except by cruelty. - -In the organism of states such men are necessary, as wolves are -necessary in the organism of nature, and they always exist, always -appear and hold their own, however incongruous their presence and -their proximity to the head of the government may be. This -inevitability alone can explain how the cruel Arakcheev, who tore -out a grenadier's mustache with his own hands, whose weak nerves -rendered him unable to face danger, and who was neither an educated -man nor a courtier, was able to maintain his powerful position with -Alexander, whose own character was chivalrous, noble, and gentle. - -Balashev found Davout seated on a barrel in the shed of a -peasant's hut, writing--he was auditing accounts. Better quarters -could have been found him, but Marshal Davout was one of those men who -purposely put themselves in most depressing conditions to have a -justification for being gloomy. For the same reason they are always -hard at work and in a hurry. "How can I think of the bright side of -life when, as you see, I am sitting on a barrel and working in a dirty -shed?" the expression of his face seemed to say. The chief pleasure -and necessity of such men, when they encounter anyone who shows -animation, is to flaunt their own dreary, persistent activity. -Davout allowed himself that pleasure when Balashev was brought in. -He became still more absorbed in his task when the Russian general -entered, and after glancing over his spectacles at Balashev's face, -which was animated by the beauty of the morning and by his talk with -Murat, he did not rise or even stir, but scowled still more and -sneered malevolently. - -When he noticed in Balashev's face the disagreeable impression -this reception produced, Davout raised his head and coldly asked -what he wanted. - -Thinking he could have been received in such a manner only because -Davout did not know that he was adjutant general to the Emperor -Alexander and even his envoy to Napoleon, Balashev hastened to -inform him of his rank and mission. Contrary to his expectation, -Davout, after hearing him, became still surlier and ruder. - -"Where is your dispatch?" he inquired. "Give it to me. I will send -it to the Emperor." - -Balashev replied that he had been ordered to hand it personally to -the Emperor. - -"Your Emperor's orders are obeyed in your army, but here," said -Davout, "you must do as you're told." - -And, as if to make the Russian general still more conscious of his -dependence on brute force, Davout sent an adjutant to call the officer -on duty. - -Balashev took out the packet containing the Emperor's letter and -laid it on the table (made of a door with its hinges still hanging -on it, laid across two barrels). Davout took the packet and read the -inscription. - -"You are perfectly at liberty to treat me with respect or not," -protested Balashev, "but permit me to observe that I have the honor to -be adjutant general to His Majesty...." - -Davout glanced at him silently and plainly derived pleasure from the -signs of agitation and confusion which appeared on Balashev's face. - -"You will be treated as is fitting," said he and, putting the packet -in his pocket, left the shed. - -A minute later the marshal's adjutant, de Castres, came in and -conducted Balashev to the quarters assigned him. - -That day he dined with the marshal, at the same board on the -barrels. - -Next day Davout rode out early and, after asking Balashev to come to -him, peremptorily requested him to remain there, to move on with the -baggage train should orders come for it to move, and to talk to no one -except Monsieur de Castres. - -After four days of solitude, ennui, and consciousness of his -impotence and insignificance--particularly acute by contrast with -the sphere of power in which he had so lately moved--and after several -marches with the marshal's baggage and the French army, which occupied -the whole district, Balashev was brought to Vilna--now occupied by the -French--through the very gate by which he had left it four days -previously. - -Next day the imperial gentleman-in-waiting, the Comte de Turenne, -came to Balashev and informed him of the Emperor Napoleon's wish to -honor him with an audience. - -Four days before, sentinels of the Preobrazhensk regiment had -stood in front of the house to which Balashev was conducted, and now -two French grenadiers stood there in blue uniforms unfastened in front -and with shaggy caps on their heads, and an escort of hussars and -Uhlans and a brilliant suite of aides-de-camp, pages, and generals, -who were waiting for Napoleon to come out, were standing at the porch, -round his saddle horse and his Mameluke, Rustan. Napoleon received -Balashev in the very house in Vilna from which Alexander had -dispatched him on his mission. - - - - - -CHAPTER VI - - -Though Balashev was used to imperial pomp, he was amazed at the -luxury and magnificence of Napoleon's court. - -The Comte de Turenne showed him into a big reception room where many -generals, gentlemen-in-waiting, and Polish magnates--several of whom -Balashev had seen at the court of the Emperor of Russia--were waiting. -Duroc said that Napoleon would receive the Russian general before -going for his ride. - -After some minutes, the gentleman-in-waiting who was on duty came -into the great reception room and, bowing politely, asked Balashev -to follow him. - -Balashev went into a small reception room, one door of which led -into a study, the very one from which the Russian Emperor had -dispatched him on his mission. He stood a minute or two, waiting. He -heard hurried footsteps beyond the door, both halves of it were opened -rapidly; all was silent and then from the study the sound was heard of -other steps, firm and resolute--they were those of Napoleon. He had -just finished dressing for his ride, and wore a blue uniform, -opening in front over a white waistcoat so long that it covered his -rotund stomach, white leather breeches tightly fitting the fat -thighs of his short legs, and Hessian boots. His short hair had -evidently just been brushed, but one lock hung down in the middle of -his broad forehead. His plump white neck stood out sharply above the -black collar of his uniform, and he smelled of Eau de Cologne. His -full face, rather young-looking, with its prominent chin, wore a -gracious and majestic expression of imperial welcome. - -He entered briskly, with a jerk at every step and his head -slightly thrown back. His whole short corpulent figure with broad -thick shoulders, and chest and stomach involuntarily protruding, had -that imposing and stately appearance one sees in men of forty who live -in comfort. It was evident, too, that he was in the best of spirits -that day. - -He nodded in answer to Balashav's low and respectful bow, and coming -up to him at once began speaking like a man who values every moment of -his time and does not condescend to prepare what he has to say but -is sure he will always say the right thing and say it well. - -"Good day, General!" said he. "I have received the letter you -brought from the Emperor Alexander and am very glad to see you." He -glanced with his large eyes into Balashav's face and immediately -looked past him. - -It was plain that Balashev's personality did not interest him at -all. Evidently only what took place within his own mind interested -him. Nothing outside himself had any significance for him, because -everything in the world, it seemed to him, depended entirely on his -will. - -"I do not, and did not, desire war," he continued, "but it has -been forced on me. Even now" (he emphasized the word) "I am ready to -receive any explanations you can give me." - -And he began clearly and concisely to explain his reasons for -dissatisfaction with the Russian government. Judging by the calmly -moderate and amicable tone in which the French Emperor spoke, Balashev -was firmly persuaded that he wished for peace and intended to enter -into negotiations. - -When Napoleon, having finished speaking, looked inquiringly at the -Russian envoy, Balashev began a speech he had prepared long before: -"Sire! The Emperor, my master..." but the sight of the Emperor's -eyes bent on him confused him. "You are flurried--compose yourself!" -Napoleon seemed to say, as with a scarcely perceptible smile he looked -at Balashev's uniform and sword. - -Balashev recovered himself and began to speak. He said that the -Emperor Alexander did not consider Kurakin's demand for his -passports a sufficient cause for war; that Kurakin had acted on his -own initiative and without his sovereign's assent, that the Emperor -Alexander did not desire war, and had no relations with England. - -"Not yet!" interposed Napoleon, and, as if fearing to give vent to -his feelings, he frowned and nodded slightly as a sign that Balashev -might proceed. - -After saying all he had been instructed to say, Balashev added -that the Emperor Alexander wished for peace, but would not enter -into negotiations except on condition that... Here Balashev hesitated: -he remembered the words the Emperor Alexander had not written in his -letter, but had specially inserted in the rescript to Saltykov and had -told Balashev to repeat to Napoleon. Balashev remembered these -words, "So long as a single armed foe remains on Russian soil," but -some complex feeling restrained him. He could not utter them, though -he wished to do so. He grew confused and said: "On condition that -the French army retires beyond the Niemen." - -Napoleon noticed Balashev's embarrassment when uttering these last -words; his face twitched and the calf of his left leg began to -quiver rhythmically. Without moving from where he stood he began -speaking in a louder tone and more hurriedly than before. During the -speech that followed, Balashev, who more than once lowered his eyes, -involuntarily noticed the quivering of Napoleon's left leg which -increased the more Napoleon raised his voice. - -"I desire peace, no less than the Emperor Alexander," he began. -"Have I not for eighteen months been doing everything to obtain it? -I have waited eighteen months for explanations. But in order to -begin negotiations, what is demanded of me?" he said, frowning and -making an energetic gesture of inquiry with his small white plump -hand. - -"The withdrawal of your army beyond the Niemen, sire," replied -Balashev. - -"The Niemen?" repeated Napoleon. "So now you want me to retire -beyond the Niemen--only the Niemen?" repeated Napoleon, looking -straight at Balashev. - -The latter bowed his head respectfully. - -Instead of the demand of four months earlier to withdraw from -Pomerania, only a withdrawal beyond the Niemen was now demanded. -Napoleon turned quickly and began to pace the room. - -"You say the demand now is that I am to withdraw beyond the Niemen -before commencing negotiations, but in just the same way two months -ago the demand was that I should withdraw beyond the Vistula and the -Oder, and yet you are willing to negotiate." - -He went in silence from one corner of the room to the other and -again stopped in front of Balashev. Balashev noticed that his left leg -was quivering faster than before and his face seemed petrified in -its stern expression. This quivering of his left leg was a thing -Napoleon was conscious of. "The vibration of my left calf is a great -sign with me," he remarked at a later date. - -"Such demands as to retreat beyond the Vistula and Oder may be -made to a Prince of Baden, but not to me!" Napoleon almost screamed, -quite to his own surprise. "If you gave me Petersburg and Moscow I -could not accept such conditions. You say I have begun this war! But -who first joined his army? The Emperor Alexander, not I! And you offer -me negotiations when I have expended millions, when you are in -alliance with England, and when your position is a bad one. You -offer me negotiations! But what is the aim of your alliance with -England? What has she given you?" he continued hurriedly, evidently no -longer trying to show the advantages of peace and discuss its -possibility, but only to prove his own rectitude and power and -Alexander's errors and duplicity. - -The commencement of his speech had obviously been made with the -intention of demonstrating the advantages of his position and -showing that he was nevertheless willing to negotiate. But he had -begun talking, and the more he talked the less could he control his -words. - -The whole purport of his remarks now was evidently to exalt -himself and insult Alexander--just what he had least desired at the -commencement of the interview. - -"I hear you have made peace with Turkey?" - -Balashev bowed his head affirmatively. - -"Peace has been concluded..." he began. - -But Napoleon did not let him speak. He evidently wanted to do all -the talking himself, and continued to talk with the sort of -eloquence and unrestrained irritability to which spoiled people are so -prone. - -"Yes, I know you have made peace with the Turks without obtaining -Moldavia and Wallachia; I would have given your sovereign those -provinces as I gave him Finland. Yes," he went on, "I promised and -would have given the Emperor Alexander Moldavia and Wallachia, and now -he won't have those splendid provinces. Yet he might have united -them to his empire and in a single reign would have extended Russia -from the Gulf of Bothnia to the mouths of the Danube. Catherine the -Great could not have done more," said Napoleon, growing more and -more excited as he paced up and down the room, repeating to Balashev -almost the very words he had used to Alexander himself at Tilsit. "All -that, he would have owed to my friendship. Oh, what a splendid reign!" -he repeated several times, then paused, drew from his pocket a gold -snuffbox, lifted it to his nose, and greedily sniffed at it. - -"What a splendid reign the Emperor Alexander's might have been!" - -He looked compassionately at Balashev, and as soon as the latter -tried to make some rejoinder hastily interrupted him. - -"What could he wish or look for that he would not have obtained -through my friendship?" demanded Napoleon, shrugging his shoulders -in perplexity. "But no, he has preferred to surround himself with my -enemies, and with whom? With Steins, Armfeldts, Bennigsens, and -Wintzingerodes! Stein, a traitor expelled from his own country; -Armfeldt, a rake and an intriguer; Wintzingerode, a fugitive French -subject; Bennigsen, rather more of a soldier than the others, but -all the same an incompetent who was unable to do anything in 1807 -and who should awaken terrible memories in the Emperor Alexander's -mind.... Granted that were they competent they might be made use -of," continued Napoleon--hardly able to keep pace in words with the -rush of thoughts that incessantly sprang up, proving how right and -strong he was (in his perception the two were one and the same)- -"but they are not even that! They are neither fit for war nor peace! -Barclay is said to be the most capable of them all, but I cannot say -so, judging by his first movements. And what are they doing, all these -courtiers? Pfuel proposes, Armfeldt disputes, Bennigsen considers, and -Barclay, called on to act, does not know what to decide on, and time -passes bringing no result. Bagration alone is a military man. He's -stupid, but he has experience, a quick eye, and resolution.... And -what role is your young monarch playing in that monstrous crowd? -They compromise him and throw on him the responsibility for all that -happens. A sovereign should not be with the army unless he is a -general!" said Napoleon, evidently uttering these words as a direct -challenge to the Emperor. He knew how Alexander desired to be a -military commander. - -"The campaign began only a week ago, and you haven't even been -able to defend Vilna. You are cut in two and have been driven out of -the Polish provinces. Your army is grumbling." - -"On the contrary, Your Majesty," said Balashev, hardly able to -remember what had been said to him and following these verbal -fireworks with difficulty, "the troops are burning with eagerness..." - -"I know everything!" Napoleon interrupted him. "I know everything. I -know the number of your battalions as exactly as I know my own. You -have not two hundred thousand men, and I have three times that number. -I give you my word of honor," said Napoleon, forgetting that his -word of honor could carry no weight--"I give you my word of honor that -I have five hundred and thirty thousand men this side of the -Vistula. The Turks will be of no use to you; they are worth nothing -and have shown it by making peace with you. As for the Swedes--it is -their fate to be governed by mad kings. Their king was insane and they -changed him for another--Bernadotte, who promptly went mad--for no -Swede would ally himself with Russia unless he were mad." - -Napoleon grinned maliciously and again raised his snuffbox to his -nose. - -Balashev knew how to reply to each of Napoleon's remarks, and -would have done so; he continually made the gesture of a man wishing -to say something, but Napoleon always interrupted him. To the -alleged insanity of the Swedes, Balashev wished to reply that when -Russia is on her side Sweden is practically an island: but Napoleon -gave an angry exclamation to drown his voice. Napoleon was in that -state of irritability in which a man has to talk, talk, and talk, -merely to convince himself that he is in the right. Balashev began -to feel uncomfortable: as envoy he feared to demean his dignity and -felt the necessity of replying; but, as a man, he shrank before the -transport of groundless wrath that had evidently seized Napoleon. He -knew that none of the words now uttered by Napoleon had any -significance, and that Napoleon himself would be ashamed of them -when he came to his senses. Balashev stood with downcast eyes, looking -at the movements of Napoleon's stout legs and trying to avoid -meeting his eyes. - -"But what do I care about your allies?" said Napoleon. "I have -allies--the Poles. There are eighty thousand of them and they fight -like lions. And there will be two hundred thousand of them." - -And probably still more perturbed by the fact that he had uttered -this obvious falsehood, and that Balashev still stood silently -before him in the same attitude of submission to fate, Napoleon -abruptly turned round, drew close to Balashev's face, and, -gesticulating rapidly and energetically with his white hands, almost -shouted: - -"Know that if you stir up Prussia against me, I'll wipe it off the -map of Europe!" he declared, his face pale and distorted by anger, and -he struck one of his small hands energetically with the other. "Yes, I -will throw you back beyond the Dvina and beyond the Dnieper, and -will re-erect against you that barrier which it was criminal and blind -of Europe to allow to be destroyed. Yes, that is what will happen to -you. That is what you have gained by alienating me!" And he walked -silently several times up and down the room, his fat shoulders -twitching. - -He put his snuffbox into his waistcoat pocket, took it out again, -lifted it several times to his nose, and stopped in front of Balashev. -He paused, looked ironically straight into Balashev's eyes, and said -in a quiet voice: - -"And yet what a splendid reign your master might have had!" - -Balashev, feeling it incumbent on him to reply, said that from the -Russian side things did not appear in so gloomy a light. Napoleon -was silent, still looking derisively at him and evidently not -listening to him. Balashev said that in Russia the best results were -expected from the war. Napoleon nodded condescendingly, as if to -say, "I know it's your duty to say that, but you don't believe it -yourself. I have convinced you." - -When Balashev had ended, Napoleon again took out his snuffbox, -sniffed at it, and stamped his foot twice on the floor as a signal. -The door opened, a gentleman-in-waiting, bending respectfully, -handed the Emperor his hat and gloves; another brought him a pocket -handkerchief. Napoleon, without giving them a glance, turned to -Balashev: - -"Assure the Emperor Alexander from me," said he, taking his hat, -"that I am as devoted to him as before: I know him thoroughly and very -highly esteem his lofty qualities. I will detain you no longer, -General; you shall receive my letter to the Emperor." - -And Napoleon went quickly to the door. Everyone in the reception -room rushed forward and descended the staircase. - - - - - -CHAPTER VII - - -After all that Napoleon had said to him--those bursts of anger and -the last dryly spoken words: "I will detain you no longer, General; -you shall receive my letter," Balashev felt convinced that Napoleon -would not wish to see him, and would even avoid another meeting with -him--an insulted envoy--especially as he had witnessed his unseemly -anger. But, to his surprise, Balashev received, through Duroc, an -invitation to dine with the Emperor that day. - -Bessieres, Caulaincourt, and Berthier were present at that dinner. - -Napoleon met Balashev cheerfully and amiably. He not only showed -no sign of constraint or self-reproach on account of his outburst that -morning, but, on the contrary, tried to reassure Balashev. It was -evident that he had long been convinced that it was impossible for him -to make a mistake, and that in his perception whatever he did was -right, not because it harmonized with any idea of right and wrong, but -because he did it. - -The Emperor was in very good spirits after his ride through Vilna, -where crowds of people had rapturously greeted and followed him. -From all the windows of the streets through which he rode, rugs, -flags, and his monogram were displayed, and the Polish ladies, -welcoming him, waved their handkerchiefs to him. - -At dinner, having placed Balashev beside him, Napoleon not only -treated him amiably but behaved as if Balashev were one of his own -courtiers, one of those who sympathized with his plans and ought to -rejoice at his success. In the course of conversation he mentioned -Moscow and questioned Balashev about the Russian capital, not merely -as an interested traveler asks about a new city he intends to visit, -but as if convinced that Balashev, as a Russian, must be flattered -by his curiosity. - -"How many inhabitants are there in Moscow? How many houses? Is it -true that Moscow is called 'Holy Moscow'? How many churches are -there in Moscow?" he asked. - -And receiving the reply that there were more than two hundred -churches, he remarked: - -"Why such a quantity of churches?" - -"The Russians are very devout," replied Balashev. - -"But a large number of monasteries and churches is always a sign -of the backwardness of a people," said Napoleon, turning to -Caulaincourt for appreciation of this remark. - -Balashev respectfully ventured to disagree with the French Emperor. - -"Every country has its own character," said he. - -"But nowhere in Europe is there anything like that," said Napoleon. - -"I beg your Majesty's pardon," returned Balashev, "besides Russia -there is Spain, where there are also many churches and monasteries." - -This reply of Balashev's, which hinted at the recent defeats of -the French in Spain, was much appreciated when he related it at -Alexander's court, but it was not much appreciated at Napoleon's -dinner, where it passed unnoticed. - -The uninterested and perplexed faces of the marshals showed that -they were puzzled as to what Balashev's tone suggested. "If there is a -point we don't see it, or it is not at all witty," their expressions -seemed to say. So little was his rejoinder appreciated that Napoleon -did not notice it at all and naively asked Balashev through what towns -the direct road from there to Moscow passed. Balashev, who was on -the alert all through the dinner, replied that just as "all roads lead -to Rome," so all roads lead to Moscow: there were many roads, and -"among them the road through Poltava, which Charles XII chose." -Balashev involuntarily flushed with pleasure at the aptitude of this -reply, but hardly had he uttered the word Poltava before -Caulaincourt began speaking of the badness of the road from Petersburg -to Moscow and of his Petersburg reminiscences. - -After dinner they went to drink coffee in Napoleon's study, which -four days previously had been that of the Emperor Alexander. -Napoleon sat down, toying with his Sevres coffee cup, and motioned -Balashev to a chair beside him. - -Napoleon was in that well-known after-dinner mood which, more than -any reasoned cause, makes a man contented with himself and disposed to -consider everyone his friend. It seemed to him that he was -surrounded by men who adored him: and he felt convinced that, after -his dinner, Balashev too was his friend and worshiper. Napoleon turned -to him with a pleasant, though slightly ironic, smile. - -"They tell me this is the room the Emperor Alexander occupied? -Strange, isn't it, General?" he said, evidently not doubting that this -remark would be agreeable to his hearer since it went to prove his, -Napoleon's, superiority to Alexander. - -Balashev made no reply and bowed his head in silence. - -"Yes. Four days ago in this room, Wintzingerode and Stein were -deliberating," continued Napoleon with the same derisive and -self-confident smile. "What I can't understand," he went on, "is -that the Emperor Alexander has surrounded himself with my personal -enemies. That I do not... understand. Has he not thought that I may -the same?" and he turned inquiringly to Balashev, and evidently this -thought turned him back on to the track of his morning's anger, -which was still fresh in him. - -"And let him know that I will do so!" said Napoleon, rising and -pushing his cup away with his hand. "I'll drive all his Wurttemberg, -Baden, and Weimar relations out of Germany.... Yes. I'll drive them -out. Let him prepare an asylum for them in Russia!" - -Balashev bowed his head with an air indicating that he would like to -make his bow and leave, and only listened because he could not help -hearing what was said to him. Napoleon did not notice this expression; -he treated Balashev not as an envoy from his enemy, but as a man now -fully devoted to him and who must rejoice at his former master's -humiliation. - -"And why has the Emperor Alexander taken command of the armies? What -is the good of that? War is my profession, but his business is to -reign and not to command armies! Why has he taken on himself such a -responsibility?" - -Again Napoleon brought out his snuffbox, paced several times up -and down the room in silence, and then, suddenly and unexpectedly, -went up to Balashev and with a slight smile, as confidently, -quickly, and simply as if he were doing something not merely -important but pleasing to Balashev, he raised his hand to the -forty-year-old Russian general's face and, taking him by the ear, -pulled it gently, smiling with his lips only. - -To have one's ear pulled by the Emperor was considered the -greatest honor and mark of favor at the French court. - -"Well, adorer and courtier of the Emperor Alexander, why don't you -say anything?" said he, as if it was ridiculous, in his presence, to -be the adorer and courtier of anyone but himself, Napoleon. "Are the -horses ready for the general?" he added, with a slight inclination -of his head in reply to Balashev's bow. "Let him have mine, he has a -long way to go!" - -The letter taken by Balashev was the last Napoleon sent to -Alexander. Every detail of the interview was communicated to the -Russian monarch, and the war began... - - - - - -CHAPTER VIII - - -After his interview with Pierre in Moscow, Prince Andrew went to -Petersburg, on business as he told his family, but really to meet -Anatole Kuragin whom he felt it necessary to encounter. On reaching -Petersburg he inquired for Kuragin but the latter had already left the -city. Pierre had warned his brother-in-law that Prince Andrew was on -his track. Anatole Kuragin promptly obtained an appointment from the -Minister of War and went to join the army in Moldavia. While in -Petersburg Prince Andrew met Kutuzov, his former commander who was -always well disposed toward him, and Kutuzov suggested that he -should accompany him to the army in Moldavia, to which the old general -had been appointed commander in chief. So Prince Andrew, having -received an appointment on the headquarters staff, left for Turkey. - -Prince Andrew did not think it proper to write and challenge -Kuragin. He thought that if he challenged him without some fresh cause -it might compromise the young Countess Rostova and so he wanted to -meet Kuragin personally in order to find a fresh pretext for a duel. -But he again failed to meet Kuragin in Turkey, for soon after Prince -Andrew arrived, the latter returned to Russia. In a new country, -amid new conditions, Prince Andrew found life easier to bear. After -his betrothed had broken faith with him--which he felt the more -acutely the more he tried to conceal its effects--the surroundings -in which he had been happy became trying to him, and the freedom and -independence he had once prized so highly were still more so. Not only -could he no longer think the thoughts that had first come to him as he -lay gazing at the sky on the field of Austerlitz and had later -enlarged upon with Pierre, and which had filled his solitude at -Bogucharovo and then in Switzerland and Rome, but he even dreaded to -recall them and the bright and boundless horizons they had -revealed. He was now concerned only with the nearest practical matters -unrelated to his past interests, and he seized on these the more -eagerly the more those past interests were closed to him. It was as if -that lofty, infinite canopy of heaven that had once towered above -him had suddenly turned into a low, solid vault that weighed him down, -in which all was clear, but nothing eternal or mysterious. - -Of the activities that presented themselves to him, army service was -the simplest and most familiar. As a general on duty on Kutuzov's -staff, he applied himself to business with zeal and perseverance and -surprised Kutuzov by his willingness and accuracy in work. Not -having found Kuragin in Turkey, Prince Andrew did not think it -necessary to rush back to Russia after him, but all the same he knew -that however long it might be before he met Kuragin, despite his -contempt for him and despite all the proofs he deduced to convince -himself that it was not worth stooping to a conflict with him--he knew -that when he did meet him he would not be able to resist calling him -out, any more than a ravenous man can help snatching at food. And -the consciousness that the insult was not yet avenged, that his rancor -was still unspent, weighed on his heart and poisoned the artificial -tranquillity which he managed to obtain in Turkey by means of -restless, plodding, and rather vainglorious and ambitious activity. - -In the year 1812, when news of the war with Napoleon reached -Bucharest--where Kutuzov had been living for two months, passing his -days and nights with a Wallachian woman--Prince Andrew asked Kutuzov -to transfer him to the Western Army. Kutuzov, who was already weary of -Bolkonski's activity which seemed to reproach his own idleness, very -readily let him go and gave him a mission to Barclay de Tolly. - -Before joining the Western Army which was then, in May, encamped -at Drissa, Prince Andrew visited Bald Hills which was directly on -his way, being only two miles off the Smolensk highroad. During the -last three years there had been so many changes in his life, he had -thought, felt, and seen so much (having traveled both in the east -and the west), that on reaching Bald Hills it struck him as strange -and unexpected to find the way of life there unchanged and still the -same in every detail. He entered through the gates with their stone -pillars and drove up the avenue leading to the house as if he were -entering an enchanted, sleeping castle. The same old stateliness, -the same cleanliness, the same stillness reigned there, and inside -there was the same furniture, the same walls, sounds, and smell, and -the same timid faces, only somewhat older. Princess Mary was still the -same timid, plain maiden getting on in years, uselessly and -joylessly passing the best years of her life in fear and constant -suffering. Mademoiselle Bourienne was the same coquettish, -self-satisfied girl, enjoying every moment of her existence and full -of joyous hopes for the future. She had merely become more -self-confident, Prince Andrew thought. Dessalles, the tutor he had -brought from Switzerland, was wearing a coat of Russian cut and -talking broken Russian to the servants, but was still the same -narrowly intelligent, conscientious, and pedantic preceptor. The old -prince had changed in appearance only by the loss of a tooth, which -left a noticeable gap on one side of his mouth; in character he was -the same as ever, only showing still more irritability and -skepticism as to what was happening in the world. Little Nicholas -alone had changed. He had grown, become rosier, had curly dark hair, -and, when merry and laughing, quite unconsciously lifted the upper lip -of his pretty little mouth just as the little princess used to do. -He alone did not obey the law of immutability in the enchanted, -sleeping castle. But though externally all remained as of old, the -inner relations of all these people had changed since Prince Andrew -had seen them last. The household was divided into two alien and -hostile camps, who changed their habits for his sake and only met -because he was there. To the one camp belonged the old prince, -Madmoiselle Bourienne, and the architect; to the other Princess -Mary, Dessalles, little Nicholas, and all the old nurses and maids. - -During his stay at Bald Hills all the family dined together, but -they were ill at ease and Prince Andrew felt that he was a visitor for -whose sake an exception was being made and that his presence made them -all feel awkward. Involuntarily feeling this at dinner on the first -day, he was taciturn, and the old prince noticing this also became -morosely dumb and retired to his apartments directly after dinner. -In the evening, when Prince Andrew went to him and, trying to rouse -him, began to tell him of the young Count Kamensky's campaign, the old -prince began unexpectedly to talk about Princess Mary, blaming her for -her superstitions and her dislike of Mademoiselle Bourienne, who, he -said, was the only person really attached to him. - -The old prince said that if he was ill it was only because of -Princess Mary: that she purposely worried and irritated him, and -that by indulgence and silly talk she was spoiling little Prince -Nicholas. The old prince knew very well that he tormented his daughter -and that her life was very hard, but he also knew that he could not -help tormenting her and that she deserved it. "Why does Prince Andrew, -who sees this, say nothing to me about his sister? Does he think me -a scoundrel, or an old fool who, without any reason, keeps his own -daughter at a distance and attaches this Frenchwoman to himself? He -doesn't understand, so I must explain it, and he must hear me out," -thought the old prince. And he began explaining why he could not put -up with his daughter's unreasonable character. - -"If you ask me," said Prince Andrew, without looking up (he was -censuring his father for the first time in his life), "I did not -wish to speak about it, but as you ask me I will give you my frank -opinion. If there is any misunderstanding and discord between you -and Mary, I can't blame her for it at all. I know how she loves and -respects you. Since you ask me," continued Prince Andrew, becoming -irritable--as he was always liable to do of late--"I can only say that -if there are any misunderstandings they are caused by that worthless -woman, who is not fit to be my sister's companion." - -The old man at first stared fixedly at his son, and an unnatural -smile disclosed the fresh gap between his teeth to which Prince Andrew -could not get accustomed. - -"What companion, my dear boy? Eh? You've already been talking it -over! Eh?" - -"Father, I did not want to judge," said Prince Andrew, in a hard and -bitter tone, "but you challenged me, and I have said, and always shall -say, that Mary is not to blame, but those to blame--the one to -blame--is that Frenchwoman." - -"Ah, he has passed judgment... passed judgement!" said the old man -in a low voice and, as it seemed to Prince Andrew, with some -embarrassment, but then he suddenly jumped up and cried: "Be off, be -off! Let not a trace of you remain here!..." - - -Prince Andrew wished to leave at once, but Princess Mary persuaded -him to stay another day. That day he did not see his father, who did -not leave his room and admitted no one but Mademoiselle Bourienne -and Tikhon, but asked several times whether his son had gone. Next -day, before leaving, Prince Andrew went to his son's rooms. The boy, -curly-headed like his mother and glowing with health, sat on his knee, -and Prince Andrew began telling him the story of Bluebeard, but fell -into a reverie without finishing the story. He thought not of this -pretty child, his son whom he held on his knee, but of himself. He -sought in himself either remorse for having angered his father or -regret at leaving home for the first time in his life on bad terms -with him, and was horrified to find neither. What meant still more -to him was that he sought and did not find in himself the former -tenderness for his son which he had hoped to reawaken by caressing the -boy and taking him on his knee. - -"Well, go on!" said his son. - -Prince Andrew, without replying, put him down from his knee and went -out of the room. - -As soon as Prince Andrew had given up his daily occupations, and -especially on returning to the old conditions of life amid which he -had been happy, weariness of life overcame him with its former -intensity, and he hastened to escape from these memories and to find -some work as soon as possible. - -"So you've decided to go, Andrew?" asked his sister. - -"Thank God that I can," replied Prince Andrew. "I am very sorry -you can't." - -"Why do you say that?" replied Princess Mary. "Why do you say -that, when you are going to this terrible war, and he is so old? -Mademoiselle Bourienne says he has been asking about you...." - -As soon as she began to speak of that, her lips trembled and her -tears began to fall. Prince Andrew turned away and began pacing the -room. - -"Ah, my God! my God! When one thinks who and what--what trash--can -cause people misery!" he said with a malignity that alarmed Princess -Mary. - -She understood that when speaking of "trash" he referred not only to -Mademoiselle Bourienne, the cause of her misery, but also to the man -who had ruined his own happiness. - -"Andrew! One thing I beg, I entreat of you!" she said, touching -his elbow and looking at him with eyes that shone through her tears. -"I understand you" (she looked down). "Don't imagine that sorrow is -the work of men. Men are His tools." She looked a little above -Prince Andrew's head with the confident, accustomed look with which -one looks at the place where a familiar portrait hangs. "Sorrow is -sent by Him, not by men. Men are His instruments, they are not to -blame. If you think someone has wronged you, forget it and forgive! We -have no right to punish. And then you will know the happiness of -forgiving." - -"If I were a woman I would do so, Mary. That is a woman's virtue. -But a man should not and cannot forgive and forget," he replied, and -though till that moment he had not been thinking of Kuragin, all his -unexpended anger suddenly swelled up in his heart. - -"If Mary is already persuading me forgive, it means that I ought -long ago to have punished him," he thought. And giving her no -further reply, he began thinking of the glad vindictive moment when he -would meet Kuragin who he knew was now in the army. - -Princess Mary begged him to stay one day more, saying that she -knew how unhappy her father would be if Andrew left without being -reconciled to him, but Prince Andrew replied that he would probably -soon be back again from the army and would certainly write to his -father, but that the longer he stayed now the more embittered their -differences would become. - -"Good-by, Andrew! Remember that misfortunes come from God, and men -are never to blame," were the last words he heard from his sister when -he took leave of her. - -"Then it must be so!" thought Prince Andrew as he drove out of the -avenue from the house at Bald Hills. "She, poor innocent creature, -is left to be victimized by an old man who has outlived his wits. -The old man feels he is guilty, but cannot change himself. My boy is -growing up and rejoices in life, in which like everybody else he -will deceive or be deceived. And I am off to the army. Why? I myself -don't know. I want to meet that man whom I despise, so as to give -him a chance to kill and laugh at me!" - -These conditions of life had been the same before, but then they -were all connected, while now they had all tumbled to pieces. Only -senseless things, lacking coherence, presented themselves one after -another to Prince Andrew's mind. - - - - - -CHAPTER IX - - -Prince Andrew reached the general headquarters of the army at the -end of June. The first army, with which was the Emperor, occupied -the fortified camp at Drissa; the second army was retreating, trying -to effect a junction with the first one from which it was said to be -cut off by large French forces. Everyone was dissatisfied with the -general course of affairs in the Russian army, but no one -anticipated any danger of invasion of the Russian provinces, and no -one thought the war would extend farther than the western, the Polish, -provinces. - -Prince Andrew found Barclay de Tolly, to whom he had been -assigned, on the bank of the Drissa. As there was not a single town or -large village in the vicinity of the camp, the immense number of -generals and courtiers accompanying the army were living in the best -houses of the villages on both sides of the river, over a radius of -six miles. Barclay de Tolly was quartered nearly three miles from -the Emperor. He received Bolkonski stiffly and coldly and told him -in his foreign accent that he would mention him to the Emperor for a -decision as to his employment, but asked him meanwhile to remain on -his staff. Anatole Kuragin, whom Prince Andrew had hoped to find -with the army, was not there. He had gone to Petersburg, but Prince -Andrew was glad to hear this. His mind was occupied by the interests -of the center that was conducting a gigantic war, and he was glad to -be free for a while from the distraction caused by the thought of -Kuragin. During the first four days, while no duties were required -of him, Prince Andrew rode round the whole fortified camp and, by -the aid of his own knowledge and by talks with experts, tried to -form a definite opinion about it. But the question whether the camp -was advantageous or disadvantageous remained for him undecided. -Already from his military experience and what he had seen in the -Austrian campaign, he had come to the conclusion that in war the -most deeply considered plans have no significance and that all depends -on the way unexpected movements of the enemy--that cannot be foreseen- -are met, and on how and by whom the whole matter is handled. To -clear up this last point for himself, Prince Andrew, utilizing his -position and acquaintances, tried to fathom the character of the -control of the army and of the men and parties engaged in it, and he -deduced for himself the following of the state of affairs. - -While the Emperor had still been at Vilna, the forces had been -divided into three armies. First, the army under Barclay de Tolly, -secondly, the army under Bagration, and thirdly, the one commanded -by Tormasov. The Emperor was with the first army, but not as commander -in chief. In the orders issued it was stated, not that the Emperor -would take command, but only that he would be with the army. The -Emperor, moreover, had with him not a commander in chief's staff but -the imperial headquarters staff. In attendance on him was the head -of the imperial staff, Quartermaster General Prince Volkonski, as well -as generals, imperial aides-de-camp, diplomatic officials, and a large -number of foreigners, but not the army staff. Besides these, there -were in attendance on the Emperor without any definite appointments: -Arakcheev, the ex-Minister of War; Count Bennigsen, the senior general -in rank; the Grand Duke Tsarevich Constantine Pavlovich; Count -Rumyantsev, the Chancellor; Stein, a former Prussian minister; -Armfeldt, a Swedish general; Pfuel, the chief author of the plan of -campaign; Paulucci, an adjutant general and Sardinian emigre; -Wolzogen--and many others. Though these men had no military -appointment in the army, their position gave them influence, and often -a corps commander, or even the commander in chief, did not know in -what capacity he was questioned by Bennigsen, the Grand Duke, -Arakcheev, or Prince Volkonski, or was given this or that advice and -did not know whether a certain order received in the form of advice -emanated from the man who gave it or from the Emperor and whether it -had to be executed or not. But this was only the external condition; -the essential significance of the presence of the Emperor and of all -these people, from a courtier's point of view (and in an Emperor's -vicinity all became courtiers), was clear to everyone. It was this: -the Emperor did not assume the title of commander in chief, but -disposed of all the armies; the men around him were his assistants. -Arakcheev was a faithful custodian to enforce order and acted as the -sovereign's bodyguard. Bennigsen was a landlord in the Vilna -province who appeared to be doing the honors of the district, but -was in reality a good general, useful as an adviser and ready at -hand to replace Barclay. The Grand Duke was there because it suited -him to be. The ex-Minister Stein was there because his advice was -useful and the Emperor Alexander held him in high esteem personally. -Armfeldt virulently hated Napoleon and was a general full of -self-confidence, a quality that always influenced Alexander. -Paulucci was there because he was bold and decided in speech. The -adjutants general were there because they always accompanied the -Emperor, and lastly and chiefly Pfuel was there because he had drawn -up the plan of campaign against Napoleon and, having induced Alexander -to believe in the efficacy of that plan, was directing the whole -business of the war. With Pfuel was Wolzogen, who expressed Pfuel's -thoughts in a more comprehensible way than Pfuel himself (who was a -harsh, bookish theorist, self-confident to the point of despising -everyone else) was able to do. - -Besides these Russians and foreigners who propounded new and -unexpected ideas every day--especially the foreigners, who did so with -a boldness characteristic of people employed in a country not their -own--there were many secondary personages accompanying the army -because their principals were there. - -Among the opinions and voices in this immense, restless, -brilliant, and proud sphere, Prince Andrew noticed the following -sharply defined subdivisions of and parties: - -The first party consisted of Pfuel and his adherents--military -theorists who believed in a science of war with immutable laws--laws -of oblique movements, outflankings, and so forth. Pfuel and his -adherents demanded a retirement into the depths of the country in -accordance with precise laws defined by a pseudo-theory of war, and -they saw only barbarism, ignorance, or evil intention in every -deviation from that theory. To this party belonged the foreign nobles, -Wolzogen, Wintzingerode, and others, chiefly Germans. - -The second party was directly opposed to the first; one extreme, -as always happens, was met by representatives of the other. The -members of this party were those who had demanded an advance from -Vilna into Poland and freedom from all prearranged plans. Besides -being advocates of bold action, this section also represented -nationalism, which made them still more one-sided in the dispute. They -were Russians: Bagration, Ermolov (who was beginning to come to the -front), and others. At that time a famous joke of Ermolov's was -being circulated, that as a great favor he had petitioned the -Emperor to make him a German. The men of that party, remembering -Suvorov, said that what one had to do was not to reason, or stick pins -into maps, but to fight, beat the enemy, keep him out of Russia, and -not let the army get discouraged. - -To the third party--in which the Emperor had most confidence- -belonged the courtiers who tried to arrange compromises between the -other two. The members of this party, chiefly civilians and to whom -Arakcheev belonged, thought and said what men who have no -convictions but wish to seem to have some generally say. They said -that undoubtedly war, particularly against such a genius as -Bonaparte (they called him Bonaparte now), needs most deeply devised -plans and profound scientific knowledge and in that respect Pfuel -was a genius, but at the same time it had to be acknowledged that -the theorists are often one sided, and therefore one should not -trust them absolutely, but should also listen to what Pfuel's -opponents and practical men of experience in warfare had to say, and -then choose a middle course. They insisted on the retention of the -camp at Drissa, according to Pfuel's plan, but on changing the -movements of the other armies. Though, by this course, neither one aim -nor the other could be attained, yet it seemed best to the adherents -of this third party. - -Of a fourth opinion the most conspicuous representative was the -Tsarevich, who could not forget his disillusionment at Austerlitz, -where he had ridden out at the head of the Guards, in his casque and -cavalry uniform as to a review, expecting to crush the French -gallantly; but unexpectedly finding himself in the front line had -narrowly escaped amid the general confusion. The men of this party had -both the quality and the defect of frankness in their opinions. They -feared Napoleon, recognized his strength and their own weakness, and -frankly said so. They said: "Nothing but sorrow, shame, and ruin -will come of all this! We have abandoned Vilna and Vitebsk and shall -abandon Drissa. The only reasonable thing left to do is to conclude -peace as soon as possible, before we are turned out of Petersburg." - -This view was very general in the upper army circles and found -support also in Petersburg and from the chancellor, Rumyantsev, who, -for other reasons of state, was in favor of peace. - -The fifth party consisted of those who were adherents of Barclay -de Tolly, not so much as a man but as minister of war and commander in -chief. "Be he what he may" (they always began like that), "he is an -honest, practical man and we have nobody better. Give him real -power, for war cannot be conducted successfully without unity of -command, and he will show what he can do, as he did in Finland. If our -army is well organized and strong and has withdrawn to Drissa -without suffering any defeats, we owe this entirely to Barclay. If -Barclay is now to be superseded by Bennigsen all will be lost, for -Bennigsen showed his incapacity already in 1807." - -The sixth party, the Bennigsenites, said, on the contrary, that at -any rate there was no one more active and experienced than -Bennigsen: "and twist about as you may, you will have to come to -Bennigsen eventually. Let the others make mistakes now!" said they, -arguing that our retirement to Drissa was a most shameful reverse -and an unbroken series of blunders. "The more mistakes that are made -the better. It will at any rate be understood all the sooner that -things cannot go on like this. What is wanted is not some Barclay or -other, but a man like Bennigsen, who made his mark in 1807, and to -whom Napoleon himself did justice--a man whose authority would be -willingly recognized, and Bennigsen is the only such man." - -The seventh party consisted of the sort of people who are always -to be found, especially around young sovereigns, and of whom there -were particularly many round Alexander--generals and imperial -aides-de-camp passionately devoted to the Emperor, not merely as a -monarch but as a man, adoring him sincerely and disinterestedly, as -Rostov had done in 1805, and who saw in him not only all the virtues -but all human capabilities as well. These men, though enchanted with -the sovereign for refusing the command of the army, yet blamed him for -such excessive modesty, and only desired and insisted that their -adored sovereign should abandon his diffidence and openly announce -that he would place himself at the head of the army, gather round -him a commander in chief's staff, and, consulting experienced -theoreticians and practical men where necessary, would himself lead -the troops, whose spirits would thereby be raised to the highest -pitch. - -The eighth and largest group, which in its enormous numbers was to -the others as ninety-nine to one, consisted of men who desired neither -peace nor war, neither an advance nor a defensive camp at the Drissa -or anywhere else, neither Barclay nor the Emperor, neither Pfuel nor -Bennigsen, but only the one most essential thing--as much advantage -and pleasure for themselves as possible. In the troubled waters of -conflicting and intersecting intrigues that eddied about the Emperor's -headquarters, it was possible to succeed in many ways unthinkable at -other times. A man who simply wished to retain his lucrative post -would today agree with Pfuel, tomorrow with his opponent, and the -day after, merely to avoid responsibility or to please the Emperor, -would declare that he had no opinion at all on the matter. Another who -wished to gain some advantage would attract the Emperor's attention by -loudly advocating the very thing the Emperor had hinted at the day -before, and would dispute and shout at the council, beating his breast -and challenging those who did not agree with him to duels, thereby -proving that he was prepared to sacrifice himself for the common good. -A third, in the absence of opponents, between two councils would -simply solicit a special gratuity for his faithful services, well -knowing that at that moment people would be too busy to refuse him. -A fourth while seemingly overwhelmed with work would often come -accidentally under the Emperor's eye. A fifth, to achieve his -long-cherished aim of dining with the Emperor, would stubbornly insist -on the correctness or falsity of some newly emerging opinion and for -this object would produce arguments more or less forcible and correct. - -All the men of this party were fishing for rubles, decorations, -and promotions, and in this pursuit watched only the weathercock of -imperial favor, and directly they noticed it turning in any direction, -this whole drone population of the army began blowing hard that way, -so that it was all the harder for the Emperor to turn it elsewhere. -Amid the uncertainties of the position, with the menace of serious -danger giving a peculiarly threatening character to everything, amid -this vortex of intrigue, egotism, conflict of views and feelings, -and the diversity of race among these people--this eighth and -largest party of those preoccupied with personal interests imparted -great confusion and obscurity to the common task. Whatever question -arose, a swarm of these drones, without having finished their -buzzing on a previous theme, flew over to the new one and by their hum -drowned and obscured the voices of those who were disputing honestly. - -From among all these parties, just at the time Prince Andrew reached -the army, another, a ninth party, was being formed and was beginning -to raise its voice. This was the party of the elders, reasonable men -experienced and capable in state affairs, who, without sharing any -of those conflicting opinions, were able to take a detached view of -what was going on at the staff at headquarters and to consider means -of escape from this muddle, indecision, intricacy, and weakness. - -The men of this party said and thought that what was wrong -resulted chiefly from the Emperor's presence in the army with his -military court and from the consequent presence there of an -indefinite, conditional, and unsteady fluctuation of relations, -which is in place at court but harmful in an army; that a sovereign -should reign but not command the army, and that the only way out of -the position would be for the Emperor and his court to leave the army; -that the mere presence of the Emperor paralyzed the action of fifty -thousand men required to secure his personal safety, and that the -worst commander in chief if independent would be better than the -very best one trammeled by the presence and authority of the monarch. - -Just at the time Prince Andrew was living unoccupied at Drissa, -Shishkov, the Secretary of State and one of the chief -representatives of this party, wrote a letter to the Emperor which -Arakcheev and Balashev agreed to sign. In this letter, availing -himself of permission given him by the Emperor to discuss the -general course of affairs, he respectfully suggested--on the plea that -it was necessary for the sovereign to arouse a warlike spirit in the -people of the capital--that the Emperor should leave the army. - -That arousing of the people by their sovereign and his call to -them to defend their country--the very incitement which was the -chief cause of Russia's triumph in so far as it was produced by the -Tsar's personal presence in Moscow--was suggested to the Emperor, -and accepted by him, as a pretext for quitting the army. - - - - - -CHAPTER X - - -This letter had not yet been presented to the Emperor when -Barclay, one day at dinner, informed Bolkonski that the sovereign -wished to see him personally, to question him about Turkey, and that -Prince Andrew was to present himself at Bennigsen's quarters at six -that evening. - -News was received at the Emperor's quarters that very day of a fresh -movement by Napoleon which might endanger the army--news -subsequently found to be false. And that morning Colonel Michaud had -ridden round the Drissa fortifications with the Emperor and had -pointed out to him that this fortified camp constructed by Pfuel, -and till then considered a chef-d'oeuvre of tactical science which -would ensure Napoleon's destruction, was an absurdity, threatening the -destruction of the Russian army. - -Prince Andrew arrived at Bennigsen's quarters--a country gentleman's -house of moderate size, situated on the very banks of the river. -Neither Bennigsen nor the Emperor was there, but Chernyshev, the -Emperor's aide-de-camp, received Bolkonski and informed him that the -Emperor, accompanied by General Bennigsen and Marquis Paulucci, had -gone a second time that day to inspect the fortifications of the -Drissa camp, of the suitability of which serious doubts were beginning -to be felt. - -Chernyshev was sitting at a window in the first room with a French -novel in his hand. This room had probably been a music room; there was -still an organ in it on which some rugs were piled, and in one -corner stood the folding bedstead of Bennigsen's adjutant. This -adjutant was also there and sat dozing on the rolled-up bedding, -evidently exhausted by work or by feasting. Two doors led from the -room, one straight on into what had been the drawing room, and -another, on the right, to the study. Through the first door came the -sound of voices conversing in German and occasionally in French. In -that drawing room were gathered, by the Emperor's wish, not a military -council (the Emperor preferred indefiniteness), but certain persons -whose opinions he wished to know in view of the impending -difficulties. It was not a council of war, but, as it were, a -council to elucidate certain questions for the Emperor personally. -To this semicouncil had been invited the Swedish General Armfeldt, -Adjutant General Wolzogen, Wintzingerode (whom Napoleon had referred -to as a renegade French subject), Michaud, Toll, Count Stein who was -not a military man at all, and Pfuel himself, who, as Prince Andrew -had heard, was the mainspring of the whole affair. Prince Andrew had -an opportunity of getting a good look at him, for Pfuel arrived soon -after himself and, in passing through to the drawing room, stopped a -minute to speak to Chernyshev. - -At first sight, Pfuel, in his ill-made uniform of a Russian general, -which fitted him badly like a fancy costume, seemed familiar to Prince -Andrew, though he saw him now for the first time. There was about -him something of Weyrother, Mack, and Schmidt, and many other German -theorist-generals whom Prince Andrew had seen in 1805, but he was more -typical than any of them. Prince Andrew had never yet seen a German -theorist in whom all the characteristics of those others were united -to such an extent. - -Pfuel was short and very thin but broad-boned, of coarse, robust -build, broad in the hips, and with prominent shoulder blades. His face -was much wrinkled and his eyes deep set. His hair had evidently been -hastily brushed smooth in front of the temples, but stuck up behind in -quaint little tufts. He entered the room, looking restlessly and -angrily around, as if afraid of everything in that large apartment. -Awkwardly holding up his sword, he addressed Chernyshev and asked in -German where the Emperor was. One could see that he wished to pass -through the rooms as quickly as possible, finish with the bows and -greetings, and sit down to business in front of a map, where he -would feel at home. He nodded hurriedly in reply to Chernyshev, and -smiled ironically on hearing that the sovereign was inspecting the -fortifications that he, Pfuel, had planned in accord with his -theory. He muttered something to himself abruptly and in a bass voice, -as self-assured Germans do--it might have been "stupid fellow"... or -"the whole affair will be ruined," or "something absurd will come of -it."... Prince Andrew did not catch what he said and would have passed -on, but Chernyshev introduced him to Pfuel, remarking that Prince -Andrew was just back from Turkey where the war had terminated so -fortunately. Pfuel barely glanced--not so much at Prince Andrew as -past him--and said, with a laugh: "That must have been a fine tactical -war"; and, laughing contemptuously, went on into the room from which -the sound of voices was heard. - -Pfuel, always inclined to be irritably sarcastic, was particularly -disturbed that day, evidently by the fact that they had dared to -inspect and criticize his camp in his absence. From this short -interview with Pfuel, Prince Andrew, thanks to his Austerlitz -experiences, was able to form a clear conception of the man. Pfuel was -one of those hopelessly and immutably self-confident men, -self-confident to the point of martyrdom as only Germans are, -because only Germans are self-confident on the basis of an abstract -notion--science, that is, the supposed knowledge of absolute truth. -A Frenchman is self-assured because he regards himself personally, -both in mind and body, as irresistibly attractive to men and women. An -Englishman is self-assured, as being a citizen of the best-organized -state in the world, and therefore as an Englishman always knows what -he should do and knows that all he does as an Englishman is -undoubtedly correct. An Italian is self-assured because he is -excitable and easily forgets himself and other people. A Russian is -self-assured just because he knows nothing does not want to know -anything, since he does not believe that anything can be known. The -German's self-assurance is worst of all, stronger and more repulsive -than any other, because he imagines that he knows the truth- -science--which he himself has invented but which is for him the -absolute truth. - -Pfuel was evidently of that sort. He had a science--the theory of -oblique movements deduced by him from the history of Frederick the -Great's wars, and all he came across in the history of more recent -warfare seemed to him absurd and barbarous--monstrous collisions in -which so many blunders were committed by both sides that these wars -could not be called wars, they did not accord with the theory, and -therefore could not serve as material for science. - -In 1806 Pfuel had been one of those responsible, for the plan of -campaign that ended in Jena and Auerstadt, but he did not see the -least proof of the fallibility of his theory in the disasters of -that war. On the contrary, the deviations made from his theory were, -in his opinion, the sole cause of the whole disaster, and with -characteristically gleeful sarcasm he would remark, "There, I said the -whole affair would go to the devil!" Pfuel was one of those -theoreticians who so love their theory that they lose sight of the -theory's object--its practical application. His love of theory made -him hate everything practical, and he would not listen to it. He was -even pleased by failures, for failures resulting from deviations in -practice from the theory only proved to him the accuracy of his -theory. - -He said a few words to Prince Andrew and Chernyshev about the -present war, with the air of a man who knows beforehand that all -will go wrong, and who is not displeased that it should be so. The -unbrushed tufts of hair sticking up behind and the hastily brushed -hair on his temples expressed this most eloquently. - -He passed into the next room, and the deep, querulous sounds of -his voice were at once heard from there. - - - - - -CHAPTER XI - - -Prince Andrew's eyes were still following Pfuel out of the room when -Count Bennigsen entered hurriedly, and nodding to Bolkonski, but not -pausing, went into the study, giving instructions to his adjutant as -he went. The Emperor was following him, and Bennigsen had hastened -on to make some preparations and to be ready to receive the sovereign. -Chernyshev and Prince Andrew went out into the porch, where the -Emperor, who looked fatigued, was dismounting. Marquis Paulucci was -talking to him with particular warmth and the Emperor, with his head -bent to the left, was listening with a dissatisfied air. The Emperor -moved forward evidently wishing to end the conversation, but the -flushed and excited Italian, oblivious of decorum, followed him and -continued to speak. - -"And as for the man who advised forming this camp--the Drissa camp," -said Paulucci, as the Emperor mounted the steps and noticing Prince -Andrew scanned his unfamiliar face, "as to that person, sire..." -continued Paulucci, desperately, apparently unable to restrain -himself, "the man who advised the Drissa camp--I see no alternative -but the lunatic asylum or the gallows!" - -Without heeding the end of the Italian's remarks, and as though -not hearing them, the Emperor, recognizing Bolkonski, addressed him -graciously. - -"I am very glad to see you! Go in there where they are meeting, -and wait for me." - -The Emperor went into the study. He was followed by Prince Peter -Mikhaylovich Volkonski and Baron Stein, and the door closed behind -them. Prince Andrew, taking advantage of the Emperor's permission, -accompanied Paulucci, whom he had known in Turkey, into the drawing -room where the council was assembled. - -Prince Peter Mikhaylovich Volkonski occupied the position, as it -were, of chief of the Emperor's staff. He came out of the study into -the drawing room with some maps which he spread on a table, and put -questions on which he wished to hear the opinion of the gentlemen -present. What had happened was that news (which afterwards proved to -be false) had been received during the night of a movement by the -French to outflank the Drissa camp. - -The first to speak was General Armfeldt who, to meet the -difficulty that presented itself, unexpectedly proposed a perfectly -new position away from the Petersburg and Moscow roads. The reason for -this was inexplicable (unless he wished to show that he, too, could -have an opinion), but he urged that at this point the army should -unite and there await the enemy. It was plain that Armfeldt had -thought out that plan long ago and now expounded it not so much to -answer the questions put--which, in fact, his plan did not answer- -as to avail himself of the opportunity to air it. It was one of the -millions of proposals, one as good as another, that could be made as -long as it was quite unknown what character the war would take. Some -disputed his arguments, others defended them. Young Count Toll -objected to the Swedish general's views more warmly than anyone -else, and in the course of the dispute drew from his side pocket a -well-filled notebook, which he asked permission to read to them. In -these voluminous notes Toll suggested another scheme, totally -different from Armfeldt's or Pfuel's plan of campaign. In answer to -Toll, Paulucci suggested an advance and an attack, which, he urged, -could alone extricate us from the present uncertainty and from the -trap (as he called the Drissa camp) in which we were situated. - -During all these discussions Pfuel and his interpreter, Wolzogen -(his "bridge" in court relations), were silent. Pfuel only snorted -contemptuously and turned away, to show that he would never demean -himself by replying to such nonsense as he was now hearing. So when -Prince Volkonski, who was in the chair, called on him to give his -opinion, he merely said: - -"Why ask me? General Armfeldt has proposed a splendid position -with an exposed rear, or why not this Italian gentleman's attack--very -fine, or a retreat, also good! Why ask me?" said he. "Why, you -yourselves know everything better than I do." - -But when Volkonski said, with a frown, that it was in the -Emperor's name that he asked his opinion, Pfuel rose and, suddenly -growing animated, began to speak: - -"Everything has been spoiled, everything muddled, everybody -thought they knew better than I did, and now you come to me! How -mend matters? There is nothing to mend! The principles laid down by me -must be strictly adhered to," said he, drumming on the table with -his bony fingers. "What is the difficulty? Nonsense, childishness!" - -He went up to the map and speaking rapidly began proving that no -eventuality could alter the efficiency of the Drissa camp, that -everything had been foreseen, and that if the enemy were really -going to outflank it, the enemy would inevitably be destroyed. - -Paulucci, who did not know German, began questioning him in -French. Wolzogen came to the assistance of his chief, who spoke French -badly, and began translating for him, hardly able to keep pace with -Pfuel, who was rapidly demonstrating that not only all that had -happened, but all that could happen, had been foreseen in his -scheme, and that if there were now any difficulties the whole fault -lay in the fact that his plan had not been precisely executed. He kept -laughing sarcastically, he demonstrated, and at last contemptuously -ceased to demonstrate, like a mathematician who ceases to prove in -various ways the accuracy of a problem that has already been proved. -Wolzogen took his place and continued to explain his views in -French, every now and then turning to Pfuel and saying, "Is it not so, -your excellency?" But Pfuel, like a man heated in a fight who - -strikes those on his own side, shouted angrily at his own supporter, -Wolzogen: - -"Well, of course, what more is there to explain?" - -Paulucci and Michaud both attacked Wolzogen simultaneously in -French. Armfeldt addressed Pfuel in German. Toll explained to -Volkonski in Russian. Prince Andrew listened and observed in silence. - -Of all these men Prince Andrew sympathized most with Pfuel, angry, -determined, and absurdly self-confident as he was. Of all those -present, evidently he alone was not seeking anything for himself, -nursed no hatred against anyone, and only desired that the plan, -formed on a theory arrived at by years of toil, should be carried out. -He was ridiculous, and unpleasantly sarcastic, but yet he inspired -involuntary respect by his boundless devotion to an idea. Besides -this, the remarks of all except Pfuel had one common trait that had -not been noticeable at the council of war in 1805: there was now a -panic fear of Napoleon's genius, which, though concealed, was -noticeable in every rejoinder. Everything was assumed to be possible -for Napoleon, they expected him from every side, and invoked his -terrible name to shatter each other's proposals. Pfuel alone seemed to -consider Napoleon a barbarian like everyone else who opposed his -theory. But besides this feeling of respect, Pfuel evoked pity in -Prince Andrew. From the tone in which the courtiers addressed him -and the way Paulucci had allowed himself to speak of him to the -Emperor, but above all from a certain desperation in Pfuel's own -expressions, it was clear that the others knew, and Pfuel himself -felt, that his fall was at hand. And despite his self-confidence and -grumpy German sarcasm he was pitiable, with his hair smoothly -brushed on the temples and sticking up in tufts behind. Though he -concealed the fact under a show of irritation and contempt, he was -evidently in despair that the sole remaining chance of verifying his -theory by a huge experiment and proving its soundness to the whole -world was slipping away from him. - -The discussions continued a long time, and the longer they lasted -the more heated became the disputes, culminating in shouts and -personalities, and the less was it possible to arrive at any general -conclusion from all that had been said. Prince Andrew, listening to -this polyglot talk and to these surmises, plans, refutations, and -shouts, felt nothing but amazement at what they were saying. A thought -that had long since and often occurred to him during his military -activities--the idea that there is not and cannot be any science of -war, and that therefore there can be no such thing as a military -genius--now appeared to him an obvious truth. "What theory and science -is possible about a matter the conditions and circumstances of which -are unknown and cannot be defined, especially when the strength of the -acting forces cannot be ascertained? No one was or is able to -foresee in what condition our or the enemy's armies will be in a day's -time, and no one can gauge the force of this or that detachment. -Sometimes--when there is not a coward at the front to shout, 'We are -cut off!' and start running, but a brave and jolly lad who shouts, -'Hurrah!'--a detachment of five thousand is worth thirty thousand, -as at Schon Grabern, while at times fifty thousand run from eight -thousand, as at Austerlitz. What science can there be in a matter in -which, as in all practical matters, nothing can be defined and -everything depends on innumerable conditions, the significance of -which is determined at a particular moment which arrives no one -knows when? Armfeldt says our army is cut in half, and Paulucci says -we have got the French army between two fires; Michaud says that the -worthlessness of the Drissa camp lies in having the river behind it, -and Pfuel says that is what constitutes its strength; Toll proposes -one plan, Armfeldt another, and they are all good and all bad, and the -advantages of any suggestions can be seen only at the moment of trial. -And why do they all speak of a 'military genius'? Is a man a genius -who can order bread to be brought up at the right time and say who -is to go to the right and who to the left? It is only because military -men are invested with pomp and power and crowds of sychophants flatter -power, attributing to it qualities of genius it does not possess. -The best generals I have known were, on the contrary, stupid or -absent-minded men. Bagration was the best, Napoleon himself admitted -that. And of Bonaparte himself! I remember his limited, self-satisfied -face on the field of Austerlitz. Not only does a good army commander -not need any special qualities, on the contrary he needs the absence -of the highest and best human attributes--love, poetry, tenderness, -and philosophic inquiring doubt. He should be limited, firmly -convinced that what he is doing is very important (otherwise he will -not have sufficient patience), and only then will he be a brave -leader. God forbid that he should be humane, should love, or pity, -or think of what is just and unjust. It is understandable that a -theory of their 'genius' was invented for them long ago because they -have power! The success of a military action depends not on them, -but on the man in the ranks who shouts, 'We are lost!' or who -shouts, 'Hurrah!' And only in the ranks can one serve with assurance -of being useful." - -So thought Prince Andrew as he listened to the talking, and he -roused himself only when Paulucci called him and everyone was leaving. - -At the review next day the Emperor asked Prince Andrew where he -would like to serve, and Prince Andrew lost his standing in court -circles forever by not asking to remain attached to the sovereign's -person, but for permission to serve in the army. - - - - - -CHAPTER XII - - -Before the beginning of the campaign, Rostov had received a letter -from his parents in which they told him briefly of Natasha's illness -and the breaking off of her engagement to Prince Andrew (which they -explained by Natasha's having rejected him) and again asked Nicholas -to retire from the army and return home. On receiving this letter, -Nicholas did not even make any attempt to get leave of absence or to -retire from the army, but wrote to his parents that he was sorry -Natasha was ill and her engagement broken off, and that he would do -all he could to meet their wishes. To Sonya he wrote separately. - -"Adored friend of my soul!" he wrote. "Nothing but honor could -keep me from returning to the country. But now, at the commencement of -the campaign, I should feel dishonored, not only in my comrades' -eyes but in my own, if I preferred my own happiness to my love and -duty to the Fatherland. But this shall be our last separation. Believe -me, directly the war is over, if I am still alive and still loved by -you, I will throw up everything and fly to you, to press you forever -to my ardent breast." - -It was, in fact, only the commencement of the campaign that -prevented Rostov from returning home as he had promised and marrying -Sonya. The autumn in Otradnoe with the hunting, and the winter with -the Christmas holidays and Sonya's love, had opened out to him a vista -of tranquil rural joys and peace such as he had never known before, -and which now allured him. "A splendid wife, children, a good pack -of hounds, a dozen leashes of smart borzois, agriculture, neighbors, -service by election..." thought he. But now the campaign was -beginning, and he had to remain with his regiment. And since it had to -be so, Nicholas Rostov, as was natural to him, felt contented with the -life he led in the regiment and was able to find pleasure in that -life. - -On his return from his furlough Nicholas, having been joyfully -welcomed by his comrades, was sent to obtain remounts and brought back -from the Ukraine excellent horses which pleased him and earned him -commendation from his commanders. During his absence he had been -promoted captain, and when the regiment was put on war footing with an -increase in numbers, he was again allotted his old squadron. - -The campaign began, the regiment was moved into Poland on double -pay, new officers arrived, new men and horses, and above all everybody -was infected with the merrily excited mood that goes with the -commencement of a war, and Rostov, conscious of his advantageous -position in the regiment, devoted himself entirely to the pleasures -and interests of military service, though he knew that sooner or later -he would have to relinquish them. - -The troops retired from Vilna for various complicated reasons of -state, political and strategic. Each step of the retreat was -accompanied by a complicated interplay of interests, arguments, and -passions at headquarters. For the Pavlograd hussars, however, the -whole of this retreat during the finest period of summer and with -sufficient supplies was a very simple and agreeable business. - -It was only at headquarters that there was depression, uneasiness, -and intriguing; in the body of the army they did not ask themselves -where they were going or why. If they regretted having to retreat, -it was only because they had to leave billets they had grown -accustomed to, or some pretty young Polish lady. If the thought that -things looked bad chanced to enter anyone's head, he tried to be as -cheerful as befits a good soldier and not to think of the general -trend of affairs, but only of the task nearest to hand. First they -camped gaily before Vilna, making acquaintance with the Polish -landowners, preparing for reviews and being reviewed by the Emperor -and other high commanders. Then came an order to retreat to Sventsyani -and destroy any provisions they could not carry away with them. -Sventsyani was remembered by the hussars only as the drunken camp, a -name the whole army gave to their encampment there, and because many -complaints were made against the troops, who, taking advantage of -the order to collect provisions, took also horses, carriages, and -carpets from the Polish proprietors. Rostov remembered Sventsyani, -because on the first day of their arrival at that small town he -changed his sergeant major and was unable to manage all the drunken -men of his squadron who, unknown to him, had appropriated five barrels -of old beer. From Sventsyani they retired farther and farther to -Drissa, and thence again beyond Drissa, drawing near to the frontier -of Russia proper. - -On the thirteenth of July the Pavlograds took part in a serious -action for the first time. - -On the twelfth of July, on the eve of that action, there was a heavy -storm of rain and hail. In general, the summer of 1812 was -remarkable for its storms. - -The two Pavlograd squadrons were bivouacking on a field of rye, -which was already in ear but had been completely trodden down by -cattle and horses. The rain was descending in torrents, and Rostov, -with a young officer named Ilyin, his protege, was sitting in a -hastily constructed shelter. An officer of their regiment, with long -mustaches extending onto his cheeks, who after riding to the staff had -been overtaken by the rain, entered Rostov's shelter. - -"I have come from the staff, Count. Have you heard of Raevski's -exploit?" - -And the officer gave them details of the Saltanov battle, which he -had heard at the staff. - -Rostov, smoking his pipe and turning his head about as the water -trickled down his neck, listened inattentively, with an occasional -glance at Ilyin, who was pressing close to him. This officer, a lad of -sixteen who had recently joined the regiment, was now in the same -relation to Nicholas that Nicholas had been to Denisov seven years -before. Ilyin tried to imitate Rostov in everything and adored him -as a girl might have done. - -Zdrzhinski, the officer with the long mustache, spoke -grandiloquently of the Saltanov dam being "a Russian Thermopylae," and -of how a deed worthy of antiquity had been performed by General -Raevski. He recounted how Raevski had led his two sons onto the dam -under terrific fire and had charged with them beside him. Rostov heard -the story and not only said nothing to encourage Zdrzhinski's -enthusiasm but, on the contrary, looked like a man ashamed of what -he was hearing, though with no intention of contradicting it. Since -the campaigns of Austerlitz and of 1807 Rostov knew by experience that -men always lie when describing military exploits, as he himself had -done when recounting them; besides that, he had experience enough to -know that nothing happens in war at all as we can imagine or relate -it. And so he did not like Zdrzhinski's tale, nor did he like -Zdrzhinski himself who, with his mustaches extending over his -cheeks, bent low over the face of his hearer, as was his habit, and -crowded Rostov in the narrow shanty. Rostov looked at him in -silence. "In the first place, there must have been such a confusion -and crowding on the dam that was being attacked that if Raevski did -lead his sons there, it could have had no effect except perhaps on -some dozen men nearest to him," thought he, "the rest could not have -seen how or with whom Raevski came onto the dam. And even those who -did see it would not have been much stimulated by it, for what had -they to do with Raevski's tender paternal feelings when their own -skins were in danger? And besides, the fate of the Fatherland did -not depend on whether they took the Saltanov dam or not, as we are -told was the case at Thermopylae. So why should he have made such a -sacrifice? And why expose his own children in the battle? I would -not have taken my brother Petya there, or even Ilyin, who's a stranger -to me but a nice lad, but would have tried to put them somewhere under -cover," Nicholas continued to think, as he listened to Zdrzhinski. But -he did not express his thoughts, for in such matters, too, he had -gained experience. He knew that this tale redounded to the glory of -our arms and so one had to pretend not to doubt it. And he acted -accordingly. - -"I can't stand this any more," said Ilyin, noticing that Rostov -did not relish Zdrzhinski's conversation. "My stockings and shirt... -and the water is running on my seat! I'll go and look for shelter. The -rain seems less heavy." - -Ilyin went out and Zdrzhinski rode away. - -Five minutes later Ilyin, splashing through the mud, came running -back to the shanty. - -"Hurrah! Rostov, come quick! I've found it! About two hundred -yards away there's a tavern where ours have already gathered. We can -at least get dry there, and Mary Hendrikhovna's there." - -Mary Hendrikhovna was the wife of the regimental doctor, a pretty -young German woman he had married in Poland. The doctor, whether -from lack of means or because he did not like to part from his young -wife in the early days of their marriage, took her about with him -wherever the hussar regiment went and his jealousy had become a -standing joke among the hussar officers. - -Rostov threw his cloak over his shoulders, shouted to Lavrushka to -follow with the things, and--now slipping in the mud, now splashing -right through it--set off with Ilyin in the lessening rain and the -darkness that was occasionally rent by distant lightning. - -"Rostov, where are you?" - -"Here. What lightning!" they called to one another. - - - - - -CHAPTER XIII - - -In the tavern, before which stood the doctor's covered cart, there -were already some five officers. Mary Hendrikhovna, a plump little -blonde German, in a dressing jacket and nightcap, was sitting on a -broad bench in the front corner. Her husband, the doctor, lay asleep -behind her. Rostov and Ilyin, on entering the room, were welcomed with -merry shouts and laughter. - -"Dear me, how jolly we are!" said Rostov laughing. - -"And why do you stand there gaping?" - -"What swells they are! Why, the water streams from them! Don't -make our drawing room so wet." - -"Don't mess Mary Hendrikhovna's dress!" cried other voices. - -Rostov and Ilyin hastened to find a corner where they could change -into dry clothes without offending Mary Hendrikhovna's modesty. They -were going into a tiny recess behind a partition to change, but -found it completely filled by three officers who sat playing cards -by the light of a solitary candle on an empty box, and these -officers would on no account yield their position. Mary Hendrikhovna -obliged them with the loan of a petticoat to be used as a curtain, and -behind that screen Rostov and Ilyin, helped by Lavrushka who had -brought their kits, changed their wet things for dry ones. - -A fire was made up in the dilapidated brick stove. A board was -found, fixed on two saddles and covered with a horsecloth, a small -samovar was produced and a cellaret and half a bottle of rum, and -having asked Mary Hendrikhovna to preside, they all crowded round her. -One offered her a clean handkerchief to wipe her charming hands, -another spread a jacket under her little feet to keep them from the -damp, another hung his coat over the window to keep out the draft, and -yet another waved the flies off her husband's face, lest he should -wake up. - -"Leave him alone," said Mary Hendrikhovna, smiling timidly and -happily. "He is sleeping well as it is, after a sleepless night." - -"Oh, no, Mary Hendrikhovna," replied the officer, "one must look -after the doctor. Perhaps he'll take pity on me someday, when it comes -to cutting off a leg or an arm for me." - -There were only three tumblers, the water was so muddy that one -could not make out whether the tea was strong or weak, and the samovar -held only six tumblers of water, but this made it all the pleasanter -to take turns in order of seniority to receive one's tumbler from Mary -Hendrikhovna's plump little hands with their short and not overclean -nails. All the officers appeared to be, and really were, in love -with her that evening. Even those playing cards behind the partition -soon left their game and came over to the samovar, yielding to the -general mood of courting Mary Hendrikhovna. She, seeing herself -surrounded by such brilliant and polite young men, beamed with -satisfaction, try as she might to hide it, and perturbed as she -evidently was each time her husband moved in his sleep behind her. - -There was only one spoon, sugar was more plentiful than anything -else, but it took too long to dissolve, so it was decided that Mary -Hendrikhovna should stir the sugar for everyone in turn. Rostov -received his tumbler, and adding some rum to it asked Mary -Hendrikhovna to stir it. - -"But you take it without sugar?" she said, smiling all the time, -as if everything she said and everything the others said was very -amusing and had a double meaning. - -"It is not the sugar I want, but only that your little hand should -stir my tea." - -Mary Hendrikhovna assented and began looking for the spoon which -someone meanwhile had pounced on. - -"Use your finger, Mary Hendrikhovna, it will be still nicer," said -Rostov. - -"Too hot!" she replied, blushing with pleasure. - -Ilyin put a few drops of rum into the bucket of water and brought it -to Mary Hendrikhovna, asking her to stir it with her finger. - -"This is my cup," said he. "Only dip your finger in it and I'll -drink it all up." - -When they had emptied the samovar, Rostov took a pack of cards and -proposed that they should play "Kings" with Mary Hendrikhovna. They -drew lots to settle who should make up her set. At Rostov's suggestion -it was agreed that whoever became "King" should have the right to kiss -Mary Hendrikhovna's hand, and that the "Booby" should go to refill and -reheat the samovar for the doctor when the latter awoke. - -"Well, but supposing Mary Hendrikhovna is 'King'?" asked Ilyin. - -"As it is, she is Queen, and her word is law!" - -They had hardly begun to play before the doctor's disheveled head -suddenly appeared from behind Mary Hendrikhovna. He had been awake for -some time, listening to what was being said, and evidently found -nothing entertaining or amusing in what was going on. His face was sad -and depressed. Without greeting the officers, he scratched himself and -asked to be allowed to pass as they were blocking the way. As soon -as he had left the room all the officers burst into loud laughter -and Mary Hendrikhovna blushed till her eyes filled with tears and -thereby became still more attractive to them. Returning from the yard, -the doctor told his wife (who had ceased to smile so happily, and -looked at him in alarm, awaiting her sentence) that the rain had -ceased and they must go to sleep in their covered cart, or -everything in it would be stolen. - -"But I'll send an orderly.... Two of them!" said Rostov. "What an -idea, doctor!" - -"I'll stand guard on it myself!" said Ilyin. - -"No, gentlemen, you have had your sleep, but I have not slept for -two nights," replied the doctor, and he sat down morosely beside his -wife, waiting for the game to end. - -Seeing his gloomy face as he frowned at his wife, the officers -grew still merrier, and some of them could not refrain from -laughter, for which they hurriedly sought plausible pretexts. When -he had gone, taking his wife with him, and had settled down with her -in their covered cart, the officers lay down in the tavern, covering -themselves with their wet cloaks, but they did not sleep for a long -time; now they exchanged remarks, recalling the doctor's uneasiness -and his wife's delight, now they ran out into the porch and reported -what was taking place in the covered trap. Several times Rostov, -covering his head, tried to go to sleep, but some remark would -arouse him and conversation would be resumed, to the accompaniment -of unreasoning, merry, childlike laughter. - - - - - -CHAPTER XIV - - -It was nearly three o'clock but no one was yet asleep, when the -quartermaster appeared with an order to move on to the little town -of Ostrovna. Still laughing and talking, the officers began -hurriedly getting ready and again boiled some muddy water -in the samovar. But Rostov went off to his squadron without waiting -for tea. Day was breaking, the rain had ceased, and the clouds were -dispersing. It felt damp and cold, especially in clothes that were -still moist. As they left the tavern in the twilight of the dawn, -Rostov and Ilyin both glanced under the wet and glistening leather -hood of the doctor's cart, from under the apron of which his feet were -sticking out, and in the middle of which his wife's nightcap was -visible and her sleepy breathing audible. - -"She really is a dear little thing," said Rostov to Ilyin, who was -following him. - -"A charming woman!" said Ilyin, with all the gravity of a boy of -sixteen. - -Half an hour later the squadron was lined up on the road. The -command was heard to "mount" and the soldiers crossed themselves and -mounted. Rostov riding in front gave the order "Forward!" and the -hussars, with clanking sabers and subdued talk, their horses' hoofs -splashing in the mud, defiled in fours and moved along the broad -road planted with birch trees on each side, following the infantry and -a battery that had gone on in front. - -Tattered, blue-purple clouds, reddening in the east, were scudding -before the wind. It was growing lighter and lighter. That curly -grass which always grows by country roadsides became clearly -visible, still wet with the night's rain; the drooping branches of the -birches, also wet, swayed in the wind and flung down bright drops of -water to one side. The soldiers' faces were more and more clearly -visible. Rostov, always closely followed by Ilyin, rode along the side -of the road between two rows of birch trees. - -When campaigning, Rostov allowed himself the indulgence of riding -not a regimental but a Cossack horse. A judge of horses and a -sportsman, he had lately procured himself a large, fine, mettlesome, -Donets horse, dun-colored, with light mane and tail, and when he -rode it no one could outgallop him. To ride this horse was a -pleasure to him, and he thought of the horse, of the morning, of the -doctor's wife, but not once of the impending danger. - -Formerly, when going into action, Rostov had felt afraid; now he had -not the least feeling of fear. He was fearless, not because he had -grown used to being under fire (one cannot grow used to danger), but -because he had learned how to manage his thoughts when in danger. He -had grown accustomed when going into action to think about anything -but what would seem most likely to interest him--the impending danger. -During the first period of his service, hard as he tried and much as -he reproached himself with cowardice, he had not been able to do this, -but with time it had come of itself. Now he rode beside Ilyin under -the birch trees, occasionally plucking leaves from a branch that met -his hand, sometimes touching his horse's side with his foot, or, -without turning round, handing a pipe he had finished to an hussar -riding behind him, with as calm and careless an air as though he -were merely out for a ride. He glanced with pity at the excited face -of Ilyin, who talked much and in great agitation. He knew from -experience the tormenting expectation of terror and death the cornet -was suffering and knew that only time could help him. - -As soon as the sun appeared in a clear strip of sky beneath the -clouds, the wind fell, as if it dared not spoil the beauty of the -summer morning after the storm; drops still continued to fall, but -vertically now, and all was still. The whole sun appeared on the -horizon and disappeared behind a long narrow cloud that hung above it. -A few minutes later it reappeared brighter still from behind the top -of the cloud, tearing its edge. Everything grew bright and -glittered. And with that light, and as if in reply to it, came the -sound of guns ahead of them. - -Before Rostov had had time to consider and determine the distance of -that firing, Count Ostermann-Tolstoy's adjutant came galloping from -Vitebsk with orders to advance at a trot along the road. - -The squadron overtook and passed the infantry and the battery--which -had also quickened their pace--rode down a hill, and passing through -an empty and deserted village again ascended. The horses began to -lather and the men to flush. - -"Halt! Dress your ranks!" the order of the regimental commander -was heard ahead. "Forward by the left. Walk, march!" came the order -from in front. - -And the hussars, passing along the line of troops on the left -flank of our position, halted behind our Uhlans who were in the -front line. To the right stood our infantry in a dense column: they -were the reserve. Higher up the hill, on the very horizon, our guns -were visible through the wonderfully clear air, brightly illuminated -by slanting morning sunbeams. In front, beyond a hollow dale, could be -seen the enemy's columns and guns. Our advanced line, already in -action, could be heard briskly exchanging shots with the enemy in -the dale. - -At these sounds, long unheard, Rostov's spirits rose, as at the -strains of the merriest music. Trap-ta-ta-tap! cracked the shots, -now together, now several quickly one after another. Again all was -silent and then again it sounded as if someone were walking on -detonators and exploding them. - -The hussars remained in the same place for about an hour. A -cannonade began. Count Ostermann with his suite rode up behind the -squadron, halted, spoke to the commander of the regiment, and rode -up the hill to the guns. - -After Ostermann had gone, a command rang out to the Uhlans. - -"Form column! Prepare to charge!" - -The infantry in front of them parted into platoons to allow the -cavalry to pass. The Uhlans started, the streamers on their spears -fluttering, and trotted downhill toward the French cavalry which was -seen below to the left. - -As soon as the Uhlans descended the hill, the hussars were ordered -up the hill to support the battery. As they took the places vacated by -the Uhlans, bullets came from the front, whining and whistling, but -fell spent without taking effect. - -The sounds, which he had not heard for so long, had an even more -pleasurable and exhilarating effect on Rostov than the previous sounds -of firing. Drawing himself up, he viewed the field of battle opening -out before him from the hill, and with his whole soul followed the -movement of the Uhlans. They swooped down close to the French -dragoons, something confused happened there amid the smoke, and five -minutes later our Uhlans were galloping back, not to the place they -had occupied but more to the left, and among the orange-colored Uhlans -on chestnut horses and behind them, in a large group, blue French -dragoons on gray horses could be seen. - - - - - -CHAPTER XV - - -Rostov, with his keen sportsman's eye, was one of the first to catch -sight of these blue French dragoons pursuing our Uhlans. Nearer and -nearer in disorderly crowds came the Uhlans and the French dragoons -pursuing them. He could already see how these men, who looked so small -at the foot of the hill, jostled and overtook one another, waving -their arms and their sabers in the air. - -Rostov gazed at what was happening before him as at a hunt. He -felt instinctively that if the hussars struck at the French dragoons -now, the latter could not withstand them, but if a charge was to be -made it must be done now, at that very moment, or it would be too -late. He looked around. A captain, standing beside him, was gazing -like himself with eyes fixed on the cavalry below them. - -"Andrew Sevastyanych!" said Rostov. "You know, we could crush -them...." - -"A fine thing too!" replied the captain, "and really..." - -Rostov, without waiting to hear him out, touched his horse, galloped -to the front of his squadron, and before he had time to finish -giving the word of command, the whole squadron, sharing his feeling, -was following him. Rostov himself did not know how or why he did it. -He acted as he did when hunting, without reflecting or considering. He -saw the dragoons near and that they were galloping in disorder; he -knew they could not withstand an attack--knew there was only that -moment and that if he let it slip it would not return. The bullets -were whining and whistling so stimulatingly around him and his horse -was so eager to go that he could not restrain himself. He touched -his horse, gave the word of command, and immediately, hearing behind -him the tramp of the horses of his deployed squadron, rode at full -trot downhill toward the dragoons. Hardly had they reached the -bottom of the hill before their pace instinctively changed to a -gallop, which grew faster and faster as they drew nearer to our Uhlans -and the French dragoons who galloped after them. The dragoons were now -close at hand. On seeing the hussars, the foremost began to turn, -while those behind began to halt. With the same feeling with which -he had galloped across the path of a wolf, Rostov gave rein to his -Donets horse and galloped to intersect the path of the dragoons' -disordered lines. One Uhlan stopped, another who was on foot flung -himself to the ground to avoid being knocked over, and a riderless -horse fell in among the hussars. Nearly all the French dragoons were -galloping back. Rostov, picking out one on a gray horse, dashed -after him. On the way he came upon a bush, his gallant horse cleared -it, and almost before he had righted himself in his saddle he saw that -he would immediately overtake the enemy he had selected. That -Frenchman, by his uniform an officer, was going at a gallop, crouching -on his gray horse and urging it on with his saber. In another moment -Rostov's horse dashed its breast against the hindquarters of the -officer's horse, almost knocking it over, and at the same instant -Rostov, without knowing why, raised his saber and struck the Frenchman -with it. - -The instant he had done this, all Rostov's animation vanished. The -officer fell, not so much from the blow--which had but slightly cut -his arm above the elbow--as from the shock to his horse and from -fright. Rostov reined in his horse, and his eyes sought his foe to see -whom he had vanquished. The French dragoon officer was hopping with -one foot on the ground, the other being caught in the stirrup. His -eyes, screwed up with fear as if he every moment expected another -blow, gazed up at Rostov with shrinking terror. His pale and -mud-stained face--fair and young, with a dimple in the chin and -light-blue eyes--was not an enemy's face at all suited to a -battlefield, but a most ordinary, homelike face. Before Rostov had -decided what to do with him, the officer cried, "I surrender!" He -hurriedly but vainly tried to get his foot out of the stirrup and -did not remove his frightened blue eyes from Rostov's face. Some -hussars who galloped up disengaged his foot and helped him into the -saddle. On all sides, the hussars were busy with the dragoons; one was -wounded, but though his face was bleeding, he would not give up his -horse; another was perched up behind an hussar with his arms round -him; a third was being helped by an hussar to mount his horse. In -front, the French infantry were firing as they ran. The hussars -galloped hastily back with their prisoners. Rostov galloped back -with the rest, aware of an unpleasant feeling of depression in his -heart. Something vague and confused, which he could not at all account -for, had come over him with the capture of that officer and the blow -he had dealt him. - -Count Ostermann-Tolstoy met the returning hussars, sent for -Rostov, thanked him, and said he would report his gallant deed to -the Emperor and would recommend him for a St. George's Cross. When -sent for by Count Ostermann, Rostov, remembering that he had charged -without orders, felt sure his commander was sending for him to -punish him for breach of discipline. Ostermann's flattering words -and promise of a reward should therefore have struck him all the -more pleasantly, but he still felt that same vaguely disagreeable -feeling of moral nausea. "But what on earth is worrying me?" he -asked himself as he rode back from the general. "Ilyin? No, he's safe. -Have I disgraced myself in any way? No, that's not it." Something -else, resembling remorse, tormented him. "Yes, oh yes, that French -officer with the dimple. And I remember how my arm paused when I -raised it." - -Rostov saw the prisoners being led away and galloped after them to -have a look at his Frenchman with the dimple on his chin. He was -sitting in his foreign uniform on an hussar packhorse and looked -anxiously about him; The sword cut on his arm could scarcely be called -a wound. He glanced at Rostov with a feigned smile and waved his -hand in greeting. Rostov still had the same indefinite feeling, as -of shame. - -All that day and the next his friends and comrades noticed that -Rostov, without being dull or angry, was silent, thoughtful, and -preoccupied. He drank reluctantly, tried to remain alone, and kept -turning something over in his mind. - -Rostov was always thinking about that brilliant exploit of his, -which to his amazement had gained him the St. George's Cross and -even given him a reputation for bravery, and there was something he -could not at all understand. "So others are even more afraid than I -am!" he thought. "So that's all there is in what is called heroism! -And heroism! And did I do it for my country's sake? And how was he -to blame, with his dimple and blue eyes? And how frightened he was! He -thought that I should kill him. Why should I kill him? My hand -trembled. And they have given me a St. George's Cross.... I can't make -it out at all." - -But while Nicholas was considering these questions and still could -reach no clear solution of what puzzled him so, the wheel of fortune -in the service, as often happens, turned in his favor. After the -affair at Ostrovna he was brought into notice, received command of -an hussar battalion, and when a brave officer was needed he was -chosen. - - - - - -CHAPTER XVI - - -On receiving news of Natasha's illness, the countess, though not -quite well yet and still weak, went to Moscow with Petya and the -rest of the household, and the whole family moved from Marya -Dmitrievna's house to their own and settled down in town. - -Natasha's illness was so serious that, fortunately for her and for -her parents, the consideration of all that had caused the illness, her -conduct and the breaking off of her engagement, receded into the -background. She was so ill that it was impossible for them to consider -in how far she was to blame for what had happened. She could not eat -or sleep, grew visibly thinner, coughed, and, as the doctors made them -feel, was in danger. They could not think of anything but how to -help her. Doctors came to see her singly and in consultation, talked -much in French, German, and Latin, blamed one another, and -prescribed a great variety of medicines for all the diseases known -to them, but the simple idea never occurred to any of them that they -could not know the disease Natasha was suffering from, as no disease -suffered by a live man can be known, for every living person has his -own peculiarities and always has his own peculiar, personal, novel, -complicated disease, unknown to medicine--not a disease of the -lungs, liver, skin, heart, nerves, and so on mentioned in medical -books, but a disease consisting of one of the innumerable combinations -of the maladies of those organs. This simple thought could not occur -to the doctors (as it cannot occur to a wizard that he is unable to -work his charms) because the business of their lives was to cure, -and they received money for it and had spent the best years of their -lives on that business. But, above all, that thought was kept out of -their minds by the fact that they saw they were really useful, as in -fact they were to the whole Rostov family. Their usefulness did not -depend on making the patient swallow substances for the most part -harmful (the harm was scarcely perceptible, as they were given in -small doses), but they were useful, necessary, and indispensable -because they satisfied a mental need of the invalid and of those who -loved her--and that is why there are, and always will be, -pseudo-healers, wise women, homeopaths, and allopaths. They -satisfied that eternal human need for hope of relief, for sympathy, -and that something should be done, which is felt by those who are -suffering. They satisfied the need seen in its most elementary form in -a child, when it wants to have a place rubbed that has been hurt. A -child knocks itself and runs at once to the arms of its mother or -nurse to have the aching spot rubbed or kissed, and it feels better -when this is done. The child cannot believe that the strongest and -wisest of its people have no remedy for its pain, and the hope of -relief and the expression of its mother's sympathy while she rubs -the bump comforts it. The doctors were of use to Natasha because -they kissed and rubbed her bump, assuring her that it would soon -pass if only the coachman went to the chemist's in the Arbat and got a -powder and some pills in a pretty box of a ruble and seventy kopeks, -and if she took those powders in boiled water at intervals of -precisely two hours, neither more nor less. - -What would Sonya and the count and countess have done, how would -they have looked, if nothing had been done, if there had not been -those pills to give by the clock, the warm drinks, the chicken -cutlets, and all the other details of life ordered by the doctors, the -carrying out of which supplied an occupation and consolation to the -family circle? How would the count have borne his dearly loved -daughter's illness had he not known that it was costing him a thousand -rubles, and that he would not grudge thousands more to benefit her, or -had he not known that if her illness continued he would not grudge yet -other thousands and would take her abroad for consultations there, and -had he not been able to explain the details of how Metivier and Feller -had not understood the symptoms, but Frise had, and Mudrov had -diagnosed them even better? What would the countess have done had -she not been able sometimes to scold the invalid for not strictly -obeying the doctor's orders? - -"You'll never get well like that," she would say, forgetting her -grief in her vexation, "if you won't obey the doctor and take your -medicine at the right time! You mustn't trifle with it, you know, or -it may turn to pneumonia," she would go on, deriving much comfort from -the utterance of that foreign word, incomprehensible to others as well -as to herself. - -What would Sonya have done without the glad consciousness that she -had not undressed during the first three nights, in order to be -ready to carry out all the doctor's injunctions with precision, and -that she still kept awake at night so as not to miss the proper time -when the slightly harmful pills in the little gilt box had to be -administered? Even to Natasha herself it was pleasant to see that so -many sacrifices were being made for her sake, and to know that she had -to take medicine at certain hours, though she declared that no -medicine would cure her and that it was all nonsense. And it was -even pleasant to be able to show, by disregarding the orders, that she -did not believe in medical treatment and did not value her life. - -The doctor came every day, felt her pulse, looked at her tongue, and -regardless of her grief-stricken face joked with her. But when he -had gone into another room, to which the countess hurriedly followed -him, he assumed a grave air and thoughtfully shaking his head said -that though there was danger, he had hopes of the effect of this -last medicine and one must wait and see, that the malady was chiefly -mental, but... And the countess, trying to conceal the action from -herself and from him, slipped a gold coin into his hand and always -returned to the patient with a more tranquil mind. - -The symptoms of Natasha's illness were that she ate little, slept -little, coughed, and was always low-spirited. The doctors said that -she could not get on without medical treatment, so they kept her in -the stifling atmosphere of the town, and the Rostovs did not move to -the country that summer of 1812. - -In spite of the many pills she swallowed and the drops and powders -out of the little bottles and boxes of which Madame Schoss who was -fond of such things made a large collection, and in spite of being -deprived of the country life to which she was accustomed, youth -prevailed. Natasha's grief began to be overlaid by the impressions -of daily life, it ceased to press so painfully on her heart, it -gradually faded into the past, and she began to recover physically. - - - - - -CHAPTER XVII - - -Natasha was calmer but no happier. She not merely avoided all -external forms of pleasure--balls, promenades, concerts, and theaters- -but she never laughed without a sound of tears in her laughter. She -could not sing. As soon as she began to laugh, or tried to sing by -herself, tears choked her: tears of remorse, tears at the recollection -of those pure times which could never return, tears of vexation that -she should so uselessly have ruined her young life which might have -been so happy. Laughter and singing in particular seemed to her like a -blasphemy, in face of her sorrow. Without any need of -self-restraint, no wish to coquet ever entered her head. She said -and felt at that time that no man was more to her than Nastasya -Ivanovna, the buffoon. Something stood sentinel within her and forbade -her every joy. Besides, she had lost all the old interests of her -carefree girlish life that had been so full of hope. The previous -autumn, the hunting, "Uncle," and the Christmas holidays spent with -Nicholas at Otradnoe were what she recalled oftenest and most -painfully. What would she not have given to bring back even a single -day of that time! But it was gone forever. Her presentiment at the -time had not deceived her--that that state of freedom and readiness -for any enjoyment would not return again. Yet it was necessary to live -on. - -It comforted her to reflect that she was not better as she had -formerly imagined, but worse, much worse, than anybody else in the -world. But this was not enough. She knew that, and asked herself, -"What next?" But there was nothing to come. There was no joy in -life, yet life was passing. Natasha apparently tried not to be a -burden or a hindrance to anyone, but wanted nothing for herself. She -kept away from everyone in the house and felt at ease only with her -brother Petya. She liked to be with him better than with the others, -and when alone with him she sometimes laughed. She hardly ever left -the house and of those who came to see them was glad to see only one -person, Pierre. It would have been impossible to treat her with more -delicacy, greater care, and at the same time more seriously than did -Count Bezukhov. Natasha unconsciously felt this delicacy and so -found great pleasure in his society. But she was not even grateful -to him for it; nothing good on Pierre's part seemed to her to be an -effort, it seemed so natural for him to be kind to everyone that there -was no merit in his kindness. Sometimes Natasha noticed -embarrassment and awkwardness on his part in her presence, -especially when he wanted to do something to please her, or feared -that something they spoke of would awaken memories distressing to her. -She noticed this and attributed it to his general kindness and -shyness, which she imagined must be the same toward everyone as it was -to her. After those involuntary words--that if he were free he would -have asked on his knees for her hand and her love--uttered at a moment -when she was so strongly agitated, Pierre never spoke to Natasha of -his feelings; and it seemed plain to her that those words, which had -then so comforted her, were spoken as all sorts of meaningless words -are spoken to comfort a crying child. It was not because Pierre was -a married man, but because Natasha felt very strongly with him that -moral barrier the absence of which she had experienced with Kuragin -that it never entered her head that the relations between him and -herself could lead to love on her part, still less on his, or even -to the kind of tender, self-conscious, romantic friendship between a -man and a woman of which she had known several instances. - -Before the end of the fast of St. Peter, Agrafena Ivanovna Belova, a -country neighbor of the Rostovs, came to Moscow to pay her devotions -at the shrines of the Moscow saints. She suggested that Natasha should -fast and prepare for Holy Communion, and Natasha gladly welcomed the -idea. Despite the doctor's orders that she should not go out early -in the morning, Natasha insisted on fasting and preparing for the -sacrament, not as they generally prepared for it in the Rostov -family by attending three services in their own house, but as Agrafena -Ivanovna did, by going to church every day for a week and not once -missing Vespers, Matins, or Mass. - -The countess was pleased with Natasha's zeal; after the poor results -of the medical treatment, in the depths of her heart she hoped that -prayer might help her daughter more than medicines and, though not -without fear and concealing it from the doctor, she agreed to -Natasha's wish and entrusted her to Belova. Agrafena Ivanovna used -to come to wake Natasha at three in the morning, but generally found -her already awake. She was afraid of being late for Matins. Hastily -washing, and meekly putting on her shabbiest dress and an old -mantilla, Natasha, shivering in the fresh air, went out into the -deserted streets lit by the clear light of dawn. By Agrafena -Ivanovna's advice Natasha prepared herself not in their own parish, -but at a church where, according to the devout Agrafena Ivanovna, -the priest was a man of very severe and lofty life. There were never -many people in the church; Natasha always stood beside Belova in the -customary place before an icon of the Blessed Virgin, let into the -screen before the choir on the left side, and a feeling, new to her, -of humility before something great and incomprehensible, seized her -when at that unusual morning hour, gazing at the dark face of the -Virgin illuminated by the candles burning before it and by the morning -light falling from the window, she listened to the words of the -service which she tried to follow with understanding. When she -understood them her personal feeling became interwoven in the -prayers with shades of its own. When she did not understand, it was -sweeter still to think that the wish to understand everything is -pride, that it is impossible to understand all, that it is only -necessary to believe and to commit oneself to God, whom she felt -guiding her soul at those moments. She crossed herself, bowed low, and -when she did not understand, in horror at her own vileness, simply -asked God to forgive her everything, everything, to have mercy upon -her. The prayers to which she surrendered herself most of all were -those of repentance. On her way home at an early hour when she met -no one but bricklayers going to work or men sweeping the street, and -everybody within the houses was still asleep, Natasha experienced a -feeling new to her, a sense of the possibility of correcting her -faults, the possibility of a new, clean life, and of happiness. - -During the whole week she spent in this way, that feeling grew every -day. And the happiness of taking communion, or "communing" as Agrafena -Ivanovna, joyously playing with the word, called it, seemed to Natasha -so great that she felt she should never live till that blessed Sunday. - -But the happy day came, and on that memorable Sunday, when, -dressed in white muslin, she returned home after communion, for the -first time for many months she felt calm and not oppressed by the -thought of the life that lay before her. - -The doctor who came to see her that day ordered her to continue -the powders he had prescribed a fortnight previously. - -"She must certainly go on taking them morning and evening," said he, -evidently sincerely satisfied with his success. "Only, please be -particular about it. - -"Be quite easy," he continued playfully, as he adroitly took the -gold coin in his palm. "She will soon be singing and frolicking about. -The last medicine has done her a very great deal of good. She has -freshened up very much." - -The countess, with a cheerful expression on her face, looked down at -her nails and spat a little for luck as she returned to the drawing -room. - - - - - -CHAPTER XVIII - - -At the beginning of July more and more disquieting reports about the -war began to spread in Moscow; people spoke of an appeal by the -Emperor to the people, and of his coming himself from the army to -Moscow. And as up to the eleventh of July no manifesto or appeal had -been received, exaggerated reports became current about them and about -the position of Russia. It was said that the Emperor was leaving the -army because it was in danger, it was said that Smolensk had -surrendered, that Napoleon had an army of a million and only a miracle -could save Russia. - -On the eleventh of July, which was Saturday, the manifesto was -received but was not yet in print, and Pierre, who was at the -Rostovs', promised to come to dinner next day, Sunday, and bring a -copy of the manifesto and appeal, which he would obtain from Count -Rostopchin. - -That Sunday, the Rostovs went to Mass at the Razumovskis' private -chapel as usual. It was a hot July day. Even at ten o'clock, when -the Rostovs got out of their carriage at the chapel, the sultry air, -the shouts of hawkers, the light and gay summer clothes of the -crowd, the dusty leaves of the trees on the boulevard, the sounds of -the band and the white trousers of a battalion marching to parade, the -rattling of wheels on the cobblestones, and the brilliant, hot -sunshine were all full of that summer languor, that content and -discontent with the present, which is most strongly felt on a -bright, hot day in town. All the Moscow notabilities, all the Rostovs' -acquaintances, were at the Razumovskis' chapel, for, as if expecting -something to happen, many wealthy families who usually left town for -their country estates had not gone away that summer. As Natasha, at -her mother's side, passed through the crowd behind a liveried -footman who cleared the way for them, she heard a young man speaking -about her in too loud a whisper. - -"That's Rostova, the one who..." - -"She's much thinner, but all the same she's pretty!" - -She heard, or thought she heard, the names of Kuragin and Bolkonski. -But she was always imagining that. It always seemed to her that -everyone who looked at her was thinking only of what had happened to -her. With a sinking heart, wretched as she always was now when she -found herself in a crowd, Natasha in her lilac silk dress trimmed with -black lace walked--as women can walk--with the more repose and -stateliness the greater the pain and shame in her soul. She knew for -certain that she was pretty, but this no longer gave her -satisfaction as it used to. On the contrary it tormented her more than -anything else of late, and particularly so on this bright, hot -summer day in town. "It's Sunday again--another week past," she -thought, recalling that she had been here the Sunday before, "and -always the same life that is no life, and the same surroundings in -which it used to be so easy to live. I'm pretty, I'm young, and I know -that now I am good. I used to be bad, but now I know I am good," she -thought, "but yet my best years are slipping by and are no good to -anyone." She stood by her mother's side and exchanged nods with -acquaintances near her. From habit she scrutinized the ladies' -dresses, condemned the bearing of a lady standing close by who was not -crossing herself properly but in a cramped manner, and again she -thought with vexation that she was herself being judged and was -judging others, and suddenly, at the sound of the service, she felt -horrified at her own vileness, horrified that the former purity of her -soul was again lost to her. - -A comely, fresh-looking old man was conducting the service with that -mild solemnity which has so elevating and soothing an effect on the -souls of the worshipers. The gates of the sanctuary screen were -closed, the curtain was slowly drawn, and from behind it a soft -mysterious voice pronounced some words. Tears, the cause of which -she herself did not understand, made Natasha's breast heave, and a -joyous but oppressive feeling agitated her. - -"Teach me what I should do, how to live my life, how I may grow good -forever, forever!" she pleaded. - -The deacon came out onto the raised space before the altar screen -and, holding his thumb extended, drew his long hair from under his -dalmatic and, making the sign of the cross on his breast, began in a -loud and solemn voice to recite the words of the prayer... - -"In peace let us pray unto the Lord." - -"As one community, without distinction of class, without enmity, -united by brotherly love--let us pray!" thought Natasha. - -"For the peace that is from above, and for the salvation of our -souls." - -"For the world of angels and all the spirits who dwell above us," -prayed Natasha. - -When they prayed for the warriors, she thought of her brother and -Denisov. When they prayed for all traveling by land and sea, she -remembered Prince Andrew, prayed for him, and asked God to forgive her -all the wrongs she had done him. When they prayed for those who love -us, she prayed for the members of her own family, her father and -mother and Sonya, realizing for the first time how wrongly she had -acted toward them, and feeling all the strength of her love for -them. When they prayed for those who hate us, she tried to think of -her enemies and people who hated her, in order to pray for them. She -included among her enemies the creditors and all who had business -dealings with her father, and always at the thought of enemies and -those who hated her she remembered Anatole who had done her so much -harm--and though he did not hate her she gladly prayed for him as -for an enemy. Only at prayer did she feel able to think clearly and -calmly of Prince Andrew and Anatole, as men for whom her feelings were -as nothing compared with her awe and devotion to God. When they prayed -for the Imperial family and the Synod, she bowed very low and made the -sign of the cross, saying to herself that even if she did not -understand, still she could not doubt, and at any rate loved the -governing Synod and prayed for it. - -When he had finished the Litany the deacon crossed the stole over -his breast and said, "Let us commit ourselves and our whole lives to -Christ the Lord!" - -"Commit ourselves to God," Natasha inwardly repeated. "Lord God, I -submit myself to Thy will!" she thought. "I want nothing, wish for -nothing; teach me what to do and how to use my will! Take me, take -me!" prayed Natasha, with impatient emotion in her heart, not crossing -herself but letting her slender arms hang down as if expecting some -invisible power at any moment to take her and deliver her from -herself, from her regrets, desires, remorse, hopes, and sins. - -The countess looked round several times at her daughter's softened -face and shining eyes and prayed God to help her. - -Unexpectedly, in the middle of the service, and not in the usual -order Natasha knew so well, the deacon brought out a small stool, -the one he knelt on when praying on Trinity Sunday, and placed it -before the doors of the sanctuary screen. The priest came out with his -purple velvet biretta on his head, adjusted his hair, and knelt down -with an effort. Everybody followed his example and they looked at -one another in surprise. Then came the prayer just received from the -Synod--a prayer for the deliverance of Russia from hostile invasion. - -"Lord God of might, God of our salvation!" began the priest in -that voice, clear, not grandiloquent but mild, in which only the -Slav clergy read and which acts so irresistibly on a Russian heart. - -"Lord God of might, God of our salvation! Look this day in mercy and -blessing on Thy humble people, and graciously hear us, spare us, and -have mercy upon us! This foe confounding Thy land, desiring to lay -waste the whole world, rises against us; these lawless men are -gathered together to overthrow Thy kingdom, to destroy Thy dear -Jerusalem, Thy beloved Russia; to defile Thy temples, to overthrow -Thine altars, and to desecrate our holy shrines. How long, O Lord, how -long shall the wicked triumph? How long shall they wield unlawful -power? - -"Lord God! Hear us when we pray to Thee; strengthen with Thy might -our most gracious sovereign lord, the Emperor Alexander Pavlovich; -be mindful of his uprightness and meekness, reward him according to -his righteousness, and let it preserve us, Thy chosen Israel! Bless -his counsels, his undertakings, and his work; strengthen his kingdom -by Thine almighty hand, and give him victory over his enemy, even as -Thou gavest Moses the victory over Amalek, Gideon over Midian, and -David over Goliath. Preserve his army, put a bow of brass in the hands -of those who have armed themselves in Thy Name, and gird their loins -with strength for the fight. Take up the spear and shield and arise to -help us; confound and put to shame those who have devised evil against -us, may they be before the faces of Thy faithful warriors as dust -before the wind, and may Thy mighty Angel confound them and put them -to flight; may they be ensnared when they know it not, and may the -plots they have laid in secret be turned against them; let them fall -before Thy servants' feet and be laid low by our hosts! Lord, Thou art -able to save both great and small; Thou art God, and man cannot -prevail against Thee! - -"God of our fathers! Remember Thy bounteous mercy and -loving-kindness which are from of old; turn not Thy face from us, -but be gracious to our unworthiness, and in Thy great goodness and Thy -many mercies regard not our transgressions and iniquities! Create in -us a clean heart and renew a right spirit within us, strengthen us all -in Thy faith, fortify our hope, inspire us with true love one for -another, arm us with unity of spirit in the righteous defense of the -heritage Thou gavest to us and to our fathers, and let not the scepter -of the wicked be exalted against the destiny of those Thou hast -sanctified. - -"O Lord our God, in whom we believe and in whom we put our trust, -let us not be confounded in our hope of Thy mercy, and give us a token -of Thy blessing, that those who hate us and our Orthodox faith may see -it and be put to shame and perish, and may all the nations know that -Thou art the Lord and we are Thy people. Show Thy mercy upon us this -day, O Lord, and grant us Thy salvation; make the hearts of Thy -servants to rejoice in Thy mercy; smite down our enemies and destroy -them swiftly beneath the feet of Thy faithful servants! For Thou art -the defense, the succor, and the victory of them that put their -trust in Thee, and to Thee be all glory, to Father, Son, and Holy -Ghost, now and forever, world without end. Amen." - -In Natasha's receptive condition of soul this prayer affected her -strongly. She listened to every word about the victory of Moses over -Amalek, of Gideon over Midian, and of David over Goliath, and about -the destruction of "Thy Jerusalem," and she prayed to God with the -tenderness and emotion with which her heart was overflowing, but -without fully understanding what she was asking of God in that prayer. -She shared with all her heart in the prayer for the spirit of -righteousness, for the strengthening of the heart by faith and hope, -and its animation by love. But she could not pray that her enemies -might be trampled under foot when but a few minutes before she had -been wishing she had more of them that she might pray for them. But -neither could she doubt the righteousness of the prayer that was being -read on bended knees. She felt in her heart a devout and tremulous awe -at the thought of the punishment that overtakes men for their sins, -and especially of her own sins, and she prayed to God to forgive -them all, and her too, and to give them all, and her too, peace and -happiness. And it seemed to her that God heard her prayer. - - - - - -CHAPTER XIX - - -From the day when Pierre, after leaving the Rostovs' with -Natasha's grateful look fresh in his mind, had gazed at the comet that -seemed to be fixed in the sky and felt that something new was -appearing on his own horizon--from that day the problem of the -vanity and uselessness of all earthly things, that had incessantly -tormented him, no longer presented itself. That terrible question -"Why?" "Wherefore?" which had come to him amid every occupation, was -now replaced, not by another question or by a reply to the former -question, but by her image. When he listened to, or himself took -part in, trivial conversations, when he read or heard of human -baseness or folly, he was not horrified as formerly, and did not ask -himself why men struggled so about these things when all is so -transient and incomprehensible--but he remembered her as he had last -seen her, and all his doubts vanished--not because she had answered -the questions that had haunted him, but because his conception of -her transferred him instantly to another, a brighter, realm of -spiritual activity in which no one could be justified or guilty--a -realm of beauty and love which it was worth living for. Whatever -worldly baseness presented itself to him, he said to himself: - -"Well, supposing N. N. swindled the country and the Tsar, and the -country and the Tsar confer honors upon him, what does that matter? -She smiled at me yesterday and asked me to come again, and I love her, -and no one will ever know it." And his soul felt calm and peaceful. - -Pierre still went into society, drank as much and led the same -idle and dissipated life, because besides the hours he spent at the -Rostovs' there were other hours he had to spend somehow, and the -habits and acquaintances he had made in Moscow formed a current that -bore him along irresistibly. But latterly, when more and more -disquieting reports came from the seat of war and Natasha's health -began to improve and she no longer aroused in him the former feeling -of careful pity, an ever-increasing restlessness, which he could not -explain, took possession of him. He felt that the condition he was -in could not continue long, that a catastrophe was coming which -would change his whole life, and he impatiently sought everywhere -for signs of that approaching catastrophe. One of his brother Masons -had revealed to Pierre the following prophecy concerning Napoleon, -drawn from the Revelation of St. John. - -In chapter 13, verse 18, of the Apocalypse, it is said: - - -Here is wisdom. Let him that hath understanding count the number -of the beast: for it is the number of a man; and his number is Six -hundred threescore and six. - -And in the fifth verse of the same chapter: - - -And there was given unto him a mouth speaking great things and -blasphemies; and power was given unto him to continue forty and two -months. - - -The French alphabet, written out with the same numerical values as -the Hebrew, in which the first nine letters denote units and the -others tens, will have the following significance: - - a b c d e f g h i k - 1 2 3 4 5 6 7 8 9 10 - l m n o p q r s - 20 30 40 50 60 70 80 90 - t u v w x y - 100 110 120 130 140 150 - z - 160 - - -Writing the words L'Empereur Napoleon in numbers, it appears that -the sum of them is 666, and that Napoleon therefore the beast foretold -in the Apocalypse. Moreover, by applying the same system to the -words quarante-deux,* which was the term allowed to the beast that -"spoke great things and blasphemies," the same number 666 was -obtained; from which it followed that the limit fixed for Napoleon's -power had come in the year 1812 when the French emperor was forty-two. -This prophecy pleased Pierre very much and he often asked himself what -would put an end to the power of the beast, that is, of Napoleon, -and tried by the same system of using letters as numbers and adding -them up, to find an answer to the question that engrossed him. He -wrote the words L'Empereur Alexandre, La nation russe and added up -their numbers, but the sums were either more or less than 666. Once -when making such calculations he wrote down his own name in French, -Comte Pierre Besouhoff, but the sum of the numbers did not come right. -Then he changed the spelling, substituting a z for the s and adding de -and the article le, still without obtaining the desired result. Then -it occurred to him: if the answer to the question were contained in -his name, his nationality would also be given in the answer. So he -wrote Le russe Besuhof and adding up the numbers got 671. This was -only five too much, and five was represented by e, the very letter -elided from the article le before the word Empereur. By omitting the -e, though incorrectly, Pierre got the answer he sought. L'russe -Besuhof made 666. This discovery excited him. How, or by what means, -he was connected with the great event foretold in the Apocalypse he -did not know, but he did not doubt that connection for a moment. His -love for Natasha, Antichrist, Napoleon, the invasion, the comet, -666, L'Empereur Napoleon, and L'russe Besuhof--all this had to -mature and culminate, to lift him out of that spellbound, petty sphere -of Moscow habits in which he felt himself held captive and lead him to -a great achievement and great happiness. - - -*Forty-two. - - - -On the eve of the Sunday when the special prayer was read, Pierre -had promised the Rostovs to bring them, from Count Rostopchin whom -he knew well, both the appeal to the people and the news from the -army. In the morning, when he went to call at Rostopchin's he met -there a courier fresh from the army, an acquaintance of his own, who -often danced at Moscow balls. - -"Do, please, for heaven's sake, relieve me of something!" said the -courier. "I have a sackful of letters to parents." - -Among these letters was one from Nicholas Rostov to his father. -Pierre took that letter, and Rostopchin also gave him the Emperor's -appeal to Moscow, which had just been printed, the last army orders, -and his own most recent bulletin. Glancing through the army orders, -Pierre found in one of them, in the lists of killed, wounded, and -rewarded, the name of Nicholas Rostov, awarded a St. George's Cross of -the Fourth Class for courage shown in the Ostrovna affair, and in -the same order the name of Prince Andrew Bolkonski, appointed to the -command of a regiment of Chasseurs. Though he did not want to remind -the Rostovs of Bolkonski, Pierre could not refrain from making them -happy by the news of their son's having received a decoration, so he -sent that printed army order and Nicholas' letter to the Rostovs, -keeping the appeal, the bulletin, and the other orders to take with -him when he went to dinner. - -His conversation with Count Rostopchin and the latter's tone of -anxious hurry, the meeting with the courier who talked casually of how -badly things were going in the army, the rumors of the discovery of -spies in Moscow and of a leaflet in circulation stating that -Napoleon promised to be in both the Russian capitals by the autumn, -and the talk of the Emperor's being expected to arrive next day--all -aroused with fresh force that feeling of agitation and expectation -in Pierre which he had been conscious of ever since the appearance -of the comet, and especially since the beginning of the war. - -He had long been thinking of entering the army and would have done -so had he not been hindered, first, by his membership of the Society -of Freemasons to which he was bound by oath and which preached -perpetual peace and the abolition of war, and secondly, by the fact -that when he saw the great mass of Muscovites who had donned uniform -and were talking patriotism, he somehow felt ashamed to take the step. -But the chief reason for not carrying out his intention to enter the -army lay in the vague idea that he was L'russe Besuhof who had the -number of the beast, 666; that his part in the great affair of setting -a limit to the power of the beast that spoke great and blasphemous -things had been predestined from eternity, and that therefore he ought -not to undertake anything, but wait for what was bound to come to -pass. - - - - - -CHAPTER XX - - -A few intimate friends were dining with the Rostovs that day, as -usual on Sundays. - -Pierre came early so as to find them alone. - -He had grown so stout this year that he would have been abnormal had -he not been so tall, so broad of limb, and so strong that he carried -his bulk with evident ease. - -He went up the stairs, puffing and muttering something. His coachman -did not even ask whether he was to wait. He knew that when his -master was at the Rostovs' he stayed till midnight. The Rostovs' -footman rushed eagerly forward to help him off with his cloak and take -his hat and stick. Pierre, from club habit, always left both hat and -stick in the anteroom. - -The first person he saw in the house was Natasha. Even before he saw -her, while taking off his cloak, he heard her. She was practicing -solfa exercises in the music room. He knew that she had not sung since -her illness, and so the sound of her voice surprised and delighted -him. He opened the door softly and saw her, in the lilac dress she had -worn at church, walking about the room singing. She had her back to -him when he opened the door, but when, turning quickly, she saw his -broad, surprised face, she blushed and came rapidly up to him. - -"I want to try to sing again," she said, adding as if by way of -excuse, "it is, at least, something to do." - -"That's capital!" - -"How glad I am you've come! I am so happy today," she said, with the -old animation Pierre had not seen in her for along time. "You know -Nicholas has received a St. George's Cross? I am so proud of him." - -"Oh yes, I sent that announcement. But I don't want to interrupt -you," he added, and was about to go to the drawing room. - -Natasha stopped him. - -"Count, is it wrong of me to sing?" she said blushing, and fixing -her eyes inquiringly on him. - -"No... Why should it be? On the contrary... But why do you ask me?" - -"I don't know myself," Natasha answered quickly, "but I should not -like to do anything you disapproved of. I believe in you completely. -You don't know how important you are to me, how much you've done for -me...." She spoke rapidly and did not notice how Pierre flushed at her -words. "I saw in that same army order that he, Bolkonski" (she -whispered the name hastily), "is in Russia, and in the army again. -What do you think?"--she was speaking hurriedly, evidently afraid -her strength might fail her--"Will he ever forgive me? Will he not -always have a bitter feeling toward me? What do you think? What do you -think?" - -"I think..." Pierre replied, "that he has nothing to forgive.... -If I were in his place..." - -By association of ideas, Pierre was at once carried back to the -day when, trying to comfort her, he had said that if he were not -himself but the best man in the world and free, he would ask on his -knees for her hand; and the same feeling of pity, tenderness, and love -took possession of him and the same words rose to his lips. But she -did not give him time to say them. - -"Yes, you... you..." she said, uttering the word you rapturously- -"that's a different thing. I know no one kinder, more generous, or -better than you; nobody could be! Had you not been there then, and now -too, I don't know what would have become of me, because..." - -Tears suddenly rose in her eyes, she turned away, lifted her music -before her eyes, began singing again, and again began walking up and -down the room. - -Just then Petya came running in from the drawing room. - -Petya was now a handsome rosy lad of fifteen with full red lips -and resembled Natasha. He was preparing to enter the university, but -he and his friend Obolenski had lately, in secret, agreed to join -the hussars. - -Petya had come rushing out to talk to his namesake about this -affair. He had asked Pierre to find out whether he would be accepted -in the hussars. - -Pierre walked up and down the drawing room, not listening to what -Petya was saying. - -Petya pulled him by the arm to attract his attention. - -"Well, what about my plan? Peter Kirilych, for heaven's sake! You -are my only hope," said Petya. - -"Oh yes, your plan. To join the hussars? I'll mention it, I'll bring -it all up today." - -"Well, mon cher, have you got the manifesto?" asked the old count. -"The countess has been to Mass at the Razumovskis' and heard the new -prayer. She says it's very fine." - -"Yes, I've got it," said Pierre. "The Emperor is to be here -tomorrow... there's to be an Extraordinary Meeting of the nobility, -and they are talking of a levy of ten men per thousand. Oh yes, let me -congratulate you!" - -"Yes, yes, thank God! Well, and what news from the army?" - -"We are again retreating. They say we're already near Smolensk," -replied Pierre. - -"O Lord, O Lord!" exclaimed the count. "Where is the manifesto?" - -"The Emperor's appeal? Oh yes!" - -Pierre began feeling in his pockets for the papers, but could not -find them. Still slapping his pockets, he kissed the hand of the -countess who entered the room and glanced uneasily around, evidently -expecting Natasha, who had left off singing but had not yet come -into the drawing room. - -"On my word, I don't know what I've done with it," he said. - -"There he is, always losing everything!" remarked the countess. - -Natasha entered with a softened and agitated expression of face -and sat down looking silently at Pierre. As soon as she entered, -Pierre's features, which had been gloomy, suddenly lighted up, and -while still searching for the papers he glanced at her several times. - -"No, really! I'll drive home, I must have left them there. I'll -certainly..." - -"But you'll be late for dinner." - -"Oh! And my coachman has gone." - -But Sonya, who had gone to look for the papers in the anteroom, -had found them in Pierre's hat, where he had carefully tucked them -under the lining. Pierre was about to begin reading. - -"No, after dinner," said the old count, evidently expecting much -enjoyment from that reading. - -At dinner, at which champagne was drunk to the health of the new -chevalier of St. George, Shinshin told them the town news, of the -illness of the old Georgian princess, of Metivier's disappearance from -Moscow, and of how some German fellow had been brought to Rostopchin -and accused of being a French "spyer" (so Count Rostopchin had told -the story), and how Rostopchin let him go and assured the people -that he was "not a spire at all, but only an old German ruin." - -"People are being arrested..." said the count. "I've told the -countess she should not speak French so much. It's not the time for it -now." - -"And have you heard?" Shinshin asked. "Prince Golitsyn has engaged a -master to teach him Russian. It is becoming dangerous to speak -French in the streets." - -"And how about you, Count Peter Kirilych? If they call up the -militia, you too will have to mount a horse," remarked the old -count, addressing Pierre. - -Pierre had been silent and preoccupied all through dinner, seeming -not to grasp what was said. He looked at the count. - -"Oh yes, the war," he said. "No! What sort of warrior should I make? -And yet everything is so strange, so strange! I can't make it out. I -don't know, I am very far from having military tastes, but in these -times no one can answer for himself." - -After dinner the count settled himself comfortably in an easy -chair and with a serious face asked Sonya, who was considered an -excellent reader, to read the appeal. - - -"To Moscow, our ancient Capital! - -"The enemy has entered the borders of Russia with immense forces. He -comes to despoil our beloved country," - - -Sonya read painstakingly in her high-pitched voice. The count -listened with closed eyes, heaving abrupt sighs at certain passages. - -Natasha sat erect, gazing with a searching look now at her father -and now at Pierre. - -Pierre felt her eyes on him and tried not to look round. The -countess shook her head disapprovingly and angrily at every solemn -expression in the manifesto. In all these words she saw only that -the danger threatening her son would not soon be over. Shinshin, -with a sarcastic smile on his lips, was evidently preparing to make -fun of anything that gave him the opportunity: Sonya's reading, any -remark of the count's, or even the manifesto itself should no better -pretext present itself. - -After reading about the dangers that threatened Russia, the hopes -the Emperor placed on Moscow and especially on its illustrious -nobility, Sonya, with a quiver in her voice due chiefly to the -attention that was being paid to her, read the last words: - - -"We ourselves will not delay to appear among our people in that -Capital and in others parts of our realm for consultation, and for the -direction of all our levies, both those now barring the enemy's path -and those freshly formed to defeat him wherever he may appear. May the -ruin he hopes to bring upon us recoil on his own head, and may -Europe delivered from bondage glorify the name of Russia!" - - -"Yes, that's it!" cried the count, opening his moist eyes and -sniffing repeatedly, as if a strong vinaigrette had been held to his -nose; and he added, "Let the Emperor but say the word and we'll -sacrifice everything and begrudge nothing." - -Before Shinshin had time to utter the joke he was ready to make on -the count's patriotism, Natasha jumped up from her place and ran to -her father. - -"What a darling our Papa is!" she cried, kissing him, and she -again looked at Pierre with the unconscious coquetry that had returned -to her with her better spirits. - -"There! Here's a patriot for you!" said Shinshin. - -"Not a patriot at all, but simply..." Natasha replied in an -injured tone. "Everything seems funny to you, but this isn't at all -a joke...." - -"A joke indeed!" put in the count. "Let him but say the word and -we'll all go.... We're not Germans!" - -"But did you notice, it says, 'for consultation'?" said Pierre. - -"Never mind what it's for...." - -At this moment, Petya, to whom nobody was paying any attention, came -up to his father with a very flushed face and said in his breaking -voice that was now deep and now shrill: - -"Well, Papa, I tell you definitely, and Mamma too, it's as you -please, but I say definitely that you must let me enter the army, -because I can't... that's all...." - -The countess, in dismay, looked up to heaven, clasped her hands, and -turned angrily to her husband. - -"That comes of your talking!" said she. - -But the count had already recovered from his excitement. - -"Come, come!" said he. "Here's a fine warrior! No! Nonsense! You -must study." - -"It's not nonsense, Papa. Fedya Obolenski is younger than I, and -he's going too. Besides, all the same I can't study now when..." Petya -stopped short, flushed till he perspired, but still got out the words, -"when our Fatherland is in danger." - -"That'll do, that'll do--nonsense...." - -"But you said yourself that we would sacrifice everything." - -"Petya! Be quiet, I tell you!" cried the count, with a glance at his -wife, who had turned pale and was staring fixedly at her son. - -"And I tell you--Peter Kirilych here will also tell you..." - -"Nonsense, I tell you. Your mother's milk has hardly dried on your -lips and you want to go into the army! There, there, I tell you," -and the count moved to go out of the room, taking the papers, probably -to reread them in his study before having a nap. - -"Well, Peter Kirilych, let's go and have a smoke," he said. - -Pierre was agitated and undecided. Natasha's unwontedly brilliant -eyes, continually glancing at him with a more than cordial look, had -reduced him to this condition. - -"No, I think I'll go home." - -"Home? Why, you meant to spend the evening with us.... You don't -often come nowadays as it is, and this girl of mine," said the count -good-naturedly, pointing to Natasha, "only brightens up when you're -here." - -"Yes, I had forgotten... I really must go home... business..." -said Pierre hurriedly. - -"Well, then, au revoir!" said the count, and went out of the room. - -"Why are you going? Why are you upset?" asked Natasha, and she -looked challengingly into Pierre's eyes. - -"Because I love you!" was what he wanted to say, but he did not -say it, and only blushed till the tears came, and lowered his eyes. - -"Because it is better for me to come less often... because... No, -simply I have business...." - -"Why? No, tell me!" Natasha began resolutely and suddenly stopped. - -They looked at each other with dismayed and embarrassed faces. He -tried to smile but could not: his smile expressed suffering, and he -silently kissed her hand and went out. - -Pierre made up his mind not to go to the Rostovs' any more. - - - - - -CHAPTER XXI - - -After the definite refusal he had received, Petya went to his room -and there locked himself in and wept bitterly. When he came in to tea, -silent, morose, and with tear-stained face, everybody pretended not to -notice anything. - -Next day the Emperor arrived in Moscow, and several of the -Rostovs' domestic serfs begged permission to go to have a look at him. -That morning Petya was a long time dressing and arranging his hair and -collar to look like a grown-up man. He frowned before his looking -glass, gesticulated, shrugged his shoulders, and finally, without -saying a word to anyone, took his cap and left the house by the back -door, trying to avoid notice. Petya decided to go straight to where -the Emperor was and to explain frankly to some gentleman-in-waiting -(he imagined the Emperor to be always surrounded by -gentlemen-in-waiting) that he, Count Rostov, in spite of his youth -wished to serve his country; that youth could be no hindrance to -loyalty, and that he was ready to... While dressing, Petya had -prepared many fine things he meant to say to the gentleman-in-waiting. - -It was on the very fact of being so young that Petya counted for -success in reaching the Emperor--he even thought how surprised -everyone would be at his youthfulness--and yet in the arrangement of -his collar and hair and by his sedate deliberate walk he wished to -appear a grown-up man. But the farther he went and the more his -attention was diverted by the ever-increasing crowds moving toward the -Kremlin, the less he remembered to walk with the sedateness and -deliberation of a man. As he approached the Kremlin he even began to -avoid being crushed and resolutely stuck out his elbows in a -menacing way. But within the Trinity Gateway he was so pressed to -the wall by people who probably were unaware of the patriotic -intentions with which he had come that in spite of all his -determination he had to give in, and stop while carriages passed in, -rumbling beneath the archway. Beside Petya stood a peasant woman, a -footman, two tradesmen, and a discharged soldier. After standing -some time in the gateway, Petya tried to move forward in front of -the others without waiting for all the carriages to pass, and he began -resolutely working his way with his elbows, but the woman just in -front of him, who was the first against whom he directed his -efforts, angrily shouted at him: - -"What are you shoving for, young lordling? Don't you see we're all -standing still? Then why push?" - -"Anybody can shove," said the footman, and also began working his -elbows to such effect that he pushed Petya into a very filthy corner -of the gateway. - -Petya wiped his perspiring face with his hands and pulled up the -damp collar which he had arranged so well at home to seem like a -man's. - -He felt that he no longer looked presentable, and feared that if -he were now to approach the gentlemen-in-waiting in that plight he -would not be admitted to the Emperor. But it was impossible to smarten -oneself up or move to another place, because of the crowd. One of -the generals who drove past was an acquaintance of the Rostovs', and -Petya thought of asking his help, but came to the conclusion that that -would not be a manly thing to do. When the carriages had all passed -in, the crowd, carrying Petya with it, streamed forward into the -Kremlin Square which was already full of people. There were people not -only in the square, but everywhere--on the slopes and on the roofs. As -soon as Petya found himself in the square he clearly heard the sound -of bells and the joyous voices of the crowd that filled the whole -Kremlin. - -For a while the crowd was less dense, but suddenly all heads were -bared, and everyone rushed forward in one direction. Petya was being -pressed so that he could scarcely breathe, and everybody shouted, -"Hurrah! hurrah! hurrah!" Petya stood on tiptoe and pushed and -pinched, but could see nothing except the people about him. - -All the faces bore the same expression of excitement and enthusiasm. -A tradesman's wife standing beside Petya sobbed, and the tears ran -down her cheeks. - -"Father! Angel! Dear one!" she kept repeating, wiping away her tears -with her fingers. - -"Hurrah!" was heard on all sides. - -For a moment the crowd stood still, but then it made another rush -forward. - -Quite beside himself, Petya, clinching his teeth and rolling his -eyes ferociously, pushed forward, elbowing his way and shouting -"hurrah!" as if he were prepared that instant to kill himself and -everyone else, but on both sides of him other people with similarly -ferocious faces pushed forward and everybody shouted "hurrah!" - -"So this is what the Emperor is!" thought Petya. "No, I can't -petition him myself--that would be too bold." But in spite of this -he continued to struggle desperately forward, and from between the -backs of those in front he caught glimpses of an open space with a -strip of red cloth spread out on it; but just then the crowd swayed -back--the police in front were pushing back those who had pressed -too close to the procession: the Emperor was passing from the palace -to the Cathedral of the Assumption--and Petya unexpectedly received -such a blow on his side and ribs and was squeezed so hard that -suddenly everything grew dim before his eyes and he lost -consciousness. When he came to himself, a man of clerical appearance -with a tuft of gray hair at the back of his head and wearing a -shabby blue cassock--probably a church clerk and chanter--was -holding him under the arm with one hand while warding off the pressure -of the crowd with the other. - -"You've crushed the young gentleman!" said the clerk. "What are -you up to? Gently!... They've crushed him, crushed him!" - -The Emperor entered the Cathedral of the Assumption. The crowd -spread out again more evenly, and the clerk led Petya--pale and -breathless--to the Tsar-cannon. Several people were sorry for Petya, -and suddenly a crowd turned toward him and pressed round him. Those -who stood nearest him attended to him, unbuttoned his coat, seated him -on the raised platform of the cannon, and reproached those others -(whoever they might be) who had crushed him. - -"One might easily get killed that way! What do they mean by it? -Killing people! Poor dear, he's as white as a sheet!"--various -voices were heard saying. - -Petya soon came to himself, the color returned to his face, the pain -had passed, and at the cost of that temporary unpleasantness he had -obtained a place by the cannon from where he hoped to see the -Emperor who would be returning that way. Petya no longer thought of -presenting his petition. If he could only see the Emperor he would -be happy! - -While the service was proceeding in the Cathedral of the Assumption- -it was a combined service of prayer on the occasion of the Emperor's -arrival and of thanksgiving for the conclusion of peace with the -Turks--the crowd outside spread out and hawkers appeared, selling -kvas, gingerbread, and poppyseed sweets (of which Petya was -particularly fond), and ordinary conversation could again be heard. -A tradesman's wife was showing a rent in her shawl and telling how -much the shawl had cost; another was saying that all silk goods had -now got dear. The clerk who had rescued Petya was talking to a -functionary about the priests who were officiating that day with the -bishop. The clerk several times used the word "plenary" (of the -service), a word Petya did not understand. Two young citizens were -joking with some serf girls who were cracking nuts. All these -conversations, especially the joking with the girls, were such as -might have had a particular charm for Petya at his age, but they did -not interest him now. He sat on his elevation--the pedestal of the -cannon--still agitated as before by the thought of the Emperor and -by his love for him. The feeling of pain and fear he had experienced -when he was being crushed, together with that of rapture, still -further intensified his sense of the importance of the occasion. - -Suddenly the sound of a firing of cannon was heard from the -embankment, to celebrate the signing of peace with the Turks, and -the crowd rushed impetuously toward the embankment to watch the -firing. Petya too would have run there, but the clerk who had taken -the young gentleman under his protection stopped him. The firing was -still proceeding when officers, generals, and gentlemen-in-waiting -came running out of the cathedral, and after them others in a more -leisurely manner: caps were again raised, and those who had run to -look at the cannon ran back again. At last four men in uniforms and -sashes emerged from the cathedral doors. "Hurrah! hurrah!" shouted the -crowd again. - -"Which is he? Which?" asked Petya in a tearful voice, of those -around him, but no one answered him, everybody was too excited; and -Petya, fixing on one of those four men, whom he could not clearly -see for the tears of joy that filled his eyes, concentrated all his -enthusiasm on him--though it happened not to be the Emperor- -frantically shouted "Hurrah!" and resolved that tomorrow, come what -might, he would join the army. - -The crowd ran after the Emperor, followed him to the palace, and -began to disperse. It was already late, and Petya had not eaten -anything and was drenched with perspiration, yet he did not go home -but stood with that diminishing, but still considerable, crowd -before the palace while the Emperor dined--looking in at the palace -windows, expecting he knew not what, and envying alike the notables he -saw arriving at the entrance to dine with the Emperor and the court -footmen who served at table, glimpses of whom could be seen through -the windows. - -While the Emperor was dining, Valuev, looking out of the window, -said: - -"The people are still hoping to see Your Majesty again." - -The dinner was nearly over, and the Emperor, munching a biscuit, -rose and went out onto the balcony. The people, with Petya among them, -rushed toward the balcony. - -"Angel! Dear one! Hurrah! Father!..." cried the crowd, and Petya -with it, and again the women and men of weaker mold, Petya among them, -wept with joy. - -A largish piece of the biscuit the Emperor was holding in his hand -broke off, fell on the balcony parapet, and then to the ground. A -coachman in a jerkin, who stood nearest, sprang forward and snatched -it up. Several people in the crowd rushed at the coachman. Seeing this -the Emperor had a plateful of biscuits brought him and began -throwing them down from the balcony. Petya's eyes grew bloodshot, -and still more excited by the danger of being crushed, he rushed at -the biscuits. He did not know why, but he had to have a biscuit from -the Tsar's hand and he felt that he must not give way. He sprang -forward and upset an old woman who was catching at a biscuit; the -old woman did not consider herself defeated though she was lying on -the ground--she grabbed at some biscuits but her hand did not reach -them. Petya pushed her hand away with his knee, seized a biscuit, -and as if fearing to be too late, again shouted "Hurrah!" with a voice -already hoarse. - -The Emperor went in, and after that the greater part of the crowd -began to disperse. - -"There! I said if only we waited--and so it was!" was being joyfully -said by various people. - -Happy as Petya was, he felt sad at having to go home knowing that -all the enjoyment of that day was over. He did not go straight home -from the Kremlin, but called on his friend Obolenski, who was -fifteen and was also entering the regiment. On returning home Petya -announced resolutely and firmly that if he was not allowed to enter -the service he would run away. And next day, Count Ilya Rostov--though -he had not yet quite yielded--went to inquire how he could arrange for -Petya to serve where there would be least danger. - - - - - -CHAPTER XXII - - -Two days later, on the fifteenth of July, an immense number of -carriages were standing outside the Sloboda Palace. - -The great halls were full. In the first were the nobility and gentry -in their uniforms, in the second bearded merchants in full-skirted -coats of blue cloth and wearing medals. In the noblemen's hall there -was an incessant movement and buzz of voices. The chief magnates sat -on high-backed chairs at a large table under the portrait of the -Emperor, but most of the gentry were strolling about the room. - -All these nobles, whom Pierre met every day at the Club or in -their own houses, were in uniform--some in that of Catherine's day, -others in that of Emperor Paul, others again in the new uniforms of -Alexander's time or the ordinary uniform of the nobility, and the -general characteristic of being in uniform imparted something -strange and fantastic to these diverse and familiar personalities, -both old and young. The old men, dim-eyed, toothless, bald, sallow, -and bloated, or gaunt and wrinkled, were especially striking. For -the most part they sat quietly in their places and were silent, or, if -they walked about and talked, attached themselves to someone -younger. On all these faces, as on the faces of the crowd Petya had -seen in the Square, there was a striking contradiction: the general -expectation of a solemn event, and at the same time the everyday -interests in a boston card party, Peter the cook, Zinaida Dmitrievna's -health, and so on. - -Pierre was there too, buttoned up since early morning in a -nobleman's uniform that had become too tight for him. He was agitated; -this extraordinary gathering not only of nobles but also of the -merchant-class--les etats generaux (States-General)--evoked in him a -whole series of ideas he had long laid aside but which were deeply -graven in his soul: thoughts of the Contrat social and the French -Revolution. The words that had struck him in the Emperor's appeal- -that the sovereign was coming to the capital for consultation with his -people--strengthened this idea. And imagining that in this direction -something important which he had long awaited was drawing near, he -strolled about watching and listening to conversations, but nowhere -finding any confirmation of the ideas that occupied him. - -The Emperor's manifesto was read, evoking enthusiasm, and then all -moved about discussing it. Besides the ordinary topics of -conversation, Pierre heard questions of where the marshals of the -nobility were to stand when the Emperor entered, when a ball should be -given in the Emperor's honor, whether they should group themselves -by districts or by whole provinces... and so on; but as soon as the -war was touched on, or what the nobility had been convened for, the -talk became undecided and indefinite. Then all preferred listening -to speaking. - -A middle-aged man, handsome and virile, in the uniform of a -retired naval officer, was speaking in one of the rooms, and a small -crowd was pressing round him. Pierre went up to the circle that had -formed round the speaker and listened. Count Ilya Rostov, in a -military uniform of Catherine's time, was sauntering with a pleasant -smile among the crowd, with all of whom he was acquainted. He too -approached that group and listened with a kindly smile and nods of -approval, as he always did, to what the speaker was saying. The -retired naval man was speaking very boldly, as was evident from the -expression on the faces of the listeners and from the fact that some -people Pierre knew as the meekest and quietest of men walked away -disapprovingly or expressed disagreement with him. Pierre pushed his -way into the middle of the group, listened, and convinced himself that -the man was indeed a liberal, but of views quite different from his -own. The naval officer spoke in a particularly sonorous, musical, -and aristocratic baritone voice, pleasantly swallowing his r's and -generally slurring his consonants: the voice of a man calling out to -his servant, "Heah! Bwing me my pipe!" It was indicative of -dissipation and the exercise of authority. - -"What if the Smolensk people have offahd to waise militia for the -Empewah? Ah we to take Smolensk as our patte'n? If the noble -awistocwacy of the pwovince of Moscow thinks fit, it can show its -loyalty to our sov'weign the Empewah in other ways. Have we -fo'gotten the waising of the militia in the yeah 'seven? All that -did was to enwich the pwiests' sons and thieves and wobbahs...." - -Count Ilya Rostov smiled blandly and nodded approval. - -"And was our militia of any use to the Empia? Not at all! It only -wuined our farming! Bettah have another conscwiption... o' ou' men -will wetu'n neithah soldiers no' peasants, and we'll get only -depwavity fwom them. The nobility don't gwudge theah lives--evewy -one of us will go and bwing in more wecwuits, and the sov'weign" (that -was the way he referred to the Emperor) "need only say the word and -we'll all die fo' him!" added the orator with animation. - -Count Rostov's mouth watered with pleasure and he nudged Pierre, but -Pierre wanted to speak himself. He pushed forward, feeling stirred, -but not yet sure what stirred him or what he would say. Scarcely had -he opened his mouth when one of the senators, a man without a tooth in -his head, with a shrewd though angry expression, standing near the -first speaker, interrupted him. Evidently accustomed to managing -debates and to maintaining an argument, he began in low but distinct -tones: - -"I imagine, sir," said he, mumbling with his toothless mouth, -"that we have been summoned here not to discuss whether it's best -for the empire at the present moment to adopt conscription or to -call out the militia. We have been summoned to reply to the appeal -with which our sovereign the Emperor has honored us. But to judge what -is best--conscription or the militia--we can leave to the supreme -authority...." - -Pierre suddenly saw an outlet for his excitement. He hardened his -heart against the senator who was introducing this set and narrow -attitude into the deliberations of the nobility. Pierre stepped -forward and interrupted him. He himself did not yet know what he would -say, but he began to speak eagerly, occasionally lapsing into French -or expressing himself in bookish Russian. - -"Excuse me, your excellency," he began. (He was well acquainted with -the senator, but thought it necessary on this occasion to address -him formally.) "Though I don't agree with the gentleman..." (he -hesitated: he wished to say, "Mon tres honorable preopinant"--"My very -honorable opponent") "with the gentleman... whom I have not the -honor of knowing, I suppose that the nobility have been summoned not -merely to express their sympathy and enthusiasm but also to consider -the means by which we can assist our Fatherland! I imagine," he went -on, warming to his subject, "that the Emperor himself would not be -satisfied to find in us merely owners of serfs whom we are willing -to devote to his service, and chair a canon* we are ready to make of -ourselves--and not to obtain from us any co-co-counsel." - - -*"Food for cannon." - - -Many persons withdrew from the circle, noticing the senator's -sarcastic smile and the freedom of Pierre's remarks. Only Count Rostov -was pleased with them as he had been pleased with those of the naval -officer, the senator, and in general with whatever speech he had -last heard. - -"I think that before discussing these questions," Pierre -continued, "we should ask the Emperor--most respectfully ask His -Majesty--to let us know the number of our troops and the position in -which our army and our forces now are, and then..." - -But scarcely had Pierre uttered these words before he was attacked -from three sides. The most vigorous attack came from an old -acquaintance, a boston player who had always been well disposed toward -him, Stepan Stepanovich Adraksin. Adraksin was in uniform, and whether -as a result of the uniform or from some other cause Pierre saw -before him quite a different man. With a sudden expression of -malevolence on his aged face, Adraksin shouted at Pierre: - -"In the first place, I tell you we have no right to question the -Emperor about that, and secondly, if the Russian nobility had that -right, the Emperor could not answer such a question. The troops are -moved according to the enemy's movements and the number of men -increases and decreases..." - -Another voice, that of a nobleman of medium height and about forty -years of age, whom Pierre had formerly met at the gypsies' and knew as -a bad cardplayer, and who, also transformed by his uniform, came up to -Pierre, interrupted Adraksin. - -"Yes, and this is not a time for discussing," he continued, "but for -acting: there is war in Russia! The enemy is advancing to destroy -Russia, to desecrate the tombs of our fathers, to carry off our -wives and children." The nobleman smote his breast. "We will all -arise, every one of us will go, for our father the Tsar!" he -shouted, rolling his bloodshot eyes. Several approving voices were -heard in the crowd. "We are Russians and will not grudge our blood -in defense of our faith, the throne, and the Fatherland! We must cease -raving if we are sons of our Fatherland! We will show Europe how -Russia rises to the defense of Russia!" - -Pierre wished to reply, but could not get in a word. He felt that -his words, apart from what meaning they conveyed, were less audible -than the sound of his opponent's voice. - -Count Rostov at the back of the crowd was expressing approval; -several persons, briskly turning a shoulder to the orator at the end -of a phrase, said: - -"That's right, quite right! Just so!" - -Pierre wished to say that he was ready to sacrifice his money, his -serfs, or himself, only one ought to know the state of affairs in -order to be able to improve it, but he was unable to speak. Many -voices shouted and talked at the same time, so that Count Rostov had -not time to signify his approval of them all, and the group increased, -dispersed, re-formed, and then moved with a hum of talk into the -largest hall and to the big table. Not only was Pierre's attempt to -speak unsuccessful, but he was rudely interrupted, pushed aside, and -people turned away from him as from a common enemy. This happened -not because they were displeased by the substance of his speech, which -had even been forgotten after the many subsequent speeches, but to -animate it the crowd needed a tangible object to love and a tangible -object to hate. Pierre became the latter. Many other orators spoke -after the excited nobleman, and all in the same tone. Many spoke -eloquently and with originality. - -Glinka, the editor of the Russian Messenger, who was recognized -(cries of "author! author!" were heard in the crowd), said that -"hell must be repulsed by hell," and that he had seen a child -smiling at lightning flashes and thunderclaps, but "we will not be -that child." - -"Yes, yes, at thunderclaps!" was repeated approvingly in the back -rows of the crowd. - -The crowd drew up to the large table, at which sat gray-haired or -bald seventy-year-old magnates, uniformed and besashed almost all of -whom Pierre had seen in their own homes with their buffoons, or -playing boston at the clubs. With an incessant hum of voices the crowd -advanced to the table. Pressed by the throng against the high backs of -the chairs, the orators spoke one after another and sometimes two -together. Those standing behind noticed what a speaker omitted to -say and hastened to supply it. Others in that heat and crush racked -their brains to find some thought and hastened to utter it. The old -magnates, whom Pierre knew, sat and turned to look first at one and -then at another, and their faces for the most part only expressed -the fact that they found it very hot. Pierre, however, felt excited, -and the general desire to show that they were ready to go to all -lengths--which found expression in the tones and looks more than in -the substance of the speeches--infected him too. He did not renounce -his opinions, but felt himself in some way to blame and wished to -justify himself. - -"I only said that it would be more to the purpose to make sacrifices -when we know what is needed!" said he, trying to be heard above the -other voices. - -One of the old men nearest to him looked round, but his attention -was immediately diverted by an exclamation at the other side of the -table. - -"Yes, Moscow will be surrendered! She will be our expiation!" -shouted one man. - -"He is the enemy of mankind!" cried another. "Allow me to speak...." -"Gentlemen, you are crushing me!..." - - - - - -CHAPTER XXIII - - -At that moment Count Rostopchin with his protruding chin and alert -eyes, wearing the uniform of a general with sash over his shoulder, -entered the room, stepping briskly to the front of the crowd of -gentry. - -"Our sovereign the Emperor will be here in a moment," said -Rostopchin. "I am straight from the palace. Seeing the position we are -in, I think there is little need for discussion. The Emperor has -deigned to summon us and the merchants. Millions will pour forth -from there"--he pointed to the merchants' hall--"but our business is -to supply men and not spare ourselves... That is the least we can do!" - -A conference took place confined to the magnates sitting at the -table. The whole consultation passed more than quietly. After all -the preceding noise the sound of their old voices saying one after -another, "I agree," or for variety, "I too am of that opinion," and so -on had even a mournful effect. - -The secretary was told to write down the resolution of the Moscow -nobility and gentry, that they would furnish ten men, fully -equipped, out of every thousand serfs, as the Smolensk gentry had -done. Their chairs made a scraping noise as the gentlemen who had -conferred rose with apparent relief, and began walking up and down, -arm in arm, to stretch their legs and converse in couples. - -"The Emperor! The Emperor!" a sudden cry resounded through the halls -and the whole throng hurried to the entrance. - -The Emperor entered the hall through a broad path between two -lines of nobles. Every face expressed respectful, awe-struck -curiosity. Pierre stood rather far off and could not hear all that the -Emperor said. From what he did hear he understood that the Emperor -spoke of the danger threatening the empire and of the hopes he -placed on the Moscow nobility. He was answered by a voice which -informed him of the resolution just arrived at. - -"Gentlemen!" said the Emperor with a quivering voice. - -There was a rustling among the crowd and it again subsided, so -that Pierre distinctly heard the pleasantly human voice of the Emperor -saying with emotion: - -"I never doubted the devotion of the Russian nobles, but today it -has surpassed my expectations. I thank you in the name of the -Fatherland! Gentlemen, let us act! Time is most precious..." - -The Emperor ceased speaking, the crowd began pressing round him, and -rapturous exclamations were heard from all sides. - -"Yes, most precious... a royal word," said Count Rostov, with a sob. -He stood at the back, and, though he had heard hardly anything, -understood everything in his own way. - -From the hall of the nobility the Emperor went to that of the -merchants. There he remained about ten minutes. Pierre was among those -who saw him come out from the merchants' hall with tears of emotion in -his eyes. As became known later, he had scarcely begun to address -the merchants before tears gushed from his eyes and he concluded in -a trembling voice. When Pierre saw the Emperor he was coming out -accompanied by two merchants, one of whom Pierre knew, a fat -otkupshchik. The other was the mayor, a man with a thin sallow face -and narrow beard. Both were weeping. Tears filled the thin man's eyes, -and the fat otkupshchik sobbed outright like a child and kept -repeating: - -"Our lives and property--take them, Your Majesty!" - -Pierre's one feeling at the moment was a desire to show that he -was ready to go all lengths and was prepared to sacrifice -everything. He now felt ashamed of his speech with its -constitutional tendency and sought an opportunity of effacing it. -Having heard that Count Mamonov was furnishing a regiment, Bezukhov at -once informed Rostopchin that he would give a thousand men and their -maintenance. - -Old Rostov could not tell his wife of what had passed without tears, -and at once consented to Petya's request and went himself to enter his -name. - -Next day the Emperor left Moscow. The assembled nobles all took -off their uniforms and settled down again in their homes and clubs, -and not without some groans gave orders to their stewards about the -enrollment, feeling amazed themselves at what they had done. - - - - - -BOOK TEN: 1812 - - - - - -CHAPTER I - - -Napoleon began the war with Russia because he could not resist going -to Dresden, could not help having his head turned by the homage he -received, could not help donning a Polish uniform and yielding to -the stimulating influence of a June morning, and could not refrain -from bursts of anger in the presence of Kurakin and then of Balashev. - -Alexander refused negotiations because he felt himself to be -personally insulted. Barclay de Tolly tried to command the army in the -best way, because he wished to fulfill his duty and earn fame as a -great commander. Rostov charged the French because he could not -restrain his wish for a gallop across a level field; and in the same -way the innumerable people who took part in the war acted in accord -with their personal characteristics, habits, circumstances, and -aims. They were moved by fear or vanity, rejoiced or were indignant, -reasoned, imagining that they knew what they were doing and did it -of their own free will, but they all were involuntary tools of -history, carrying on a work concealed from them but comprehensible -to us. Such is the inevitable fate of men of action, and the higher -they stand in the social hierarchy the less are they free. - -The actors of 1812 have long since left the stage, their personal -interests have vanished leaving no trace, and nothing remains of -that time but its historic results. - -Providence compelled all these men, striving to attain personal -aims, to further the accomplishment of a stupendous result no one of -them at all expected--neither Napoleon, nor Alexander, nor still -less any of those who did the actual fighting. - -The cause of the destruction of the French army in 1812 is clear -to us now. No one will deny that that cause was, on the one hand, -its advance into the heart of Russia late in the season without any -preparation for a winter campaign and, on the other, the character -given to the war by the burning of Russian towns and the hatred of the -foe this aroused among the Russian people. But no one at the time -foresaw (what now seems so evident) that this was the only way an army -of eight hundred thousand men--the best in the world and led by the -best general--could be destroyed in conflict with a raw army of half -its numerical strength, and led by inexperienced commanders as the -Russian army was. Not only did no one see this, but on the Russian -side every effort was made to hinder the only thing that could save -Russia, while on the French side, despite Napoleon's experience and -so-called military genius, every effort was directed to pushing on -to Moscow at the end of the summer, that is, to doing the very thing -that was bound to lead to destruction. - -In historical works on the year 1812 French writers are very fond of -saying that Napoleon felt the danger of extending his line, that he -sought a battle and that his marshals advised him to stop at Smolensk, -and of making similar statements to show that the danger of the -campaign was even then understood. Russian authors are still fonder of -telling us that from the commencement of the campaign a Scythian war -plan was adopted to lure Napoleon into the depths of Russia, and -this plan some of them attribute to Pfuel, others to a certain -Frenchman, others to Toll, and others again to Alexander himself- -pointing to notes, projects, and letters which contain hints of such a - -line of action. But all these hints at what happened, both from the -French side and the Russian, are advanced only because they fit in -with the event. Had that event not occurred these hints would have -been forgotten, as we have forgotten the thousands and millions of -hints and expectations to the contrary which were current then but -have now been forgotten because the event falsified them. There are -always so many conjectures as to the issue of any event that however -it may end there will always be people to say: "I said then that it -would be so," quite forgetting that amid their innumerable conjectures -many were to quite the contrary effect. - -Conjectures as to Napoleon's awareness of the danger of extending -his line, and (on the Russian side) as to luring the enemy into the -depths of Russia, are evidently of that kind, and only by much -straining can historians attribute such conceptions to Napoleon and -his marshals, or such plans to the Russian commanders. All the facts -are in flat contradiction to such conjectures. During the whole period -of the war not only was there no wish on the Russian side to draw -the French into the heart of the country, but from their first entry -into Russia everything was done to stop them. And not only was -Napoleon not afraid to extend his line, but he welcomed every step -forward as a triumph and did not seek battle as eagerly as in former -campaigns, but very lazily. - -At the very beginning of the war our armies were divided, and our -sole aim was to unite them, though uniting the armies was no advantage -if we meant to retire and lure the enemy into the depths of the -country. Our Emperor joined the army to encourage it to defend every -inch of Russian soil and not to retreat. The enormous Drissa camp -was formed on Pfuel's plan, and there was no intention of retiring -farther. The Emperor reproached the commanders in chief for every step -they retired. He could not bear the idea of letting the enemy even -reach Smolensk, still less could he contemplate the burning of Moscow, -and when our armies did unite he was displeased that Smolensk was -abandoned and burned without a general engagement having been fought -under its walls. - -So thought the Emperor, and the Russian commanders and people were -still more provoked at the thought that our forces were retreating -into the depths of the country. - -Napoleon having cut our armies apart advanced far into the country -and missed several chances of forcing an engagement. In August he -was at Smolensk and thought only of how to advance farther, though -as we now see that advance was evidently ruinous to him. - -The facts clearly show that Napoleon did not foresee the danger of -the advance on Moscow, nor did Alexander and the Russian commanders -then think of luring Napoleon on, but quite the contrary. The luring -of Napoleon into the depths of the country was not the result of any -plan, for no one believed it to be possible; it resulted from a most -complex interplay of intrigues, aims, and wishes among those who -took part in the war and had no perception whatever of the inevitable, -or of the one way of saving Russia. Everything came about -fortuitously. The armies were divided at the commencement of the -campaign. We tried to unite them, with the evident intention of giving -battle and checking the enemy's advance, and by this effort to unite -them while avoiding battle with a much stronger enemy, and necessarily -withdrawing the armies at an acute angle--we led the French on to -Smolensk. But we withdrew at an acute angle not only because the -French advanced between our two armies; the angle became still more -acute and we withdrew still farther, because Barclay de Tolly was an -unpopular foreigner disliked by Bagration (who would come his -command), and Bagration--being in command of the second army--tried to -postpone joining up and coming under Barclay's command as long as he -could. Bagration was slow in effecting the junction--though that was -the chief aim of all at headquarters--because, as he alleged, he -exposed his army to danger on this march, and it was best for him to -retire more to the left and more to the south, worrying the enemy from -flank and rear and securing from the Ukraine recruits for his army; -and it looks as if he planned this in order not to come under the -command of the detested foreigner Barclay, whose rank was inferior -to his own. - -The Emperor was with the army to encourage it, but his presence -and ignorance of what steps to take, and the enormous number of -advisers and plans, destroyed the first army's energy and it retired. - -The intention was to make a stand at the Drissa camp, but -Paulucci, aiming at becoming commander in chief, unexpectedly employed -his energy to influence Alexander, and Pfuel's whole plan was -abandoned and the command entrusted to Barclay. But as Barclay did not -inspire confidence his power was limited. The armies were divided, -there was no unity of command, and Barclay was unpopular; but from -this confusion, division, and the unpopularity of the foreign -commander in chief, there resulted on the one hand indecision and -the avoidance of a battle (which we could not have refrained from -had the armies been united and had someone else, instead of Barclay, -been in command) and on the other an ever-increasing indignation -against the foreigners and an increase in patriotic zeal. - -At last the Emperor left the army, and as the most convenient and -indeed the only pretext for his departure it was decided that it was -necessary for him to inspire the people in the capitals and arouse the -nation in general to a patriotic war. And by this visit of the Emperor -to Moscow the strength of the Russian army was trebled. - -He left in order not to obstruct the commander in chief's -undivided control of the army, and hoping that more decisive action -would then be taken, but the command of the armies became still more -confused and enfeebled. Bennigsen, the Tsarevich, and a swarm of -adjutants general remained with the army to keep the commander in -chief under observation and arouse his energy, and Barclay, feeling -less free than ever under the observation of all these "eyes of the -Emperor," became still more cautious of undertaking any decisive -action and avoided giving battle. - -Barclay stood for caution. The Tsarevich hinted at treachery and -demanded a general engagement. Lubomirski, Bronnitski, Wlocki, and the -others of that group stirred up so much trouble that Barclay, under -pretext of sending papers to the Emperor, dispatched these Polish -adjutants general to Petersburg and plunged into an open struggle with -Bennigsen and the Tsarevich. - -At Smolensk the armies at last reunited, much as Bagration -disliked it. - -Bagration drove up in a carriage to to the house occupied by -Barclay. Barclay donned his sash and came out to meet and report to -his senior officer Bagration. - -Despite his seniority in rank Bagration, in this contest of -magnanimity, took his orders from Barclay, but, having submitted, -agreed with him less than ever. By the Emperor's orders Bagration -reported direct to him. He wrote to Arakcheev, the Emperor's -confidant: "It must be as my sovereign pleases, but I cannot work with -the Minister (meaning Barclay). For God's sake send me somewhere -else if only in command of a regiment. I cannot stand it here. -Headquarters are so full of Germans that a Russian cannot exist and -there is no sense in anything. I thought I was really serving my -sovereign and the Fatherland, but it turns out that I am serving -Barclay. I confess I do not want to." - -The swarm of Bronnitskis and Wintzingerodes and their like still -further embittered the relations between the commanders in chief, -and even less unity resulted. Preparations were made to fight the -French before Smolensk. A general was sent to survey the position. -This general, hating Barclay, rode to visit a friend of his own, a -corps commander, and, having spent the day with him, returned to -Barclay and condemned, as unsuitable from every point of view, the -battleground he had not seen. - -While disputes and intrigues were going on about the future field of -battle, and while we were looking for the French--having lost touch -with them--the French stumbled upon Neverovski's division and -reached the walls of Smolensk. - -It was necessary to fight an unexpected battle at Smolensk to save -our lines of communication. The battle was fought and thousands were -killed on both sides. - -Smolensk was abandoned contrary to the wishes of the Emperor and -of the whole people. But Smolensk was burned by its own -inhabitants-who had been misled by their governor. And these ruined -inhabitants, setting an example to other Russians, went to Moscow -thinking only of their own losses but kindling hatred of the foe. -Napoleon advanced farther and we retired, thus arriving at the very -result which caused his destruction. - - - - - -CHAPTER II - - -The day after his son had left, Prince Nicholas sent for Princess -Mary to come to his study. - -"Well? Are you satisfied now?" said he. "You've made me quarrel with -my son! Satisfied, are you? That's all you wanted! Satisfied?... It -hurts me, it hurts. I'm old and weak and this is what you wanted. Well -then, gloat over it! Gloat over it!" - -After that Princess Mary did not see her father for a whole week. He -was ill and did not leave his study. - -Princess Mary noticed to her surprise that during this illness the -old prince not only excluded her from his room, but did not admit -Mademoiselle Bourienne either. Tikhon alone attended him. - -At the end of the week the prince reappeared and resumed his -former way of life, devoting himself with special activity to building -operations and the arrangement of the gardens and completely -breaking off his relations with Mademoiselle Bourienne. His looks -and cold tone to his daughter seemed to say: "There, you see? You -plotted against me, you lied to Prince Andrew about my relations -with that Frenchwoman and made me quarrel with him, but you see I need -neither her nor you!" - -Princess Mary spent half of every day with little Nicholas, watching -his lessons, teaching him Russian and music herself, and talking to -Dessalles; the rest of the day she spent over her books, with her -old nurse, or with "God's folk" who sometimes came by the back door to -see her. - -Of the war Princess Mary thought as women do think about wars. She -feared for her brother who was in it, was horrified by and amazed at -the strange cruelty that impels men to kill one another, but she did -not understand the significance of this war, which seemed to her -like all previous wars. She did not realize the significance of this -war, though Dessalles with whom she constantly conversed was -passionately interested in its progress and tried to explain his own -conception of it to her, and though the "God's folk" who came to see -her reported, in their own way, the rumors current among the people of -an invasion by Antichrist, and though Julie (now Princess -Drubetskaya), who had resumed correspondence with her, wrote patriotic -letters from Moscow. - -"I write you in Russian, my good friend," wrote Julie in her -Frenchified Russian, "because I have a detestation for all the French, -and the same for their language which I cannot support to hear -spoken.... We in Moscow are elated by enthusiasm for our adored -Emperor. - -"My poor husband is enduring pains and hunger in Jewish taverns, but -the news which I have inspires me yet more. - -"You heard probably of the heroic exploit of Raevski, embracing -his two sons and saying: 'I will perish with them but we will not be -shaken!' And truly though the enemy was twice stronger than we, we -were unshakable. We pass the time as we can, but in war as in war! The -princesses Aline and Sophie sit whole days with me, and we, unhappy -widows of live men, make beautiful conversations over our charpie, -only you, my friend, are missing..." and so on. - -The chief reason Princess Mary did not realize the full significance -of this war was that the old prince never spoke of it, did not -recognize it, and laughed at Dessalles when he mentioned it at dinner. -The prince's tone was so calm and confident that Princess Mary -unhesitatingly believed him. - -All that July the old prince was exceedingly active and even -animated. He planned another garden and began a new building for the -domestic serfs. The only thing that made Princess Mary anxious about -him was that he slept very little and, instead of sleeping in his -study as usual, changed his sleeping place every day. One day he would -order his camp bed to be set up in the glass gallery, another day he -remained on the couch or on the lounge chair in the drawing room and -dozed there without undressing, while--instead of Mademoiselle -Bourienne--a serf boy read to him. Then again he would spend a night -in the dining room. - -On August 1, a second letter was received from Prince Andrew. In his -first letter which came soon after he had left home, Prince Andrew had -dutifully asked his father's forgiveness for what he had allowed -himself to say and begged to be restored to his favor. To this -letter the old prince had replied affectionately, and from that time -had kept the Frenchwoman at a distance. Prince Andrew's second letter, -written near Vitebsk after the French had occupied that town, gave a -brief account of the whole campaign, enclosed for them a plan he had -drawn and forecasts as to the further progress of the war. In this -letter Prince Andrew pointed out to his father the danger of staying -at Bald Hills, so near the theater of war and on the army's direct -line of march, and advised him to move to Moscow. - -At dinner that day, on Dessalles' mentioning that the French were -said to have already entered Vitebsk, the old prince remembered his -son's letter. - -"There was a letter from Prince Andrew today," he said to Princess -Mary--"Haven't you read it?" - -"No, Father," she replied in a frightened voice. - -She could not have read the letter as she did not even know it had -arrived. - -"He writes about this war," said the prince, with the ironic smile -that had become habitual to him in speaking of the present war. - -"That must be very interesting," said Dessalles. "Prince Andrew is -in a position to know..." - -"Oh, very interesting!" said Mademoiselle Bourienne. - -"Go and get it for me," said the old prince to Mademoiselle -Bourienne. "You know--under the paperweight on the little table." - -Mademoiselle Bourienne jumped up eagerly. - -"No, don't!" he exclaimed with a frown. "You go, Michael Ivanovich." - -Michael Ivanovich rose and went to the study. But as soon as he -had left the room the old prince, looking uneasily round, threw down -his napkin and went himself. - -"They can't do anything... always make some muddle," he muttered. - -While he was away Princess Mary, Dessalles, Mademoiselle -Bourienne, and even little Nicholas exchanged looks in silence. The -old prince returned with quick steps, accompanied by Michael -Ivanovich, bringing the letter and a plan. These he put down beside -him--not letting anyone read them at dinner. - -On moving to the drawing room he handed the letter to Princess -Mary and, spreading out before him the plan of the new building and -fixing his eyes upon it, told her to read the letter aloud. When she -had done so Princess Mary looked inquiringly at her father. He was -examining the plan, evidently engrossed in his own ideas. - -"What do you think of it, Prince?" Dessalles ventured to ask. - -"I? I?..." said the prince as if unpleasantly awakened, and not -taking his eyes from the plan of the building. - -"Very possibly the theater of war will move so near to us that..." - -"Ha ha ha! The theater of war!" said the prince. "I have said and -still say that the theater of war is Poland and the enemy will never -get beyond the Niemen." - -Dessalles looked in amazement at the prince, who was talking of -the Niemen when the enemy was already at the Dnieper, but Princess -Mary, forgetting the geographical position of the Niemen, thought that -what her father was saying was correct. - -"When the snow melts they'll sink in the Polish swamps. Only they -could fail to see it," the prince continued, evidently thinking of the -campaign of 1807 which seemed to him so recent. "Bennigsen should have -advanced into Prussia sooner, then things would have taken a different -turn..." - -"But, Prince," Dessalles began timidly, "the letter mentions -Vitebsk...." - -"Ah, the letter? Yes..." replied the prince peevishly. "Yes... -yes..." His face suddenly took on a morose expression. He paused. -"Yes, he writes that the French were beaten at... at... what river -is it?" - -Dessalles dropped his eyes. - -"The prince says nothing about that," he remarked gently. - -"Doesn't he? But I didn't invent it myself." - -No one spoke for a long time. - -"Yes... yes... Well, Michael Ivanovich," he suddenly went on, -raising his head and pointing to the plan of the building, "tell me -how you mean to alter it...." - -Michael Ivanovich went up to the plan, and the prince after speaking -to him about the building looked angrily at Princess Mary and -Dessalles and went to his own room. - -Princess Mary saw Dessalles' embarrassed and astonished look fixed -on her father, noticed his silence, and was struck by the fact that -her father had forgotten his son's letter on the drawing-room table; -but she was not only afraid to speak of it and ask Dessalles the -reason of his confusion and silence, but was afraid even to think -about it. - -In the evening Michael Ivanovich, sent by the prince, came to -Princess Mary for Prince Andrew's letter which had been forgotten in -the drawing room. She gave it to him and, unpleasant as it was to -her to do so, ventured to ask him what her father was doing. - -"Always busy," replied Michael Ivanovich with a respectfully -ironic smile which caused Princess Mary to turn pale. "He's worrying -very much about the new building. He has been reading a little, but -now"--Michael Ivanovich went on, lowering his voice--"now he's at -his desk, busy with his will, I expect." (One of the prince's favorite -occupations of late had been the preparation of some papers he meant -to leave at his death and which he called his "will.") - -"And Alpatych is being sent to Smolensk?" asked Princess Mary. - -"Oh, yes, he has been waiting to start for some time." - - - - - -CHAPTER III - - -When Michael Ivanovich returned to the study with the letter, the -old prince, with spectacles on and a shade over his eyes, was -sitting at his open bureau with screened candles, holding a paper in -his outstretched hand, and in a somewhat dramatic attitude was reading -his manuscript--his "Remarks" as he termed it--which was to be -transmitted to the Emperor after his death. - -When Michael Ivanovich went in there were tears in the prince's eyes -evoked by the memory of the time when the paper he was now reading had -been written. He took the letter from Michael Ivanovich's hand, put it -in his pocket, folded up his papers, and called in Alpatych who had -long been waiting. - -The prince had a list of things to be bought in Smolensk and, -walking up and down the room past Alpatych who stood by the door, he -gave his instructions. - -"First, notepaper--do you hear? Eight quires, like this sample, -gilt-edged... it must be exactly like the sample. Varnish, sealing -wax, as in Michael Ivanovich's list." - -He paced up and down for a while and glanced at his notes. - -"Then hand to the governor in person a letter about the deed." - -Next, bolts for the doors of the new building were wanted and had to -be of a special shape the prince had himself designed, and a leather -case had to be ordered to keep the "will" in. - -The instructions to Alpatych took over two hours and still the -prince did not let him go. He sat down, sank into thought, closed -his eyes, and dozed off. Alpatych made a slight movement. - -"Well, go, go! If anything more is wanted I'll send after you." - -Alpatych went out. The prince again went to his bureau, glanced into -it, fingered his papers, closed the bureau again, and sat down at -the table to write to the governor. - -It was already late when he rose after sealing the letter. He wished -to sleep, but he knew he would not be able to and that most depressing -thoughts came to him in bed. So he called Tikhon and went through -the rooms with him to show him where to set up the bed for that night. - -He went about looking at every corner. Every place seemed -unsatisfactory, but worst of all was his customary couch in the study. -That couch was dreadful to him, probably because of the oppressive -thoughts he had had when lying there. It was unsatisfactory -everywhere, but the corner behind the piano in the sitting room was -better than other places: he had never slept there yet. - -With the help of a footman Tikhon brought in the bedstead and -began putting it up. - -"That's not right! That's not right!" cried the prince, and -himself pushed it a few inches from the corner and then closer in -again. - -"Well, at last I've finished, now I'll rest," thought the prince, -and let Tikhon undress him. - -Frowning with vexation at the effort necessary to divest himself -of his coat and trousers, the prince undressed, sat down heavily on -the bed, and appeared to be meditating as he looked contemptuously -at his withered yellow legs. He was not meditating, but only deferring -the moment of making the effort to lift those legs up and turn over on -the bed. "Ugh, how hard it is! Oh, that this toil might end and you -would release me!" thought he. Pressing his lips together he made that -effort for the twenty-thousandth time and lay down. But hardly had -he done so before he felt the bed rocking backwards and forwards -beneath him as if it were breathing heavily and jolting. This happened -to him almost every night. He opened his eyes as they were closing. - -"No peace, damn them!" he muttered, angry he knew not with whom. "Ah -yes, there was something else important, very important, that I was -keeping till I should be in bed. The bolts? No, I told him about them. -No, it was something, something in the drawing room. Princess Mary -talked some nonsense. Dessalles, that fool, said something. -Something in my pocket--can't remember..." - -"Tikhon, what did we talk about at dinner?" - -"About Prince Michael..." - -"Be quiet, quiet!" The prince slapped his hand on the table. "Yes, I -know, Prince Andrew's letter! Princess Mary read it. Dessalles said -something about Vitebsk. Now I'll read it." - -He had the letter taken from his pocket and the table--on which -stood a glass of lemonade and a spiral wax candle--moved close to -the bed, and putting on his spectacles he began reading. Only now in -the stillness of the night, reading it by the faint light under the -green shade, did he grasp its meaning for a moment. - -"The French at Vitebsk, in four days' march they may be at Smolensk; -perhaps are already there! Tikhon!" Tikhon jumped up. "No, no, I don't -want anything!" he shouted. - -He put the letter under the candlestick and closed his eyes. And -there rose before him the Danube at bright noonday: reeds, the Russian -camp, and himself a young general without a wrinkle on his ruddy face, -vigorous and alert, entering Potemkin's gaily colored tent, and a -burning sense of jealousy of "the favorite" agitated him now as -strongly as it had done then. He recalled all the words spoken at that -first meeting with Potemkin. And he saw before him a plump, rather -sallow-faced, short, stout woman, the Empress Mother, with her smile -and her words at her first gracious reception of him, and then that -same face on the catafalque, and the encounter he had with Zubov -over her coffin about his right to kiss her hand. - -"Oh, quicker, quicker! To get back to that time and have done with -all the present! Quicker, quicker--and that they should leave me in -peace!" - - - - - -CHAPTER IV - - -Bald Hills, Prince Nicholas Bolkonski's estate, lay forty miles east -from Smolensk and two miles from the main road to Moscow. - -The same evening that the prince gave his instructions to -Alpatych, Dessalles, having asked to see Princess Mary, told her that, -as the prince was not very well and was taking no steps to secure -his safety, though from Prince Andrew's letter it was evident that -to remain at Bald Hills might be dangerous, he respectfully advised -her to send a letter by Alpatych to the Provincial Governor at -Smolensk, asking him to let her know the state of affairs and the -extent of the danger to which Bald Hills was exposed. Dessalles -wrote this letter to the Governor for Princess Mary, she signed it, -and it was given to Alpatych with instructions to hand it to the -Governor and to come back as quickly as possible if there was danger. - -Having received all his orders Alpatych, wearing a white beaver hat- -a present from the prince--and carrying a stick as the prince did, -went out accompanied by his family. Three well-fed roans stood ready -harnessed to a small conveyance with a leather hood. - -The larger bell was muffled and the little bells on the harness -stuffed with paper. The prince allowed no one at Bald Hills to drive -with ringing bells; but on a long journey Alpatych liked to have them. -His satellites--the senior clerk, a countinghouse clerk, a scullery -maid, a cook, two old women, a little pageboy, the coachman, and -various domestic serfs--were seeing him off. - -His daughter placed chintz-covered down cushions for him to sit on -and behind his back. His old sister-in-law popped in a small bundle, -and one of the coachmen helped him into the vehicle. - -"There! There! Women's fuss! Women, women!" said Alpatych, puffing -and speaking rapidly just as the prince did, and he climbed into the -trap. - -After giving the clerk orders about the work to be done, Alpatych, -not trying to imitate the prince now, lifted the hat from his bald -head and crossed himself three times. - -"If there is anything... come back, Yakov Alpatych! For Christ's -sake think of us!" cried his wife, referring to the rumors of war -and the enemy. - -"Women, women! Women's fuss!" muttered Alpatych to himself and -started on his journey, looking round at the fields of yellow rye -and the still-green, thickly growing oats, and at other quite black -fields just being plowed a second time. - -As he went along he looked with pleasure at the year's splendid crop -of corn, scrutinized the strips of ryefield which here and there -were already being reaped, made his calculations as to the sowing -and the harvest, and asked himself whether he had not forgotten any of -the prince's orders. - -Having baited the horses twice on the way, he arrived at the town -toward evening on the fourth of August. - -Alpatych kept meeting and overtaking baggage trains and troops on -the road. As he approached Smolensk he heard the sounds of distant -firing, but these did not impress him. What struck him most was the -sight of a splendid field of oats in which a camp had been pitched and -which was being mown down by the soldiers, evidently for fodder. -This fact impressed Alpatych, but in thinking about his own business -he soon forgot it. - -All the interests of his life for more than thirty years had been -bounded by the will of the prince, and he never went beyond that -limit. Everything not connected with the execution of the prince's -orders did not interest and did not even exist for Alpatych. - -On reaching Smolensk on the evening of the fourth of August he put -up in the Gachina suburb across the Dnieper, at the inn kept by -Ferapontov, where he had been in the habit of putting up for the -last thirty years. Some thirty years ago Ferapontov, by Alpatych's -advice, had bought a wood from the prince, had begun to trade, and now -had a house, an inn, and a corn dealer's shop in that province. He was -a stout, dark, red-faced peasant in the forties, with thick lips, a -broad knob of a nose, similar knobs over his black frowning brows, and -a round belly. - -Wearing a waistcoat over his cotton shirt, Ferapontov was standing -before his shop which opened onto the street. On seeing Alpatych he -went up to him. - -"You're welcome, Yakov Alpatych. Folks are leaving the town, but you -have come to it," said he. - -"Why are they leaving the town?" asked Alpatych. - -"That's what I say. Folks are foolish! Always afraid of the French." - -"Women's fuss, women's fuss!" said Alpatych. - -"Just what I think, Yakov Alpatych. What I say is: orders have -been given not to let them in, so that must be right. And the peasants -are asking three rubles for carting--it isn't Christian!" - -Yakov Alpatych heard without heeding. He asked for a samovar and for -hay for his horses, and when he had had his tea he went to bed. - -All night long troops were moving past the inn. Next morning -Alpatych donned a jacket he wore only in town and went out on -business. It was a sunny morning and by eight o'clock it was already -hot. "A good day for harvesting," thought Alpatych. - -From beyond the town firing had been heard since early morning. At -eight o'clock the booming of cannon was added to the sound of -musketry. Many people were hurrying through the streets and there were -many soldiers, but cabs were still driving about, tradesmen stood at -their shops, and service was being held in the churches as usual. -Alpatych went to the shops, to government offices, to the post office, -and to the Governor's. In the offices and shops and at the post office -everyone was talking about the army and about the enemy who was -already attacking the town, everybody was asking what should be -done, and all were trying to calm one another. - -In front of the Governor's house Alpatych found a large number of -people, Cossacks, and a traveling carriage of the Governor's. At the -porch he met two of the landed gentry, one of whom he knew. This -man, an ex-captain of police, was saying angrily: - -"It's no joke, you know! It's all very well if you're single. 'One -man though undone is but one,' as the proverb says, but with -thirteen in your family and all the property... They've brought us -to utter ruin! What sort of governors are they to do that? They -ought to be hanged--the brigands!..." - -"Oh come, that's enough!" said the other. - -"What do I care? Let him hear! We're not dogs," said the -ex-captain of police, and looking round he noticed Alpatych. - -"Oh, Yakov Alpatych! What have you come for?" - -"To see the Governor by his excellency's order," answered -Alpatych, lifting his head and proudly thrusting his hand into the -bosom of his coat as he always did when he mentioned the prince.... -"He has ordered me to inquire into the position of affairs," he added. - -"Yes, go and find out!" shouted the angry gentleman. "They've -brought things to such a pass that there are no carts or -anything!... There it is again, do you hear?" said he, pointing -in the direction whence came the sounds of firing. - -"They've brought us all to ruin... the brigands!" he repeated, and -descended the porch steps. - -Alpatych swayed his head and went upstairs. In the waiting room were -tradesmen, women, and officials, looking silently at one another. -The door of the Governor's room opened and they all rose and moved -forward. An official ran out, said some words to a merchant, called -a stout official with a cross hanging on his neck to follow him, and -vanished again, evidently wishing to avoid the inquiring looks and -questions addressed to him. Alpatych moved forward and next time the -official came out addressed him, one hand placed in the breast of -his buttoned coat, and handed him two letters. - -"To his Honor Baron Asch, from General-in-Chief Prince Bolkonski," -he announced with such solemnity and significance that the official -turned to him and took the letters. - -A few minutes later the Governor received Alpatych and hurriedly -said to him: - -"Inform the prince and princess that I knew nothing: I acted on -the highest instructions--here..." and he handed a paper to -Alpatych. "Still, as the prince is unwell my advice is that they -should go to Moscow. I am just starting myself. Inform them..." - -But the Governor did not finish: a dusty perspiring officer ran into -the room and began to say something in French. The Governor's face -expressed terror. - -"Go," he said, nodding his head to Alpatych, and began questioning -the officer. - -Eager, frightened, helpless glances were turned on Alpatych when -he came out of the Governor's room. Involuntarily listening now to the -firing, which had drawn nearer and was increasing in strength, -Alpatych hurried to his inn. The paper handed to him by the Governor -said this: - - -"I assure you that the town of Smolensk is not in the slightest -danger as yet and it is unlikely that it will be threatened with -any. I from the one side and Prince Bagration from the other are -marching to unite our forces before Smolensk, which junction will be -effected on the 22nd instant, and both armies with their united forces -will defend our compatriots of the province entrusted to your care -till our efforts shall have beaten back the enemies of our Fatherland, -or till the last warrior in our valiant ranks has perished. From -this you will see that you have a perfect right to reassure the -inhabitants of Smolensk, for those defended by two such brave armies -may feel assured of victory." (Instructions from Barclay de Tolly to -Baron Asch, the civil governor of Smolensk, 1812.) - - -People were anxiously roaming about the streets. - -Carts piled high with household utensils, chairs, and cupboards kept -emerging from the gates of the yards and moving along the streets. -Loaded carts stood at the house next to Ferapontov's and women were -wailing and lamenting as they said good-by. A small watchdog ran round -barking in front of the harnessed horses. - -Alpatych entered the innyard at a quicker pace than usual and went -straight to the shed where his horses and trap were. The coachman -was asleep. He woke him up, told him to harness, and went into the -passage. From the host's room came the sounds of a child crying, the -despairing sobs of a woman, and the hoarse angry shouting of -Ferapontov. The cook began running hither and thither in the passage -like a frightened hen, just as Alpatych entered. - -"He's done her to death. Killed the mistress!... Beat her... dragged -her about so!..." - -"What for?" asked Alpatych. - -"She kept begging to go away. She's a woman! 'Take me away,' says -she, 'don't let me perish with my little children! Folks,' she says, -'are all gone, so why,' she says, 'don't we go?' And he began -beating and pulling her about so!" - -At these words Alpatych nodded as if in approval, and not wishing to -hear more went to the door of the room opposite the innkeeper's, where -he had left his purchases. - -"You brute, you murderer!" screamed a thin, pale woman who, with a -baby in her arms and her kerchief torn from her head, burst through -the door at that moment and down the steps into the yard. - -Ferapontov came out after her, but on seeing Alpatych adjusted his -waistcoat, smoothed his hair, yawned, and followed Alpatych into the -opposite room. - -"Going already?" said he. - -Alpatych, without answering or looking at his host, sorted his -packages and asked how much he owed. - -"We'll reckon up! Well, have you been to the Governor's?" asked -Ferapontov. "What has been decided?" - -Alpatych replied that the Governor had not told him anything -definite. - -"With our business, how can we get away?" said Ferapontov. "We'd -have to pay seven rubles a cartload to Dorogobuzh and I tell them -they're not Christians to ask it! Selivanov, now, did a good stroke -last Thursday--sold flour to the army at nine rubles a sack. Will -you have some tea?" he added. - -While the horses were being harnessed Alpatych and Ferapontov over -their tea talked of the price of corn, the crops, and the good weather -for harvesting. - -"Well, it seems to be getting quieter," remarked Ferapontov, -finishing his third cup of tea and getting up. "Ours must have got the -best of it. The orders were not to let them in. So we're in force, -it seems.... They say the other day Matthew Ivanych Platov drove -them into the river Marina and drowned some eighteen thousand in one -day." - -Alpatych collected his parcels, handed them to the coachman who -had come in, and settled up with the innkeeper. The noise of wheels, -hoofs, and bells was heard from the gateway as a little trap passed -out. - -It was by now late in the afternoon. Half the street was in -shadow, the other half brightly lit by the sun. Alpatych looked out of -the window and went to the door. Suddenly the strange sound of a -far-off whistling and thud was heard, followed by a boom of cannon -blending into a dull roar that set the windows rattling. - -He went out into the street: two men were running past toward the -bridge. From different sides came whistling sounds and the thud of -cannon balls and bursting shells falling on the town. But these sounds -were hardly heard in comparison with the noise of the firing outside -the town and attracted little attention from the inhabitants. The town -was being bombarded by a hundred and thirty guns which Napoleon had -ordered up after four o'clock. The people did not at once realize -the meaning of this bombardment. - -At first the noise of the falling bombs and shells only aroused -curiosity. Ferapontov's wife, who till then had not ceased wailing -under the shed, became quiet and with the baby in her arms went to the -gate, listening to the sounds and looking in silence at the people. - -The cook and a shop assistant came to the gate. With lively -curiosity everyone tried to get a glimpse of the projectiles as they -flew over their heads. Several people came round the corner talking -eagerly. - -"What force!" remarked one. "Knocked the roof and ceiling all to -splinters!" - -"Routed up the earth like a pig," said another. - -"That's grand, it bucks one up!" laughed the first. "Lucky you -jumped aside, or it would have wiped you out!" - -Others joined those men and stopped and told how cannon balls had -fallen on a house close to them. Meanwhile still more projectiles, now -with the swift sinister whistle of a cannon ball, now with the -agreeable intermittent whistle of a shell, flew over people's heads -incessantly, but not one fell close by, they all flew over. Alpatych -was getting into his trap. The innkeeper stood at the gate. - -"What are you staring at?" he shouted to the cook, who in her red -skirt, with sleeves rolled up, swinging her bare elbows, had stepped -to the corner to listen to what was being said. - -"What marvels!" she exclaimed, but hearing her master's voice she -turned back, pulling down her tucked-up skirt. - -Once more something whistled, but this time quite close, swooping -downwards like a little bird; a flame flashed in the middle of the -street, something exploded, and the street was shrouded in smoke. - -"Scoundrel, what are you doing?" shouted the innkeeper, rushing to -the cook. - -At that moment the pitiful wailing of women was heard from different -sides, the frightened baby began to cry, and people crowded silently -with pale faces round the cook. The loudest sound in that crowd was -her wailing. - -"Oh-h-h! Dear souls, dear kind souls! Don't let me die! My good -souls!..." - -Five minutes later no one remained in the street. The cook, with her -thigh broken by a shell splinter, had been carried into the kitchen. -Alpatych, his coachman, Ferapontov's wife and children and the house -porter were all sitting in the cellar, listening. The roar of guns, -the whistling of projectiles, and the piteous moaning of the cook, -which rose above the other sounds, did not cease for a moment. The -mistress rocked and hushed her baby and when anyone came into the -cellar asked in a pathetic whisper what had become of her husband -who had remained in the street. A shopman who entered told her that -her husband had gone with others to the cathedral, whence they were -fetching the wonder-working icon of Smolensk. - -Toward dusk the cannonade began to subside. Alpatych left the cellar -and stopped in the doorway. The evening sky that had been so clear was -clouded with smoke, through which, high up, the sickle of the new moon -shone strangely. Now that the terrible din of the guns had ceased a -hush seemed to reign over the town, broken only by the rustle of -footsteps, the moaning, the distant cries, and the crackle of fires -which seemed widespread everywhere. The cook's moans had now subsided. -On two sides black curling clouds of smoke rose and spread from the -fires. Through the streets soldiers in various uniforms walked or -ran confusedly in different directions like ants from a ruined -ant-hill. Several of them ran into Ferapontov's yard before Alpatych's -eyes. Alpatych went out to the gate. A retreating regiment, -thronging and hurrying, blocked the street. - -Noticing him, an officer said: "The town is being abandoned. Get -away, get away!" and then, turning to the soldiers, shouted: - -"I'll teach you to run into the yards!" - -Alpatych went back to the house, called the coachman, and told him -to set off. Ferapontov's whole household came out too, following -Alpatych and the coachman. The women, who had been silent till then, -suddenly began to wail as they looked at the fires--the smoke and even -the flames of which could be seen in the failing twilight--and as if -in reply the same kind of lamentation was heard from other parts of -the street. Inside the shed Alpatych and the coachman arranged the -tangled reins and traces of their horses with trembling hands. - -As Alpatych was driving out of the gate he saw some ten soldiers -in Ferapontov's open shop, talking loudly and filling their bags and -knapsacks with flour and sunflower seeds. Just then Ferapontov -returned and entered his shop. On seeing the soldiers he was about -to shout at them, but suddenly stopped and, clutching at his hair, -burst into sobs and laughter: - -"Loot everything, lads! Don't let those devils get it!" he cried, -taking some bags of flour himself and throwing them into the street. - -Some of the soldiers were frightened and ran away, others went on -filling their bags. On seeing Alpatych, Ferapontov turned to him: - -"Russia is done for!" he cried. "Alpatych, I'll set the place on -fire myself. We're done for!..." and Ferapontov ran into the yard. - -Soldiers were passing in a constant stream along the street blocking -it completely, so that Alpatych could not pass out and had to wait. -Ferapontov's wife and children were also sitting in a cart waiting -till it was possible to drive out. - -Night had come. There were stars in the sky and the new moon shone -out amid the smoke that screened it. On the sloping descent to the -Dnieper Alpatych's cart and that of the innkeeper's wife, which were -slowly moving amid the rows of soldiers and of other vehicles, had -to stop. In a side street near the crossroads where the vehicles had -stopped, a house and some shops were on fire. This fire was already -burning itself out. The flames now died down and were lost in the -black smoke, now suddenly flared up again brightly, lighting up with -strange distinctness the faces of the people crowding at the -crossroads. Black figures flitted about before the fire, and through -the incessant crackling of the flames talking and shouting could be -heard. Seeing that his trap would not be able to move on for some -time, Alpatych got down and turned into the side street to look at the -fire. Soldiers were continually rushing backwards and forwards near -it, and he saw two of them and a man in a frieze coat dragging burning -beams into another yard across the street, while others carried -bundles of hay. - -Alpatych went up to a large crowd standing before a high barn -which was blazing briskly. The walls were all on fire and the back -wall had fallen in, the wooden roof was collapsing, and the rafters -were alight. The crowd was evidently watching for the roof to fall in, -and Alpatych watched for it too. - -"Alpatych!" a familiar voice suddenly hailed the old man. - -"Mercy on us! Your excellency!" answered Alpatych, immediately -recognizing the voice of his young prince. - -Prince Andrew in his riding cloak, mounted on a black horse, was -looking at Alpatych from the back of the crowd. - -"Why are you here?" he asked. - -"Your... your excellency," stammered Alpatych and broke into sobs. -"Are we really lost? Master!..." - -"Why are you here?" Prince Andrew repeated. - -At that moment the flames flared up and showed his young master's -pale worn face. Alpatych told how he had been sent there and how -difficult it was to get away. - -"Are we really quite lost, your excellency?" he asked again. - -Prince Andrew without replying took out a notebook and raising his -knee began writing in pencil on a page he tore out. He wrote to his -sister: - - -"Smolensk is being abandoned. Bald Hills will be occupied by the -enemy within a week. Set off immediately for Moscow. Let me know at -once when you will start. Send by special messenger to Usvyazh." - - -Having written this and given the paper to Alpatych, he told him how -to arrange for departure of the prince, the princess, his son, and the -boy's tutor, and how and where to let him know immediately. Before -he had had time to finish giving these instructions, a chief of -staff followed by a suite galloped up to him. - -"You are a colonel?" shouted the chief of staff with a German -accent, in a voice familiar to Prince Andrew. "Houses are set on -fire in your presence and you stand by! What does this mean? You -will answer for it!" shouted Berg, who was now assistant to the -chief of staff of the commander of the left flank of the infantry of -the first army, a place, as Berg said, "very agreeable and well en -evidence." - -Prince Andrew looked at him and without replying went on speaking to -Alpatych. - -"So tell them that I shall await a reply till the tenth, and if by -the tenth I don't receive news that they have all got away I shall -have to throw up everything and come myself to Bald Hills." - -"Prince," said Berg, recognizing Prince Andrew, "I only spoke -because I have to obey orders, because I always do obey exactly.... -You must please excuse me," he went on apologetically. - -Something cracked in the flames. The fire died down for a moment and -wreaths of black smoke rolled from under the roof. There was another -terrible crash and something huge collapsed. - -"Ou-rou-rou!" yelled the crowd, echoing the crash of the -collapsing roof of the barn, the burning grain in which diffused a -cakelike aroma all around. The flames flared up again, lighting the -animated, delighted, exhausted faces of the spectators. - -The man in the frieze coat raised his arms and shouted: - -"It's fine, lads! Now it's raging... It's fine!" - -"That's the owner himself," cried several voices. - -"Well then," continued Prince Andrew to Alpatych, "report to them as -I have told you"; and not replying a word to Berg who was now mute -beside him, he touched his horse and rode down the side street. - - - - - -CHAPTER V - - -From Smolensk the troops continued to retreat, followed by the -enemy. On the tenth of August the regiment Prince Andrew commanded was -marching along the highroad past the avenue leading to Bald Hills. -Heat and drought had continued for more than three weeks. Each day -fleecy clouds floated across the sky and occasionally veiled the -sun, but toward evening the sky cleared again and the sun set in -reddish-brown mist. Heavy night dews alone refreshed the earth. The -unreaped corn was scorched and shed its grain. The marshes dried up. -The cattle lowed from hunger, finding no food on the sun-parched -meadows. Only at night and in the forests while the dew lasted was -there any freshness. But on the road, the highroad along which the -troops marched, there was no such freshness even at night or when -the road passed through the forest; the dew was imperceptible on the -sandy dust churned up more than six inches deep. As soon as day dawned -the march began. The artillery and baggage wagons moved noiselessly -through the deep dust that rose to the very hubs of the wheels, and -the infantry sank ankle-deep in that soft, choking, hot dust that -never cooled even at night. Some of this dust was kneaded by the -feet and wheels, while the rest rose and hung like a cloud over the -troops, settling in eyes, ears, hair, and nostrils, and worst of all -in the lungs of the men and beasts as they moved along that road. -The higher the sun rose the higher rose that cloud of dust, and -through the screen of its hot fine particles one could look with naked -eye at the sun, which showed like a huge crimson ball in the unclouded -sky. There was no wind, and the men choked in that motionless -atmosphere. They marched with handkerchiefs tied over their noses -and mouths. When they passed through a village they all rushed to -the wells and fought for the water and drank it down to the mud. - -Prince Andrew was in command of a regiment, and the management of -that regiment, the welfare of the men and the necessity of receiving -and giving orders, engrossed him. The burning of Smolensk and its -abandonment made an epoch in his life. A novel feeling of anger -against the foe made him forget his own sorrow. He was entirely -devoted to the affairs of his regiment and was considerate and kind to -his men and officers. In the regiment they called him "our prince," -were proud of him and loved him. But he was kind and gentle only to -those of his regiment, to Timokhin and the like--people quite new to -him, belonging to a different world and who could not know and -understand his past. As soon as he came across a former acquaintance -or anyone from the staff, he bristled up immediately and grew -spiteful, ironical, and contemptuous. Everything that reminded him -of his past was repugnant to him, and so in his relations with that -former circle he confined himself to trying to do his duty and not -to be unfair. - -In truth everything presented itself in a dark and gloomy light to -Prince Andrew, especially after the abandonment of Smolensk on the -sixth of August (he considered that it could and should have been -defended) and after his sick father had had to flee to Moscow, -abandoning to pillage his dearly beloved Bald Hills which he had built -and peopled. But despite this, thanks to his regiment, Prince Andrew -had something to think about entirely apart from general questions. -Two days previously he had received news that his father, son, and -sister had left for Moscow; and though there was nothing for him to do -at Bald Hills, Prince Andrew with a characteristic desire to foment -his own grief decided that he must ride there. - -He ordered his horse to be saddled and, leaving his regiment on -the march, rode to his father's estate where he had been born and -spent his childhood. Riding past the pond where there used always to -be dozens of women chattering as they rinsed their linen or beat it -with wooden beetles, Prince Andrew noticed that there was not a soul -about and that the little washing wharf, torn from its place and -half submerged, was floating on its side in the middle of the pond. He -rode to the keeper's lodge. No one at the stone entrance gates of -the drive and the door stood open. Grass had already begun to grow -on the garden paths, and horses and calves were straying in the -English park. Prince Andrew rode up to the hothouse; some of the glass -panes were broken, and of the trees in tubs some were overturned and -others dried up. He called for Taras the gardener, but no one replied. -Having gone round the corner of the hothouse to the ornamental garden, -he saw that the carved garden fence was broken and branches of the -plum trees had been torn off with the fruit. An old peasant whom -Prince Andrew in his childhood had often seen at the gate was -sitting on a green garden seat, plaiting a bast shoe. - -He was deaf and did not hear Prince Andrew ride up. He was sitting -on the seat the old prince used to like to sit on, and beside him -strips of bast were hanging on the broken and withered branch of a -magnolia. - -Prince Andrew rode up to the house. Several limes in the old -garden had been cut down and a piebald mare and her foal were -wandering in front of the house among the rosebushes. The shutters -were all closed, except at one window which was open. A little serf -boy, seeing Prince Andrew, ran into the house. Alpatych, having sent -his family away, was alone at Bald Hills and was sitting indoors -reading the Lives of the Saints. On hearing that Prince Andrew had -come, he went out with his spectacles on his nose, buttoning his coat, -and, hastily stepping up, without a word began weeping and kissing -Prince Andrew's knee. - -Then, vexed at his own weakness, he turned away and began to -report on the position of affairs. Everything precious and valuable -had been removed to Bogucharovo. Seventy quarters of grain had also -been carted away. The hay and the spring corn, of which Alpatych -said there had been a remarkable crop that year, had been commandeered -by the troops and mown down while still green. The peasants were -ruined; some of them too had gone to Bogucharovo, only a few remained. - -Without waiting to hear him out, Prince Andrew asked: - -"When did my father and sister leave?" meaning when did they leave -for Moscow. - -Alpatych, understanding the question to refer to their departure for -Bogucharovo, replied that they had left on the seventh and again -went into details concerning the estate management, asking for -instructions. - -"Am I to let the troops have the oats, and to take a receipt for -them? We have still six hundred quarters left," he inquired. - -"What am I to say to him?" thought Prince Andrew, looking down on -the old man's bald head shining in the sun and seeing by the -expression on his face that the old man himself understood how -untimely such questions were and only asked them to allay his grief. - -"Yes, let them have it," replied Prince Andrew. - -"If you noticed some disorder in the garden," said Alpatych, "it was -impossible to prevent it. Three regiments have been here and spent the -night, dragoons mostly. I took down the name and rank of their -commanding officer, to hand in a complaint about it." - -"Well, and what are you going to do? Will you stay here if the enemy -occupies the place?" asked Prince Andrew. - -Alpatych turned his face to Prince Andrew, looked at him, and -suddenly with a solemn gesture raised his arm. - -"He is my refuge! His will be done!" he exclaimed. - -A group of bareheaded peasants was approaching across the meadow -toward the prince. - -"Well, good-by!" said Prince Andrew, bending over to Alpatych. -"You must go away too, take away what you can and tell the serfs to go -to the Ryazan estate or to the one near Moscow." - -Alpatych clung to Prince Andrew's leg and burst into sobs. Gently -disengaging himself, the prince spurred his horse and rode down the -avenue at a gallop. - -The old man was still sitting in the ornamental garden, like a fly -impassive on the face of a loved one who is dead, tapping the last -on which he was making the bast shoe, and two little girls, running -out from the hot house carrying in their skirts plums they had plucked -from the trees there, came upon Prince Andrew. On seeing the young -master, the elder one frightened look clutched her younger companion -by the hand and hid with her behind a birch tree, not stopping to pick -up some green plums they had dropped. - -Prince Andrew turned away with startled haste, unwilling to let them -see that they had been observed. He was sorry for the pretty -frightened little girl, was afraid of looking at her, and yet felt -an irresistible desire to do so. A new sensation of comfort and relief -came over him when, seeing these girls, he realized the existence of -other human interests entirely aloof from his own and just as -legitimate as those that occupied him. Evidently these girls -passionately desired one thing--to carry away and eat those green -plums without being caught--and Prince Andrew shared their wish for -the success of their enterprise. He could not resist looking at them -once more. Believing their danger past, they sprang from their -ambush and, chirruping something in their shrill little voices and -holding up their skirts, their bare little sunburned feet scampered -merrily and quickly across the meadow grass. - -Prince Andrew was somewhat refreshed by having ridden off the -dusty highroad along which the troops were moving. But not far from -Bald Hills he again came out on the road and overtook his regiment -at its halting place by the dam of a small pond. It was past one -o'clock. The sun, a red ball through the dust, burned and scorched his -back intolerably through his black coat. The dust always hung -motionless above the buzz of talk that came from the resting troops. -There was no wind. As he crossed the dam Prince Andrew smelled the -ooze and freshness of the pond. He longed to get into that water, -however dirty it might be, and he glanced round at the pool from -whence came sounds of shrieks and laughter. The small, muddy, green -pond had risen visibly more than a foot, flooding the dam, because -it was full of the naked white bodies of soldiers with brick-red -hands, necks, and faces, who were splashing about in it. All this -naked white human flesh, laughing and shrieking, floundered about in -that dirty pool like carp stuffed into a watering can, and the -suggestion of merriment in that floundering mass rendered it specially -pathetic. - -One fair-haired young soldier of the third company, whom Prince -Andrew knew and who had a strap round the calf of one leg, crossed -himself, stepped back to get a good run, and plunged into the water; -another, a dark noncommissioned officer who was always shaggy, stood -up to his waist in the water joyfully wriggling his muscular figure -and snorted with satisfaction as he poured the water over his head -with hands blackened to the wrists. There were sounds of men -slapping one another, yelling, and puffing. - -Everywhere on the bank, on the dam, and in the pond, there was -healthy, white, muscular flesh. The officer, Timokhin, with his red -little nose, standing on the dam wiping himself with a towel, felt -confused at seeing the prince, but made up his mind to address him -nevertheless. - -"It's very nice, your excellency! Wouldn't you like to?" said he. - -"It's dirty," replied Prince Andrew, making a grimace. - -"We'll clear it out for you in a minute," said Timokhin, and, -still undressed, ran off to clear the men out of the pond. - -"The prince wants to bathe." - -"What prince? Ours?" said many voices, and the men were in such -haste to clear out that the prince could hardly stop them. He -decided that he would rather wash himself with water in the barn. - -"Flesh, bodies, cannon fodder!" he thought, and he looked at his own -naked body and shuddered, not from cold but from a sense of disgust -and horror he did not himself understand, aroused by the sight of that -immense number of bodies splashing about in the dirty pond. - - -On the seventh of August Prince Bagration wrote as follows from -his quarters at Mikhaylovna on the Smolensk road: - - -Dear Count Alexis Andreevich--(He was writing to Arakcheev but -knew that his letter would be read by the Emperor, and therefore -weighed every word in it to the best of his ability.) - -I expect the Minister [Barclay de Tolly] has already reported the -abandonment of Smolensk to the enemy. It is pitiable and sad, and -the whole army is in despair that this most important place has been -wantonly abandoned. I, for my part, begged him personally most -urgently and finally wrote him, but nothing would induce him to -consent. I swear to you on my honor that Napoleon was in such a fix as -never before and might have lost half his army but could not have -taken Smolensk. Our troops fought, and are fighting, as never -before. With fifteen thousand men I held the enemy at bay for -thirty-five hours and beat him; but he would not hold out even for -fourteen hours. It is disgraceful, a stain on our army, and as for -him, he ought, it seems to me, not to live. If he reports that our -losses were great, it is not true; perhaps about four thousand, not -more, and not even that; but even were they ten thousand, that's -war! But the enemy has lost masses... - -What would it have cost him to hold out for another two days? They -would have had to retire of their own accord, for they had no water -for men or horses. He gave me his word he would not retreat, but -suddenly sent instructions that he was retiring that night. We -cannot fight in this way, or we may soon bring the enemy to Moscow... - -There is a rumor that you are thinking of peace. God forbid that you -should make peace after all our sacrifices and such insane retreats! -You would set all Russia against you and every one of us would feel -ashamed to wear the uniform. If it has come to this--we must fight -as long as Russia can and as long as there are men able to stand... - -One man ought to be in command, and not two. Your Minister may -perhaps be good as a Minister, but as a general he is not merely bad -but execrable, yet to him is entrusted the fate of our whole -country.... I am really frantic with vexation; forgive my writing -boldly. It is clear that the man who advocates the conclusion of a -peace, and that the Minister should command the army, does not love -our sovereign and desires the ruin of us all. So I write you -frankly: call out the militia. For the Minister is leading these -visitors after him to Moscow in a most masterly way. The whole army -feels great suspicion of the Imperial aide-de-camp Wolzogen. He is -said to be more Napoleon's man than ours, and he is always advising -the Minister. I am not merely civil to him but obey him like a -corporal, though I am his senior. This is painful, but, loving my -benefactor and sovereign, I submit. Only I am sorry for the Emperor -that he entrusts our fine army to such as he. Consider that on our -retreat we have lost by fatigue and left in the hospital more than -fifteen thousand men, and had we attacked this would not have -happened. Tell me, for God's sake, what will Russia, our mother -Russia, say to our being so frightened, and why are we abandoning -our good and gallant Fatherland to such rabble and implanting feelings -of hatred and shame in all our subjects? What are we scared at and -of whom are we afraid? I am not to blame that the Minister is -vacillating, a coward, dense, dilatory, and has all bad qualities. The -whole army bewails it and calls down curses upon him... - - - - - -CHAPTER VI - - -Among the innumerable categories applicable to the phenomena of -human life one may discriminate between those in which substance -prevails and those in which form prevails. To the latter--as -distinguished from village, country, provincial, or even Moscow -life--we may allot Petersburg life, and especially the life of its -salons. That life of the salons is unchanging. Since the year 1805 -we had made peace and had again quarreled with Bonaparte and had -made constitutions and unmade them again, but the salons of Anna -Pavlovna Helene remained just as they had been--the one seven and -the other five years before. At Anna Pavlovna's they talked with -perplexity of Bonaparte's successes just as before and saw in them and -in the subservience shown to him by the European sovereigns a -malicious conspiracy, the sole object of which was to cause -unpleasantness and anxiety to the court circle of which Anna -Pavlovna was the representative. And in Helene's salon, which -Rumyantsev himself honored with his visits, regarding Helene as a -remarkably intelligent woman, they talked with the same ecstasy in -1812 as in 1808 of the "great nation" and the "great man," and -regretted our rupture with France, a rupture which, according to them, -ought to be promptly terminated by peace. - -Of late, since the Emperor's return from the army, there had been -some excitement in these conflicting salon circles and some -demonstrations of hostility to one another, but each camp retained its -own tendency. In Anna Pavlovna's circle only those Frenchmen were -admitted who were deep-rooted legitimists, and patriotic views were -expressed to the effect that one ought not to go to the French theater -and that to maintain the French troupe was costing the government as -much as a whole army corps. The progress of the war was eagerly -followed, and only the reports most flattering to our army were -circulated. In the French circle of Helene and Rumyantsev the -reports of the cruelty of the enemy and of the war were contradicted -and all Napoleon's attempts at conciliation were discussed. In that -circle they discountenanced those who advised hurried preparations for -a removal to Kazan of the court and the girls' educational -establishments under the patronage of the Dowager Empress. In Helene's -circle the war in general was regarded as a series of formal -demonstrations which would very soon end in peace, and the view -prevailed expressed by Bilibin--who now in Petersburg was quite at -home in Helene's house, which every clever man was obliged to visit- -that not by gunpowder but by those who invented it would matters be -settled. In that circle the Moscow enthusiasm--news of which had -reached Petersburg simultaneously with the Emperor's return--was -ridiculed sarcastically and very cleverly, though with much caution. - -Anna Pavlovna's circle on the contrary was enraptured by this -enthusiasm and spoke of it as Plutarch speaks of the deeds of the -ancients. Prince Vasili, who still occupied his former important -posts, formed a connecting link between these two circles. He -visited his "good friend Anna Pavlovna" as well as his daughter's -"diplomatic salon," and often in his constant comings and goings -between the two camps became confused and said at Helene's what he -should have said at Anna Pavlovna's and vice versa. - -Soon after the Emperor's return Prince Vasili in a conversation -about the war at Anna Pavlovna's severely condemned Barclay de -Tolly, but was undecided as to who ought to be appointed commander -in chief. One of the visitors, usually spoken of as "a man of great -merit," having described how he had that day seen Kutuzov, the newly -chosen chief of the Petersburg militia, presiding over the -enrollment of recruits at the Treasury, cautiously ventured to suggest -that Kutuzov would be the man to satisfy all requirements. - -Anna Pavlovna remarked with a melancholy smile that Kutuzov had done -nothing but cause the Emperor annoyance. - -"I have talked and talked at the Assembly of the Nobility," Prince -Vasili interrupted, "but they did not listen to me. I told them his -election as chief of the militia would not please the Emperor. They -did not listen to me. - -"It's all this mania for opposition," he went on. "And who for? It -is all because we want to ape the foolish enthusiasm of those -Muscovites," Prince Vasili continued, forgetting for a moment that -though at Helene's one had to ridicule the Moscow enthusiasm, at -Anna Pavlovna's one had to be ecstatic about it. But he retrieved -his mistake at once. "Now, is it suitable that Count Kutuzov, the -oldest general in Russia, should preside at that tribunal? He will get -nothing for his pains! How could they make a man commander in chief -who cannot mount a horse, who drops asleep at a council, and has the -very worst morals! A good reputation he made for himself at Bucharest! -I don't speak of his capacity as a general, but at a time like this -how they appoint a decrepit, blind old man, positively -blind? A fine idea to have a blind general! He can't see anything. -To play blindman's bluff? He can't see at all!" - -No one replied to his remarks. - -This was quite correct on the twenty-fourth of July. But on the -twenty-ninth of July Kutuzov received the title of Prince. This -might indicate a wish to get rid of him, and therefore Prince Vasili's -opinion continued to be correct though he was not now in any hurry -to express it. But on the eighth of August a committee, consisting -of Field Marshal Saltykov, Arakcheev, Vyazmitinov, Lopukhin, and -Kochubey met to consider the progress of the war. This committee -came to the conclusion that our failures were due to a want of unity -in the command and though the members of the committee were aware of -the Emperor's dislike of Kutuzov, after a short deliberation they -agreed to advise his appointment as commander in chief. That same -day Kutuzov was appointed commander in chief with full powers over the -armies and over the whole region occupied by them. - -On the ninth of August Prince Vasili at Anna Pavlovna's again met -the "man of great merit." The latter was very attentive to Anna -Pavlovna because he wanted to be appointed director of one of the -educational establishments for young ladies. Prince Vasili entered the -room with the air of a happy conqueror who has attained the object -of his desires. - -"Well, have you heard the great news? Prince Kutuzov is field -marshal! All dissensions are at an end! I am so glad, so delighted! At -last we have a man!" said he, glancing sternly and significantly round -at everyone in the drawing room. - -The "man of great merit," despite his desire to obtain the post of -director, could not refrain from reminding Prince Vasili of his former -opinion. Though this was impolite to Prince Vasili in Anna -Pavlovna's drawing room, and also to Anna Pavlovna herself who had -received the news with delight, he could not resist the temptation. - -"But, Prince, they say he is blind!" said he, reminding Prince -Vasili of his own words. - -"Eh? Nonsense! He sees well enough," said Prince Vasili rapidly, -in a deep voice and with a slight cough--the voice and cough with -which he was wont to dispose of all difficulties. - -"He sees well enough," he added. "And what I am so pleased about," -he went on, "is that our sovereign has given him full powers over -all the armies and the whole region--powers no commander in chief ever -had before. He is a second autocrat," he concluded with a victorious -smile. - -"God grant it! God grant it!" said Anna Pavlovna. - -The "man of great merit," who was still a novice in court circles, -wishing to flatter Anna Pavlovna by defending her former position on -this question, observed: - -"It is said that the Emperor was reluctant to give Kutuzov those -powers. They say he blushed like a girl to whom Joconde is read, -when he said to Kutuzov: 'Your Emperor and the Fatherland award you -this honor.'" - -"Perhaps the heart took no part in that speech," said Anna Pavlovna. - -"Oh, no, no!" warmly rejoined Prince Vasili, who would not now yield -Kutuzov to anyone; in his opinion Kutuzov was not only admirable -himself, but was adored by everybody. "No, that's impossible," said -he, "for our sovereign appreciated him so highly before." - -"God grant only that Prince Kutuzov assumes real power and does -not allow anyone to put a spoke in his wheel," observed Anna Pavlovna. - -Understanding at once to whom she alluded, Prince Vasili said in a -whisper: - -"I know for a fact that Kutuzov made it an absolute condition that -the Tsarevich should not be with the army. Do you know what he said to -the Emperor?" - -And Prince Vasili repeated the words supposed to have been spoken by -Kutuzov to the Emperor. "I can neither punish him if he does wrong nor -reward him if he does right." - -"Oh, a very wise man is Prince Kutuzov! I have known him a long -time!" - -"They even say," remarked the "man of great merit" who did not yet -possess courtly tact, "that his excellency made it an express -condition that the sovereign himself should not be with the army." - -As soon as he said this both Prince Vasili and Anna Pavlovna -turned away from him and glanced sadly at one another with a sigh at -his naivete. - - - - - -CHAPTER VII - - -While this was taking place in Petersburg the French had already -passed Smolensk and were drawing nearer and nearer to Moscow. -Napoleon's historian Thiers, like other of his historians, trying to -justify his hero says that he was drawn to the walls of Moscow against -his will. He is as right as other historians who look for the -explanation of historic events in the will of one man; he is as -right as the Russian historians who maintain that Napoleon was drawn -to Moscow by the skill of the Russian commanders. Here besides the law -of retrospection, which regards all the past as a preparation for -events that subsequently occur, the law of reciprocity comes in, -confusing the whole matter. A good chessplayer having lost a game is -sincerely convinced that his loss resulted from a mistake he made -and looks for that mistake in the opening, but forgets that at each -stage of the game there were similar mistakes and that none of his -moves were perfect. He only notices the mistake to which he pays -attention, because his opponent took advantage of it. How much more -complex than this is the game of war, which occurs under certain -limits of time, and where it is not one will that manipulates lifeless -objects, but everything results from innumerable conflicts of -various wills! - -After Smolensk Napoleon sought a battle beyond Dorogobuzh at Vyazma, -and then at Tsarevo-Zaymishche, but it happened that owing to a -conjunction of innumerable circumstances the Russians could not give -battle till they reached Borodino, seventy miles from Moscow. From -Vyazma Napoleon ordered a direct advance on Moscow. - -Moscou, la capitale asiatique de ce grand empire, la ville sacree -des peuples d'Alexandre, Moscou avec ses innombrables eglises en forme -de pagodes chinoises,* this Moscow gave Napoleon's imagination no -rest. On the march from Vyazma to Tsarevo-Zaymishche he rode his light -bay bobtailed ambler accompanied by his Guards, his bodyguard, his -pages, and aides-de-camp. Berthier, his chief of staff, dropped behind -to question a Russian prisoner captured by the cavalry. Followed by -Lelorgne d'Ideville, an interpreter, he overtook Napoleon at a -gallop and reined in his horse with an amused expression. - - -*"Moscow, the Asiatic capital of this great empire, the sacred -city of Alexander's people, Moscow with its innumerable churches -shaped like Chinese pagodas." - - -"Well?" asked Napoleon. - -"One of Platov's Cossacks says that Platov's corps is joining up -with the main army and that Kutuzov has been appointed commander in -chief. He is a very shrewd and garrulous fellow." - -Napoleon smiled and told them to give the Cossack a horse and -bring the man to him. He wished to talk to him himself. Several -adjutants galloped off, and an hour later, Lavrushka, the serf Denisov -had handed over to Rostov, rode up to Napoleon in an orderly's -jacket and on a French cavalry saddle, with a merry, and tipsy face. -Napoleon told him to ride by his side and began questioning him. - -"You are a Cossack?" - -"Yes, a Cossack, your Honor." - -"The Cossack, not knowing in what company he was, for Napoleon's -plain appearance had nothing about it that would reveal to an Oriental -mind the presence of a monarch, talked with extreme familiarity of the -incidents of the war," says Thiers, narrating this episode. In reality -Lavrushka, having got drunk the day before and left his master -dinnerless, had been whipped and sent to the village in quest of -chickens, where he engaged in looting till the French took him -prisoner. Lavrushka was one of those coarse, bare-faced lackeys who -have seen all sorts of things, consider it necessary to do -everything in a mean and cunning way, are ready to render any sort -of service to their master, and are keen at guessing their master's -baser impulses, especially those prompted by vanity and pettiness. - -Finding himself in the company of Napoleon, whose identity he had -easily and surely recognized, Lavrushka was not in the least abashed -but merely did his utmost to gain his new master's favor. - -He knew very well that this was Napoleon, but Napoleon's presence -could no more intimidate him than Rostov's, or a sergeant major's with -the rods, would have done, for he had nothing that either the sergeant -major or Napoleon could deprive him of. - -So he rattled on, telling all the gossip he had heard among the -orderlies. Much of it true. But when Napoleon asked him whether the -Russians thought they would beat Bonaparte or not, Lavrushka screwed -up his eyes and considered. - -In this question he saw subtle cunning, as men of his type see -cunning in everything, so he frowned and did not answer immediately. - -"It's like this," he said thoughtfully, "if there's a battle soon, -yours will win. That's right. But if three days pass, then after that, -well, then that same battle will not soon be over." - -Lelorgne d'Ideville smilingly interpreted this speech to Napoleon -thus: "If a battle takes place within the next three days the French -will win, but if later, God knows what will happen." Napoleon did -not smile, though he was evidently in high good humor, and he -ordered these words to be repeated. - -Lavrushka noticed this and to entertain him further, pretending -not to know who Napoleon was, added: - -"We know that you have Bonaparte and that he has beaten everybody in -the world, but we are a different matter..."--without knowing why or -how this bit of boastful patriotism slipped out at the end. - -The interpreter translated these words without the last phrase, -and Bonaparte smiled. "The young Cossack made his mighty -interlocutor smile," says Thiers. After riding a few paces in silence, -Napoleon turned to Berthier and said he wished to see how the news -that he was talking to the Emperor himself, to that very Emperor who -had written his immortally victorious name on the Pyramids, would -affect this enfant du Don.* - - -*"Child of the Don." - - -The fact was accordingly conveyed to Lavrushka. - -Lavrushka, understanding that this was done to perplex him and -that Napoleon expected him to be frightened, to gratify his new -masters promptly pretended to be astonished and awe-struck, opened his -eyes wide, and assumed the expression he usually put on when taken -to be whipped. "As soon as Napoleon's interpreter had spoken," says -Thiers, "the Cossack, seized by amazement, did not utter another word, -but rode on, his eyes fixed on the conqueror whose fame had reached -him across the steppes of the East. All his loquacity was suddenly -arrested and replaced by a naive and silent feeling of admiration. -Napoleon, after making the Cossack a present, had him set free like -a bird restored to its native fields." - -Napoleon rode on, dreaming of the Moscow that so appealed to his -imagination, and "the bird restored to its native fields" galloped -to our outposts, inventing on the way all that had not taken place but -that he meant to relate to his comrades. What had really taken place -he did not wish to relate because it seemed to him not worth -telling. He found the Cossacks, inquired for the regiment operating -with Platov's detachment and by evening found his master, Nicholas -Rostov, quartered at Yankovo. Rostov was just mounting to go for a -ride round the neighboring villages with Ilyin; he let Lavrushka -have another horse and took him along with him. - - - - - -CHAPTER VIII - - -Princess Mary was not in Moscow and out of danger as Prince Andrew -supposed. - -After the return of Alpatych from Smolensk the old prince suddenly -seemed to awake as from a dream. He ordered the militiamen to be -called up from the villages and armed, and wrote a letter to the -commander in chief informing him that he had resolved to remain at -Bald Hills to the last extremity and to defend it, leaving to the -commander in chief's discretion to take measures or not for the -defense of Bald Hills, where one of Russia's oldest generals would -be captured or killed, and he announced to his household that he would -remain at Bald Hills. - -But while himself remaining, he gave instructions for the -departure of the princess and Dessalles with the little prince to -Bogucharovo and thence to Moscow. Princess Mary, alarmed by her -father's feverish and sleepless activity after his previous apathy, -could not bring herself to leave him alone and for the first time in -her life ventured to disobey him. She refused to go away and her -father's fury broke over her in a terrible storm. He repeated every -injustice he had ever inflicted on her. Trying to convict her, he told -her she had worn him out, had caused his quarrel with his son, had -harbored nasty suspicions of him, making it the object of her life -to poison his existence, and he drove her from his study telling her -that if she did not go away it was all the same to him. He declared -that he did not wish to remember her existence and warned her not to -dare to let him see her. The fact that he did not, as she had -feared, order her to be carried away by force but only told her not to -let him see her cheered Princess Mary. She knew it was a proof that in -the depth of his soul he was glad she was remaining at home and had -not gone away. - -The morning after little Nicholas had left, the old prince donned -his full uniform and prepared to visit the commander in chief. His -caleche was already at the door. Princess Mary saw him walk out of the -house in his uniform wearing all his orders and go down the garden -to review his armed peasants and domestic serfs. She sat by the window -listening to his voice which reached her from the garden. Suddenly -several men came running up the avenue with frightened faces. - -Princess Mary ran out to the porch, down the flower-bordered path, -and into the avenue. A large crowd of militiamen and domestics were -moving toward her, and in their midst several men were supporting by -the armpits and dragging along a little old man in a uniform and -decorations. She ran up to him and, in the play of the sunlight that -fell in small round spots through the shade of the lime-tree avenue, -could not be sure what change there was in his face. All she could see -was that his former stern and determined expression had altered to one -of timidity and submission. On seeing his daughter he moved his -helpless lips and made a hoarse sound. It was impossible to make out -what he wanted. He was lifted up, carried to his study, and laid on -the very couch he had so feared of late. - -The doctor, who was fetched that same night, bled him and said -that the prince had had a seizure paralyzing his right side. - -It was becoming more and more dangerous to remain at Bald Hills, and -next day they moved the prince to Bogucharovo, the doctor accompanying -him. - -By the time they reached Bogucharovo, Dessalles and the little -prince had already left for Moscow. - -For three weeks the old prince lay stricken by paralysis in the -new house Prince Andrew had built at Bogucharovo, ever in the same -state, getting neither better nor worse. He was unconscious and lay -like a distorted corpse. He muttered unceasingly, his eyebrows and -lips twitching, and it was impossible to tell whether he understood -what was going on around him or not. One thing was certain--that he -was suffering and wished to say something. But what it was, no one -could tell: it might be some caprice of a sick and half-crazy man, -or it might relate to public affairs, or possibly to family concerns. - -The doctor said this restlessness did not mean anything and was -due to physical causes; but Princess Mary thought he wished to tell -her something, and the fact that her presence always increased his -restlessness confirmed her opinion. - -He was evidently suffering both physically and mentally. There was -no hope of recovery. It was impossible for him to travel, it would not -do to let him die on the road. "Would it not be better if the end -did come, the very end?" Princess Mary sometimes thought. Night and -day, hardly sleeping at all, she watched him and, terrible to say, -often watched him not with hope of finding signs of improvement but -wishing to find symptoms of the approach of the end. - -Strange as it was to her to acknowledge this feeling in herself, yet -there it was. And what seemed still more terrible to her was that -since her father's illness began (perhaps even sooner, when she stayed -with him expecting something to happen), all the personal desires -and hopes that had been forgotten or sleeping within her had awakened. -Thoughts that had not entered her mind for years--thoughts of a life -free from the fear of her father, and even the possibility of love and -of family happiness--floated continually in her imagination like -temptations of the devil. Thrust them aside as she would, questions -continually recurred to her as to how she would order her life now, -after that. These were temptations of the devil and Princess Mary knew -it. She knew that the sole weapon against him was prayer, and she -tried to pray. She assumed an attitude of prayer, looked at the icons, -repeated the words of a prayer, but she could not pray. She felt -that a different world had now taken possession of her--the life of -a world of strenuous and free activity, quite opposed to the spiritual -world in which till now she had been confined and in which her -greatest comfort had been prayer. She could not pray, could not -weep, and worldly cares took possession of her. - -It was becoming dangerous to remain in Bogucharovo. News of the -approach of the French came from all sides, and in one village, ten -miles from Bogucharovo, a homestead had been looted by French -marauders. - -The doctor insisted on the necessity of moving the prince; the -provincial Marshal of the Nobility sent an official to Princess Mary -to persuade her to get away as quickly as possible, and the head of -the rural police having come to Bogucharovo urged the same thing, -saying that the French were only some twenty-five miles away, that -French proclamations were circulating in the villages, and that if the -princess did not take her father away before the fifteenth, he could -not answer for the consequences. - -The princess decided to leave on the fifteenth. The cares of -preparation and giving orders, for which everyone came to her, -occupied her all day. She spent the night of the fourteenth as -usual, without undressing, in the room next to the one where the -prince lay. Several times, waking up, she heard his groans and -muttering, the creak of his bed, and the steps of Tikhon and the -doctor when they turned him over. Several times she listened at the -door, and it seemed to her that his mutterings were louder than -usual and that they turned him over oftener. She could not sleep and -several times went to the door and listened, wishing to enter but -not deciding to do so. Though he did not speak, Princess Mary saw -and knew how unpleasant every sign of anxiety on his account was to -him. She had noticed with what dissatisfaction he turned from the look -she sometimes involuntarily fixed on him. She knew that her going in -during the night at an unusual hour would irritate him. - -But never had she felt so grieved for him or so much afraid of -losing him. She recalled all her life with him and in every word and -act of his found an expression of his love of her. Occasionally amid -these memories temptations of the devil would surge into her -imagination: thoughts of how things would be after his death, and -how her new, liberated life would be ordered. But she drove these -thoughts away with disgust. Toward morning he became quiet and she -fell asleep. - -She woke late. That sincerity which often comes with waking showed -her clearly what chiefly concerned her about her father's illness. -On waking she listened to what was going on behind the door and, -hearing him groan, said to herself with a sigh that things were -still the same. - -"But what could have happened? What did I want? I want his death!" -she cried with a feeling of loathing for herself. - -She washed, dressed, said her prayers, and went out to the porch. In -front of it stood carriages without horses and things were being -packed into the vehicles. - -It was a warm, gray morning. Princess Mary stopped at the porch, -still horrified by her spiritual baseness and trying to arrange her -thoughts before going to her father. The doctor came downstairs and -went out to her. - -"He is a little better today," said he. "I was looking for you. -One can make out something of what he is saying. His head is -clearer. Come in, he is asking for you..." - -Princess Mary's heart beat so violently at this news that she grew -pale and leaned against the wall to keep from falling. To see him, -talk to him, feel his eyes on her now that her whole soul was -overflowing with those dreadful, wicked temptations, was a torment -of joy and terror. - -"Come," said the doctor. - -Princess Mary entered her father's room and went up to his bed. He -was lying on his back propped up high, and his small bony hands with -their knotted purple veins were lying on the quilt; his left eye gazed -straight before him, his right eye was awry, and his brows and lips -motionless. He seemed altogether so thin, small, and pathetic. His -face seemed to have shriveled or melted; his features had grown -smaller. Princess Mary went up and kissed his hand. His left hand -pressed hers so that she understood that he had long been waiting -for her to come. He twitched her hand, and his brows and lips quivered -angrily. - -She looked at him in dismay trying to guess what he wanted of her. -When she changed her position so that his left eye could see her -face he calmed down, not taking his eyes off her for some seconds. -Then his lips and tongue moved, sounds came, and he began to speak, -gazing timidly and imploringly at her, evidently afraid that she might -not understand. - -Straining all her faculties Princess Mary looked at him. The comic -efforts with which he moved his tongue made her drop her eyes and with -difficulty repress the sobs that rose to her throat. He said -something, repeating the same words several times. She could not -understand them, but tried to guess what he was saying and inquiringly -repeated the words he uttered. - -"Mmm...ar...ate...ate..." he repeated several times. - -It was quite impossible to understand these sounds. The doctor -thought he had guessed them, and inquiringly repeated: "Mary, are -you afraid?" The prince shook his head, again repeated the same -sounds. - -"My mind, my mind aches?" questioned Princess Mary. - -He made a mumbling sound in confirmation of this, took her hand, and -began pressing it to different parts of his breast as if trying to -find the right place for it. - -"Always thoughts... about you... thoughts..." he then uttered much -more clearly than he had done before, now that he was sure of being -understood. - -Princess Mary pressed her head against his hand, trying to hide -her sobs and tears. - -He moved his hand over her hair. - -"I have been calling you all night..." he brought out. - -"If only I had known..." she said through her tears. "I was afraid -to come in." - -He pressed her hand. - -"Weren't you asleep?" - -"No, I did not sleep," said Princess Mary, shaking her head. - -Unconsciously imitating her father, she now tried to express herself -as he did, as much as possible by signs, and her tongue too seemed -to move with difficulty. - -"Dear one... Dearest..." Princess Mary could not quite make out what -he had said, but from his look it was clear that he had uttered a -tender caressing word such as he had never used to her before. "Why -didn't you come in?" - -"And I was wishing for his death!" thought Princess Mary. - -He was silent awhile. - -"Thank you... daughter dear!... for all, for all... forgive!... -thank you!... forgive!... thank you!..." and tears began to flow -from his eyes. "Call Andrew!" he said suddenly, and a childish, -timid expression of doubt showed itself on his face as he spoke. - -He himself seemed aware that his demand was meaningless. So at least -it seemed to Princess Mary. - -"I have a letter from him," she replied. - -He glanced at her with timid surprise. - -"Where is he?" - -"He's with the army, Father, at Smolensk." - -He closed his eyes and remained silent a long time. Then as if in -answer to his doubts and to confirm the fact that now he understood -and remembered everything, he nodded his head and reopened his eyes. - -"Yes," he said, softly and distinctly. "Russia has perished. They've -destroyed her." - -And he began to sob, and again tears flowed from his eyes. -Princess Mary could no longer restrain herself and wept while she -gazed at his face. - -Again he closed his eyes. His sobs ceased, he pointed to his eyes, -and Tikhon, understanding him, wiped away the tears. - -Then he again opened his eyes and said something none of them -could understand for a long time, till at last Tikhon understood and -repeated it. Princess Mary had sought the meaning of his words in -the mood in which he had just been speaking. She thought he was -speaking of Russia, or Prince Andrew, of herself, of his grandson, -or of his own death, and so she could not guess his words. - -"Put on your white dress. I like it," was what he said. - -Having understood this Princess Mary sobbed still louder, and the -doctor taking her arm led her out to the veranda, soothing her and -trying to persuade her to prepare for her journey. When she had left -the room the prince again began speaking about his son, about the war, -and about the Emperor, angrily twitching his brows and raising his -hoarse voice, and then he had a second and final stroke. - -Princess Mary stayed on the veranda. The day had cleared, it was hot -and sunny. She could understand nothing, think of nothing and feel -nothing, except passionate love for her father, love such as she -thought she had never felt till that moment. She ran out sobbing -into the garden and as far as the pond, along the avenues of young -lime trees Prince Andrew had planted. - -"Yes... I... I... I wished for his death! Yes, I wanted it to end -quicker.... I wished to be at peace.... And what will become of me? -What use will peace be when he is no longer here?" Princess Mary -murmured, pacing the garden with hurried steps and pressing her -hands to her bosom which heaved with convulsive sobs. - -When she had completed the tour of the garden, which brought her -again to the house, she saw Mademoiselle Bourienne--who had remained -at Bogucharovo and did not wish to leave it--coming toward her with -a stranger. This was the Marshal of the Nobility of the district, -who had come personally to point out to the princess the necessity for -her prompt departure. Princess Mary listened without understanding -him; she led him to the house, offered him lunch, and sat down with -him. Then, excusing herself, she went to the door of the old -prince's room. The doctor came out with an agitated face and said -she could not enter. - -"Go away, Princess! Go away... go away!" - -She returned to the garden and sat down on the grass at the foot -of the slope by the pond, where no one could see her. She did not know -how long she had been there when she was aroused by the sound of a -woman's footsteps running along the path. She rose and saw Dunyasha -her maid, who was evidently looking for her, and who stopped -suddenly as if in alarm on seeing her mistress. - -"Please come, Princess... The Prince," said Dunyasha in a breaking -voice. - -"Immediately, I'm coming, I'm coming!" replied the princess -hurriedly, not giving Dunyasha time to finish what she was saying, and -trying to avoid seeing the girl she ran toward the house. - -"Princess, it's God's will! You must be prepared for everything," -said the Marshal, meeting her at the house door. - -"Let me alone; it's not true!" she cried angrily to him. - -The doctor tried to stop her. She pushed him aside and ran to her -father's door. "Why are these people with frightened faces stopping -me? I don't want any of them! And what are they doing here?" she -thought. She opened the door and the bright daylight in that -previously darkened room startled her. In the room were her nurse -and other women. They all drew back from the bed, making way for -her. He was still lying on the bed as before, but the stern expression -of his quiet face made Princess Mary stop short on the threshold. - -"No, he's not dead--it's impossible!" she told herself and -approached him, and repressing the terror that seized her, she pressed -her lips to his cheek. But she stepped back immediately. All the force -of the tenderness she had been feeling for him vanished instantly -and was replaced by a feeling of horror at what lay there before -her. "No, he is no more! He is not, but here where he was is something -unfamiliar and hostile, some dreadful, terrifying, and repellent -mystery!" And hiding her face in her hands, Princess Mary sank into -the arms of the doctor, who held her up. - - -In the presence of Tikhon and the doctor the women washed what had -been the prince, tied his head up with a handkerchief that the mouth -should not stiffen while open, and with another handkerchief tied -together the legs that were already spreading apart. Then they dressed -him in uniform with his decorations and placed his shriveled little -body on a table. Heaven only knows who arranged all this and when, but -it all got done as if of its own accord. Toward night candles were -burning round his coffin, a pall was spread over it, the floor was -strewn with sprays of juniper, a printed band was tucked in under -his shriveled head, and in a corner of the room sat a chanter -reading the psalms. - -Just as horses shy and snort and gather about a dead horse, so the -inmates of the house and strangers crowded into the drawing room round -the coffin--the Marshal, the village Elder, peasant women--and all -with fixed and frightened eyes, crossing themselves, bowed and -kissed the old prince's cold and stiffened hand. - - - - - -CHAPTER IX - - -Until Prince Andrew settled in Bogucharovo its owners had always -been absentees, and its peasants were of quite a different character -from those of Bald Hills. They differed from them in speech, dress, -and disposition. They were called steppe peasants. The old prince used -to approve of them for their endurance at work when they came to -Bald Hills to help with the harvest or to dig ponds, and ditches, -but he disliked them for their boorishness. - -Prince Andrew's last stay at Bogucharovo, when he introduced -hospitals and schools and reduced the quitrent the peasants had to -pay, had not softened their disposition but had on the contrary -strengthened in them the traits of character the old prince called -boorishness. Various obscure rumors were always current among them: at -one time a rumor that they would all be enrolled as Cossacks; at -another of a new religion to which they were all to be converted; then -of some proclamation of the Tsar's and of an oath to the Tsar Paul -in 1797 (in connection with which it was rumored that freedom had been -granted them but the landowners had stopped it), then of Peter -Fedorovich's return to the throne in seven years' time, when -everything would be made free and so "simple" that there would be no -restrictions. Rumors of the war with Bonaparte and his invasion were -connected in their minds with the same sort of vague notions of -Antichrist, the end of the world, and "pure freedom." - -In the vicinity of Bogucharovo were large villages belonging to -the crown or to owners whose serfs paid quitrent and could work -where they pleased. There were very few resident landlords in the -neighborhood and also very few domestic or literate serfs, and in -the lives of the peasantry of those parts the mysterious undercurrents -in the life of the Russian people, the causes and meaning of which are -so baffling to contemporaries, were more clearly and strongly -noticeable than among others. One instance, which had occurred some -twenty years before, was a movement among the peasants to emigrate -to some unknown "warm rivers." Hundreds of peasants, among them the -Bogucharovo folk, suddenly began selling their cattle and moving in -whole families toward the southeast. As birds migrate to somewhere -beyond the sea, so these men with their wives and children streamed to -the southeast, to parts where none of them had ever been. They set off -in caravans, bought their freedom one by one or ran away, and drove or -walked toward the "warm rivers." Many of them were punished, some sent -to Siberia, many died of cold and hunger on the road, many returned of -their own accord, and the movement died down of itself just as it -had sprung up, without apparent reason. But such undercurrents still -existed among the people and gathered new forces ready to manifest -themselves just as strangely, unexpectedly, and at the same time -simply, naturally, and forcibly. Now in 1812, to anyone living in -close touch with these people it was apparent that these undercurrents -were acting strongly and nearing an eruption. - -Alpatych, who had reached Bogucharovo shortly before the old -prince's death, noticed an agitation among the peasants, and that -contrary to what was happening in the Bald Hills district, where -over a radius of forty miles all the peasants were moving away and -leaving their villages to be devastated by the Cossacks, the -peasants in the steppe region round Bogucharovo were, it was -rumored, in touch with the French, received leaflets from them that -passed from hand to hand, and did not migrate. He learned from -domestic serfs loyal to him that the peasant Karp, who possessed great -influence in the village commune and had recently been away driving -a government transport, had returned with news that the Cossacks -were destroying deserted villages, but that the French did not harm -them. Alpatych also knew that on the previous day another peasant -had even brought from the village of Visloukhovo, which was occupied -by the French, a proclamation by a French general that no harm would -be done to the inhabitants, and if they remained they would be paid -for anything taken from them. As proof of this the peasant had brought -from Visloukhovo a hundred rubles in notes (he did not know that -they were false) paid to him in advance for hay. - -More important still, Alpatych learned that on the morning of the -very day he gave the village Elder orders to collect carts to move the -princess' luggage from Bogucharovo, there had been a village meeting -at which it had been decided not to move but to wait. Yet there was no -time to waste. On the fifteenth, the day of the old prince's death, -the Marshal had insisted on Princess Mary's leaving at once, as it was -becoming dangerous. He had told her that after the sixteenth he -could not be responsible for what might happen. On the evening of -the day the old prince died the Marshal went away, promising to return -next day for the funeral. But this he was unable to do, for he -received tidings that the French had unexpectedly advanced, and had -barely time to remove his own family and valuables from his estate. - -For some thirty years Bogucharovo had been managed by the village -Elder, Dron, whom the old prince called by the diminutive "Dronushka." - -Dron was one of those physically and mentally vigorous peasants -who grow big beards as soon as they are of age and go on unchanged -till they are sixty or seventy, without a gray hair or the loss of a -tooth, as straight and strong at sixty as at thirty. - -Soon after the migration to the "warm rivers," in which he had taken -part like the rest, Dron was made village Elder and overseer of -Bogucharovo, and had since filled that post irreproachably for -twenty-three years. The peasants feared him more than they did their -master. The masters, both the old prince and the young, and the -steward respected him and jestingly called him "the Minister." -During the whole time of his service Dron had never been drunk or ill, -never after sleepless nights or the hardest tasks had he shown the -least fatigue, and though he could not read he had never forgotten a -single money account or the number of quarters of flour in any of -the endless cartloads he sold for the prince, nor a single shock of -the whole corn crop on any single acre of the Bogucharovo fields. - -Alpatych, arriving from the devastated Bald Hills estate, sent for -his Dron on the day of the prince's funeral and told him to have -twelve horses got ready for the princess' carriages and eighteen carts -for the things to be removed from Bogucharovo. Though the peasants -paid quitrent, Alpatych thought no difficulty would be made about -complying with this order, for there were two hundred and thirty -households at work in Bogucharovo and the peasants were well to do. -But on hearing the order Dron lowered his eyes and remained silent. -Alpatych named certain peasants he knew, from whom he told him to take -the carts. - -Dron replied that the horses of these peasants were away carting. -Alpatych named others, but they too, according to Dron, had no -horses available: some horses were carting for the government, -others were too weak, and others had died for want of fodder. It -seemed that no horses could be had even for the carriages, much less -for the carting. - -Alpatych looked intently at Dron and frowned. Just as Dron was a -model village Elder, so Alpatych had not managed the prince's -estates for twenty years in vain. He a model steward, possessing in -the highest degree the faculty of divining the needs and instincts -of those he dealt with. Having glanced at Dron he at once understood -that his answers did not express his personal views but the general -mood of the Bogucharovo commune, by which the Elder had already been -carried away. But he also knew that Dron, who had acquired property -and was hated by the commune, must be hesitating between the two -camps: the masters' and the serfs'. He noticed this hesitation in -Dron's look and therefore frowned and moved closer up to him. - -"Now just listen, Dronushka," said he. "Don't talk nonsense to me. -His excellency Prince Andrew himself gave me orders to move all the -people away and not leave them with the enemy, and there is an order -from the Tsar about it too. Anyone who stays is a traitor to the Tsar. -Do you hear?" - -"I hear," Dron answered without lifting his eyes. - -Alpatych was not satisfied with this reply. - -"Eh, Dron, it will turn out badly!" he said, shaking his head. - -"The power is in your hands," Dron rejoined sadly. - -"Eh, Dron, drop it!" Alpatych repeated, withdrawing his hand from -his bosom and solemnly pointing to the floor at Dron's feet. "I can -see through you and three yards into the ground under you," he -continued, gazing at the floor in front of Dron. - -Dron was disconcerted, glanced furtively at Alpatych and again -lowered his eyes. - -"You drop this nonsense and tell the people to get ready to leave -their homes and go to Moscow and to get carts ready for tomorrow -morning for the princess' things. And don't go to any meeting -yourself, do you hear?" - -Dron suddenly fell on his knees. - -"Yakov Alpatych, discharge me! Take the keys from me and discharge -me, for Christ's sake!" - -"Stop that!" cried Alpatych sternly. "I see through you and three -yards under you," he repeated, knowing that his skill in beekeeping, -his knowledge of the right time to sow the oats, and the fact that -he had been able to retain the old prince's favor for twenty years had -long since gained him the reputation of being a wizard, and that the -power of seeing three yards under a man is considered an attribute -of wizards. - -Dron got up and was about to say something, but Alpatych interrupted -him. - -"What is it you have got into your heads, eh?... What are you -thinking of, eh?" - -"What am I to do with the people?" said Dron. "They're quite -beside themselves; I have already told them..." - -"'Told them,' I dare say!" said Alpatych. "Are they drinking?" he -asked abruptly. - -"Quite beside themselves, Yakov Alpatych; they've fetched another -barrel." - -"Well, then, listen! I'll go to the police officer, and you tell -them so, and that they must stop this and the carts must be got -ready." - -"I understand." - -Alpatych did not insist further. He had managed people for a long -time and knew that the chief way to make them obey is to show no -suspicion that they can possibly disobey. Having wrung a submissive "I -understand" from Dron, Alpatych contented himself with that, though he -not only doubted but felt almost certain that without the help of -troops the carts would not be forthcoming. - -And so it was, for when evening came no carts had been provided. -In the village, outside the drink shop, another meeting was being -held, which decided that the horses should be driven out into the -woods and the carts should not be provided. Without saying anything of -this to the princess, Alpatych had his own belongings taken out of the -carts which had arrived from Bald Hills and had those horses got ready -for the princess' carriages. Meanwhile he went himself to the police -authorities. - - - - - -CHAPTER X - - -After her father's funeral Princess Mary shut herself up in her room -and did not admit anyone. A maid came to the door to say that Alpatych -was asking for orders about their departure. (This was before his talk -with Dron.) Princess Mary raised herself on the sofa on which she -had been lying and replied through the closed door that she did not -mean to go away and begged to be left in peace. - -The windows of the room in which she was lying looked westward. -She lay on the sofa with her face to the wall, fingering the buttons -of the leather cushion and seeing nothing but that cushion, and her -confused thoughts were centered on one subject--the irrevocability -of death and her own spiritual baseness, which she had not -suspected, but which had shown itself during her father's illness. She -wished to pray but did not dare to, dared not in her present state -of mind address herself to God. She lay for a long time in that -position. - -The sun had reached the other side of the house, and its slanting -rays shone into the open window, lighting up the room and part of -the morocco cushion at which Princess Mary was looking. The flow of -her thoughts suddenly stopped. Unconsciously she sat up, smoothed -her hair, got up, and went to the window, involuntarily inhaling the -freshness of the clear but windy evening. - -"Yes, you can well enjoy the evening now! He is gone and no one will -hinder you," she said to herself, and sinking into a chair she let her -head fall on the window sill. - -Someone spoke her name in a soft and tender voice from the garden -and kissed her head. She looked up. It was Mademoiselle Bourienne in a -black dress and weepers. She softly approached Princess Mary, -sighed, kissed her, and immediately began to cry. The princess -looked up at her. All their former disharmony and her own jealousy -recurred to her mind. But she remembered too how he had changed of -late toward Mademoiselle Bourienne and could not bear to see her, -thereby showing how unjust were the reproaches Princess Mary had -mentally addressed to her. "Besides, is it for me, for me who -desired his death, to condemn anyone?" she thought. - -Princess Mary vividly pictured to herself the position of -Mademoiselle Bourienne, whom she had of late kept at a distance, but -who yet was dependent on her and living in her house. She felt sorry -for her and held out her hand with a glance of gentle inquiry. -Mademoiselle Bourienne at once began crying again and kissed that -hand, speaking of the princess' sorrow and making herself a partner in -it. She said her only consolation was the fact that the princess -allowed her to share her sorrow, that all the old misunderstandings -should sink into nothing but this great grief; that she felt herself -blameless in regard to everyone, and that he, from above, saw her -affection and gratitude. The princess heard her, not heeding her words -but occasionally looking up at her and listening to the sound of her -voice. - -"Your position is doubly terrible, dear princess," said Mademoiselle -Bourienne after a pause. "I understand that you could not, and cannot, -think of yourself, but with my love for you I must do so.... Has -Alpatych been to you? Has he spoken to you of going away?" she asked. - -Princess Mary did not answer. She did not understand who was to go -or where to. "Is it possible to plan or think of anything now? Is it -not all the same?" she thought, and did not reply. - -"You know, chere Marie," said Mademoiselle Bourienne, "that we are -in danger--are surrounded by the French. It would be dangerous to move -now. If we go we are almost sure to be taken prisoners, and God -knows..." - -Princess Mary looked at her companion without understanding what she -was talking about. - -"Oh, if anyone knew how little anything matters to me now," she -said. "Of course I would on no account wish to go away from him.... -Alpatych did say something about going.... Speak to him; I can do -nothing, nothing, and don't want to...." - -"I've spoken to him. He hopes we should be in time to get away -tomorrow, but I think it would now be better to stay here," said -Mademoiselle Bourienne. "Because, you will agree, chere Marie, to fall -into the hands of the soldiers or of riotous peasants would be -terrible." - -Mademoiselle Bourienne took from her reticule a proclamation (not -printed on ordinary Russian paper) of General Rameau's, telling people -not to leave their homes and that the French authorities would -afford them proper protection. She handed this to the princess. - -"I think it would be best to appeal to that general," she continued, -"and and am sure that all due respect would be shown you." - -Princess Mary read the paper, and her face began to quiver with -stifled sobs. - -"From whom did you get this?" she asked. - -"They probably recognized that I am French, by my name," replied -Mademoiselle Bourienne blushing. - -Princess Mary, with the paper in her hand, rose from the window -and with a pale face went out of the room and into what had been -Prince Andrew's study. - -"Dunyasha, send Alpatych, or Dronushka, or somebody to me!" she -said, "and tell Mademoiselle Bourienne not to come to me," she -added, hearing Mademoiselle Bourienne's voice. "We must go at once, at -once!" she said, appalled at the thought of being left in the hands of -the French. - -"If Prince Andrew heard that I was in the power of the French! -That I, the daughter of Prince Nicholas Bolkonski, asked General -Rameau for protection and accepted his favor!" This idea horrified -her, made her shudder, blush, and feel such a rush of anger and -pride as she had never experienced before. All that was distressing, -and especially all that was humiliating, in her position rose -vividly to her mind. "They, the French, would settle in this house: M. -le General Rameau would occupy Prince Andrew's study and amuse himself -by looking through and reading his letters and papers. Mademoiselle -Bourienne would do the honors of Bogucharovo for him. I should be -given a small room as a favor, the soldiers would violate my -father's newly dug grave to steal his crosses and stars, they would -tell me of their victories over the Russians, and would pretend to -sympathize with my sorrow..." thought Princess Mary, not thinking -her own thoughts but feeling bound to think like her father and her -brother. For herself she did not care where she remained or what -happened to her, but she felt herself the representative of her dead -father and of Prince Andrew. Involuntarily she thought their -thoughts and felt their feelings. What they would have said and what -they would have done she felt bound to say and do. She went into -Prince Andrew's study, trying to enter completely into his ideas, -and considered her position. - -The demands of life, which had seemed to her annihilated by her -father's death, all at once rose before her with a new, previously -unknown force and took possession of her. - -Agitated and flushed she paced the room, sending now for Michael -Ivanovich and now for Tikhon or Dron. Dunyasha, the nurse, and the -other maids could not say in how far Mademoiselle Bourienne's -statement was correct. Alpatych was not at home, he had gone to the -police. Neither could the architect Michael Ivanovich, who on being -sent for came in with sleepy eyes, tell Princess Mary anything. With -just the same smile of agreement with which for fifteen years he had -been accustomed to answer the old prince without expressing views of -his own, he now replied to Princess Mary, so that nothing definite -could be got from his answers. The old valet Tikhon, with sunken, -emaciated face that bore the stamp of inconsolable grief, replied: -"Yes, Princess" to all Princess Mary's questions and hardly -refrained from sobbing as he looked at her. - -At length Dron, the village Elder, entered the room and with a -deep bow to Princess Mary came to a halt by the doorpost. - -Princess Mary walked up and down the room and stopped in front of -him. - -"Dronushka," she said, regarding as a sure friend this Dronushka who -always used to bring a special kind of gingerbread from his visit to -the fair at Vyazma every year and smilingly offer it to her, -"Dronushka, now since our misfortune..." she began, but could not go -on. - -"We are all in God's hands," said he, with a sigh. - -They were silent for a while. - -"Dronushka, Alpatych has gone off somewhere and I have no one to -turn to. Is true, as they tell me, that I can't even go away?" - -"Why shouldn't you go away, your excellency? You can go," said Dron. - -"I was told it would be dangerous because of the enemy. Dear friend, -I can do nothing. I understand nothing. I have nobody! I want to go -away tonight or early tomorrow morning." - -Dron paused. He looked askance at Princess Mary and said: "There are -no horses; I told Yakov Alpatych so." - -"Why are there none?" asked the princess. - -"It's all God's scourge," said Dron. "What horses we had have been -taken for the army or have died--this is such a year! It's not a -case of feeding horses--we may die of hunger ourselves! As it is, some -go three days without eating. We've nothing, we've been ruined." - -Princess Mary listened attentively to what he told her. - -"The peasants are ruined? They have no bread?" she asked. - -"They're dying of hunger," said Dron. "It's not a case of carting." - -"But why didn't you tell me, Dronushka? Isn't it possible to help -them? I'll do all I can...." - -To Princess Mary it was strange that now, at a moment when such -sorrow was filling her soul, there could be rich people and poor, -and the rich could refrain from helping the poor. She had heard -vaguely that there was such a thing as "landlord's corn" which was -sometimes given to the peasants. She also knew that neither her father -nor her brother would refuse to help the peasants in need, she only -feared to make some mistake in speaking about the distribution of -the grain she wished to give. She was glad such cares presented -themselves, enabling her without scruple to forget her own grief. -She began asking Dron about the peasants' needs and what there was -in Bogucharovo that belonged to the landlord. - -"But we have grain belonging to my brother?" she said. - -"The landlord's grain is all safe," replied Dron proudly. "Our -prince did not order it to be sold." - -"Give it to the peasants, let them have all they need; I give you -leave in my brother's name," said she. - -Dron made no answer but sighed deeply. - -"Give them that corn if there is enough of it. Distribute it all. -I give this order in my brother's name; and tell them that what is -ours is theirs. We do not grudge them anything. Tell them so." - -Dron looked intently at the princess while she was speaking. - -"Discharge me, little mother, for God's sake! Order the keys to be -taken from me," said he. "I have served twenty-three years and have -done no wrong. Discharge me, for God's sake!" - -Princess Mary did not understand what he wanted of her or why he was -asking to be discharged. She replied that she had never doubted his -devotion and that she was ready to do anything for him and for the -peasants. - - - - - -CHAPTER XI - - -An hour later Dunyasha came to tell the princess that Dron had come, -and all the peasants had assembled at the barn by the princess' -order and wished to have word with their mistress. - -"But I never told them to come," said Princess Mary. "I only told -Dron to let them have the grain." - -"Only, for God's sake, Princess dear, have them sent away and -don't go out to them. It's all a trick," said Dunyasha, "and when -Yakov Alpatych returns let us get away... and please don't..." - -"What is a trick?" asked Princess Mary in surprise. - -"I know it is, only listen to me for God's sake! Ask nurse too. They -say they don't agree to leave Bogucharovo as you ordered." - -"You're making some mistake. I never ordered them to go away," -said Princess Mary. "Call Dronushka." - -Dron came and confirmed Dunyasha's words; the peasants had come by -the princess' order. - -"But I never sent for them," declared the princess. "You must have -given my message wrong. I only said that you were to give them the -grain." - -Dron only sighed in reply. - -"If you order it they will go away," said he. - -"No, no. I'll go out to them," said Princess Mary, and in spite of -the nurse's and Dunyasha's protests she went out into the porch; Dron, -Dunyasha, the nurse, and Michael Ivanovich following her. - -"They probably think I am offering them the grain to bribe them to -remain here, while I myself go away leaving them to the mercy of the -French," thought Princess Mary. "I will offer them monthly rations and -housing at our Moscow estate. I am sure Andrew would do even more in -my place," she thought as she went out in the twilight toward the -crowd standing on the pasture by the barn. - -The men crowded closer together, stirred, and rapidly took off their -hats. Princess Mary lowered her eyes and, tripping over her skirt, -came close up to them. So many different eyes, old and young, were -fixed on her, and there were so many different faces, that she could -not distinguish any of them and, feeling that she must speak to them -all at once, did not know how to do it. But again the sense that she -represented her father and her brother gave her courage, and she -boldly began her speech. - -"I am very glad you have come," she said without raising her eyes, -and feeling her heart beating quickly and violently. "Dronushka -tells me that the war has ruined you. That is our common misfortune, -and I shall grudge nothing to help you. I am myself going away because -it is dangerous here... the enemy is near... because... I am giving -you everything, my friends, and I beg you to take everything, all -our grain, so that you may not suffer want! And if you have been -told that I am giving you the grain to keep you here--that is not -true. On the contrary, I ask you to go with all your belongings to our -estate near Moscow, and I promise you I will see to it that there -you shall want for nothing. You shall be given food and lodging." - -The princess stopped. Sighs were the only sound heard in the crowd. - -"I am not doing this on my own account," she continued, "I do it -in the name of my dead father, who was a good master to you, and of my -brother and his son." - -Again she paused. No one broke the silence. - -"Ours is a common misfortune and we will share it together. All that -is mine is yours," she concluded, scanning the faces before her. - -All eyes were gazing at her with one and the same expression. She -could not fathom whether it was curiosity, devotion, gratitude, or -apprehension and distrust--but the expression on all the faces was -identical. - -"We are all very thankful for your bounty, but it won't do for us to -take the landlord's grain," said a voice at the back of the crowd. - -"But why not?" asked the princess. - -No one replied and Princess Mary, looking round at the crowd, -found that every eye she met now was immediately dropped. - -"But why don't you want to take it?" she asked again. - -No one answered. - -The silence began to oppress the princess and she tried to catch -someone's eye. - -"Why don't you speak?" she inquired of a very old man who stood just -in front of her leaning on his stick. "If you think something more -is wanted, tell me! I will do anything," said she, catching his eye. - -But as if this angered him, he bent his head quite low and muttered: - -"Why should we agree? We don't want the grain." - -"Why should we give up everything? We don't agree. Don't agree.... -We are sorry for you, but we're not willing. Go away yourself, -alone..." came from various sides of the crowd. - -And again all the faces in that crowd bore an identical -expression, though now it was certainly not an expression of curiosity -or gratitude, but of angry resolve. - -"But you can't have understood me," said Princess Mary with a sad -smile. "Why don't you want to go? I promise to house and feed you, -while here the enemy would ruin you..." - -But her voice was drowned by the voices of the crowd. - -"We're not willing. Let them ruin us! We won't take your grain. We -don't agree." - -Again Princess Mary tried to catch someone's eye, but not a single -eye in the crowd was turned to her; evidently they were all trying -to avoid her look. She felt strange and awkward. - -"Oh yes, an artful tale! Follow her into slavery! Pull down your -houses and go into bondage! I dare say! 'I'll give you grain, indeed!' -she says," voices in the crowd were heard saying. - -With drooping head Princess Mary left the crowd and went back to the -house. Having repeated her order to Dron to have horses ready for -her departure next morning, she went to her room and remained alone -with her own thoughts. - - - - - -CHAPTER XII - - -For a long time that night Princess Mary sat by the open window of -her room hearing the sound of the peasants' voices that reached her -from the village, but it was not of them she was thinking. She felt -that she could not understand them however much she might think -about them. She thought only of one thing, her sorrow, which, after -the break caused by cares for the present, seemed already to belong to -the past. Now she could remember it and weep or pray. - -After sunset the wind had dropped. The night was calm and fresh. -Toward midnight the voices began to subside, a cock crowed, the full -moon began to show from behind the lime trees, a fresh white dewy mist -began to rise, and stillness reigned over the village and the house. - -Pictures of the near past--her father's illness and last moments- -rose one after another to her memory. With mournful pleasure she now -lingered over these images, repelling with horror only the last one, -the picture of his death, which she felt she could not contemplate -even in imagination at this still and mystic hour of night. And -these pictures presented themselves to her so clearly and in such -detail that they seemed now present, now past, and now future. - -She vividly recalled the moment when he had his first stroke and was -being dragged along by his armpits through the garden at Bald Hills, -muttering something with his helpless tongue, twitching his gray -eyebrows and looking uneasily and timidly at her. - -"Even then he wanted to tell me what he told me the day he died," -she thought. "He had always thought what he said then." And she -recalled in all its detail the night at Bald Hills before he had the -last stroke, when with a foreboding of disaster she had remained at -home against his will. She had not slept and had stolen downstairs -on tiptoe, and going to the door of the conservatory where he slept -that night had listened at the door. In a suffering and weary voice he -was saying something to Tikhon, speaking of the Crimea and its warm -nights and of the Empress. Evidently he had wanted to talk. "And why -didn't he call me? Why didn't he let me be there instead of Tikhon?" -Princess Mary had thought and thought again now. "Now he will never -tell anyone what he had in his soul. Never will that moment return for -him or for me when he might have said all he longed to say, and not -Tikhon but I might have heard and understood him. Why didn't I enter -the room?" she thought. "Perhaps he would then have said to me what he -said the day he died. While talking to Tikhon he asked about me twice. -He wanted to see me, and I was standing close by, outside the door. It -was sad and painful for him to talk to Tikhon who did not understand -him. I remember how he began speaking to him about Lise as if she were -alive--he had forgotten she was dead--and Tikhon reminded him that she -was no more, and he shouted, 'Fool!' He was greatly depressed. From -behind the door I heard how he lay down on his bed groaning and loudly -exclaimed, 'My God!' Why didn't I go in then? What could he have -done to me? What could I have lost? And perhaps he would then have -been comforted and would have said that word to me." And Princess Mary -uttered aloud the caressing word he had said to her on the day of -his death. "Dear-est!" she repeated, and began sobbing, with tears -that relieved her soul. She now saw his face before her. And not the -face she had known ever since she could remember and had always seen -at a distance, but the timid, feeble face she had seen for the first -time quite closely, with all its wrinkles and details, when she -stooped near to his mouth to catch what he said. - -"Dear-est!" she repeated again. - -"What was he thinking when he uttered that word? What is he thinking -now?" This question suddenly presented itself to her, and in answer -she saw him before her with the expression that was on his face as -he lay in his coffin with his chin bound up with a white handkerchief. -And the horror that had seized her when she touched him and -convinced herself that that was not he, but something mysterious and -horrible, seized her again. She tried to think of something else and -to pray, but could do neither. With wide-open eyes she gazed at the -moonlight and the shadows, expecting every moment to see his dead -face, and she felt that the silence brooding over the house and within -it held her fast. - -"Dunyasha," she whispered. "Dunyasha!" she screamed wildly, and -tearing herself out of this silence she ran to the servants' -quarters to meet her old nurse and the maidservants who came running -toward her. - - - - - -CHAPTER XIII - - -On the seventeenth of August Rostov and Ilyin, accompanied by -Lavrushka who had just returned from captivity and by an hussar -orderly, left their quarters at Yankovo, ten miles from Bogucharovo, -and went for a ride--to try a new horse Ilyin had bought and to find -out whether there was any hay to be had in the villages. - -For the last three days Bogucharovo had lain between the two hostile -armies, so that it was as easy for the Russian rearguard to get to -it as for the French vanguard; Rostov, as a careful squadron -commander, wished to take such provisions as remained at Bogucharovo -before the French could get them. - -Rostov and Ilyin were in the merriest of moods. On the way to -Bogucharovo, a princely estate with a dwelling house and farm where -they hoped to find many domestic serfs and pretty girls, they -questioned Lavrushka about Napoleon and laughed at his stories, and -raced one another to try Ilyin's horse. - -Rostov had no idea that the village he was entering was the property -of that very Bolkonski who had been engaged to his sister. - -Rostov and Ilyin gave rein to their horses for a last race along the -incline before reaching Bogucharovo, and Rostov, outstripping Ilyin, -was the first to gallop into the village street. - -"You're first!" cried Ilyin, flushed. - -"Yes, always first both on the grassland and here," answered Rostov, -stroking his heated Donets horse. - -"And I'd have won on my Frenchy, your excellency," said Lavrushka -from behind, alluding to his shabby cart horse, "only I didn't wish to -mortify you." - -They rode at a footpace to the barn, where a large crowd of peasants -was standing. - -Some of the men bared their heads, others stared at the new arrivals -without doffing their caps. Two tall old peasants with wrinkled -faces and scanty beards emerged from the tavern, smiling, -staggering, and singing some incoherent song, and approached the -officers. - -"Fine fellows!" said Rostov laughing. "Is there any hay here?" - -"And how like one another," said Ilyin. - -"A mo-o-st me-r-r-y co-o-m-pa...!" sang one of the peasants with a -blissful smile. - -One of the men came out of the crowd and went up to Rostov. - -"Who do you belong to?" he asked. - -"The French," replied Ilyin jestingly, "and here is Napoleon -himself"--and he pointed to Lavrushka. - -"Then you are Russians?" the peasant asked again. - -"And is there a large force of you here?" said another, a short man, -coming up. - -"Very large," answered Rostov. "But why have you collected here?" he -added. "Is it a holiday?" - -"The old men have met to talk over the business of the commune," -replied the peasant, moving away. - -At that moment, on the road leading from the big house, two women -and a man in a white hat were seen coming toward the officers. - -"The one in pink is mine, so keep off!" said Ilyin on seeing -Dunyasha running resolutely toward him. - -"She'll be ours!" said Lavrushka to Ilyin, winking. - -"What do you want, my pretty?" said Ilyin with a smile. - -"The princess ordered me to ask your regiment and your name." - -"This is Count Rostov, squadron commander, and I am your humble -servant." - -"Co-o-om-pa-ny!" roared the tipsy peasant with a beatific smile as -he looked at Ilyin talking to the girl. Following Dunyasha, Alpatych -advanced to Rostov, having bared his head while still at a distance. - -"May I make bold to trouble your honor?" said he respectfully, but -with a shade of contempt for the youthfulness of this officer and with -a hand thrust into his bosom. "My mistress, daughter of General in -Chief Prince Nicholas Bolkonski who died on the fifteenth of this -month, finding herself in difficulties owing to the boorishness of -these people"--he pointed to the peasants--"asks you to come up to the -house.... Won't you, please, ride on a little farther," said -Alpatych with a melancholy smile, "as it is not convenient in the -presence of...?" He pointed to the two peasants who kept as close to -him as horseflies to a horse. - -"Ah!... Alpatych... Ah, Yakov Alpatych... Grand! Forgive us for -Christ's sake, eh?" said the peasants, smiling joyfully at him. - -Rostov looked at the tipsy peasants and smiled. - -"Or perhaps they amuse your honor?" remarked Alpatych with a staid -air, as he pointed at the old men with his free hand. - -"No, there's not much to be amused at here," said Rostov, and rode -on a little way. "What's the matter?" he asked. - -"I make bold to inform your honor that the rude peasants here -don't wish to let the mistress leave the estate, and threaten to -unharness her horses, so that though everything has been packed up -since morning, her excellency cannot get away." - -"Impossible!" exclaimed Rostov. - -"I have the honor to report to you the actual truth," said Alpatych. - -Rostov dismounted, gave his horse to the orderly, and followed -Alpatych to the house, questioning him as to the state of affairs. -It appeared that the princess' offer of corn to the peasants the -previous day, and her talk with Dron and at the meeting, had -actually had so bad an effect that Dron had finally given up the -keys and joined the peasants and had not appeared when Alpatych sent -for him; and that in the morning when the princess gave orders to -harness for her journey, the peasants had come in a large crowd to the -barn and sent word that they would not let her leave the village: that -there was an order not to move, and that they would unharness the -horses. Alpatych had gone out to admonish them, but was told (it was -chiefly Karp who did the talking, Dron not showing himself in the -crowd) that they could not let the princess go, that there was an -order to the contrary, but that if she stayed they would serve her -as before and obey her in everything. - -At the moment when Rostov and Ilyin were galloping along the road, -Princess Mary, despite the dissuasions of Alpatych, her nurse, and the -maids, had given orders to harness and intended to start, but when the -cavalrymen were espied they were taken for Frenchmen, the coachman ran -away, and the women in the house began to wail. - -"Father! Benefactor! God has sent you!" exclaimed deeply moved -voices as Rostov passed through the anteroom. - -Princess Mary was sitting helpless and bewildered in the large -sitting room, when Rostov was shown in. She could not grasp who he was -and why he had come, or what was happening to her. When she saw his -Russian face, and by his walk and the first words he uttered -recognized him as a man of her own class, she glanced at him with -her deep radiant look and began speaking in a voice that faltered -and trembled with emotion. This meeting immediately struck Rostov as a -romantic event. "A helpless girl overwhelmed with grief, left to the -mercy of coarse, rioting peasants! And what a strange fate sent me -here! What gentleness and nobility there are in her features and -expression!" thought he as he looked at her and listened to her -timid story. - -When she began to tell him that all this had happened the day -after her father's funeral, her voiced trembled. She turned away, -and then, as if fearing he might take her words as meant to move him -to pity, looked at him with an apprehensive glance of inquiry. There -were tears in Rostov's eyes. Princess Mary noticed this and glanced -gratefully at him with that radiant look which caused the plainness of -her face to be forgotten. - -"I cannot express, Princess, how glad I am that I happened to ride -here and am able to show my readiness to serve you," said Rostov, -rising. "Go when you please, and I give you my word of honor that no -one shall dare to cause you annoyance if only you will allow me to act -as your escort." And bowing respectfully, as if to a lady of royal -blood, he moved toward the door. - -Rostov's deferential tone seemed to indicate that though he would -consider himself happy to be acquainted with her, he did not wish to -take advantage of her misfortunes to intrude upon her. - -Princess Mary understood this and appreciated his delicacy. - -"I am very, very grateful to you," she said in French, "but I hope -it was all a misunderstanding and that no one is to blame for it." She -suddenly began to cry. - -"Excuse me!" she said. - -Rostov, knitting his brows, left the room with another low bow. - - - - - -CHAPTER XIV - - -"Well, is she pretty? Ah, friend--my pink one is delicious; her -name is Dunyasha...." - -But on glancing at Rostov's face Ilyin stopped short. He saw that -his hero and commander was following quite a different train of -thought. - -Rostov glanced angrily at Ilyin and without replying strode off with -rapid steps to the village. - -"I'll show them; I'll give it to them, the brigands!" said he to -himself. - -Alpatych at a gliding trot, only just managing not to run, kept up -with him with difficulty. - -"What decision have you been pleased to come to?" said he. - -Rostov stopped and, clenching his fists, suddenly and sternly turned -on Alpatych. - -"Decision? What decision? Old dotard!..." cried he. "What have you -been about? Eh? The peasants are rioting, and you can't manage them? -You're a traitor yourself! I know you. I'll flay you all alive!..." -And as if afraid of wasting his store of anger, he left Alpatych and -went rapidly forward. Alpatych, mastering his offended feelings, -kept pace with Rostov at a gliding gait and continued to impart his -views. He said the peasants were obdurate and that at the present -moment it would be imprudent to "overresist" them without an armed -force, and would it not be better first to send for the military? - -"I'll give them armed force... I'll 'overresist' them!" uttered -Rostov meaninglessly, breathless with irrational animal fury and the -need to vent it. - -Without considering what he would do he moved unconciously with -quick, resolute steps toward the crowd. And the nearer he drew to it -the more Alpatych felt that this unreasonable action might produce -good results. The peasants in the crowd were similarly impressed -when they saw Rostov's rapid, firm steps and resolute, frowning face. - -After the hussars had come to the village and Rostov had gone to see -the princess, a certain confusion and dissension had arisen among -the crowd. Some of the peasants said that these new arrivals were -Russians and might take it amiss that the mistress was being detained. -Dron was of this opinion, but as soon as he expressed it Karp and -others attacked their ex-Elder. - -"How many years have you been fattening on the commune?" Karp -shouted at him. "It's all one to you! You'll dig up your pot of -money and take it away with you.... What does it matter to you whether -our homes are ruined or not?" - -"We've been told to keep order, and that no one is to leave their -homes or take away a single grain, and that's all about it!" cried -another. - -"It was your son's turn to be conscripted, but no fear! You -begrudged your lump of a son," a little old man suddenly began -attacking Dron--"and so they took my Vanka to be shaved for a soldier! -But we all have to die." - -"To be sure, we all have to die. I'm not against the commune," -said Dron. - -"That's it--not against it! You've filled your belly...." - -The two tall peasants had their say. As soon as Rostov, followed -by Ilyin, Lavrushka, and Alpatych, came up to the crowd, Karp, -thrusting his fingers into his belt and smiling a little, walked to -the front. Dron on the contrary retired to the rear and the crowd drew -closer together. - -"Who is your Elder here? Hey?" shouted Rostov, coming up to the -crowd with quick steps. - -"The Elder? What do you want with him?..." asked Karp. - -But before the words were well out of his mouth, his cap flew off -and a fierce blow jerked his head to one side. - -"Caps off, traitors!" shouted Rostov in a wrathful voice. "Where's -the Elder?" he cried furiously. - -"The Elder.... He wants the Elder!... Dron Zakharych, you!" meek and -flustered voices here and there were heard calling and caps began to -come off their heads. - -"We don't riot, we're following the orders," declared Karp, and at -that moment several voices began speaking together. - -"It's as the old men have decided--there's too many of you giving -orders." - -"Arguing? Mutiny!... Brigands! Traitors!" cried Rostov unmeaningly -in a voice not his own, gripping Karp by the collar. "Bind him, bind -him!" he shouted, though there was no one to bind him but Lavrushka -and Alpatych. - -Lavrushka, however, ran up to Karp and seized him by the arms from -behind. - -"Shall I call up our men from beyond the hill?" he called out. - -Alpatych turned to the peasants and ordered two of them by name to -come and bind Karp. The men obediently came out of the crowd and began -taking off their belts. - -"Where's the Elder?" demanded Rostov in a loud voice. - -With a pale and frowning face Dron stepped out of the crowd. - -"Are you the Elder? Bind him, Lavrushka!" shouted Rostov, as if that -order, too, could not possibly meet with any opposition. - -And in fact two more peasants began binding Dron, who took off his -own belt and handed it to them, as if to aid them. - -"And you all listen to me!" said Rostov to the peasants. "Be off -to your houses at once, and don't let one of your voices be heard!" - -"Why, we've not done any harm! We did it just out of foolishness. -It's all nonsense... I said then that it was not in order," voices -were heard bickering with one another. - -"There! What did I say?" said Alpatych, coming into his own again. -"It's wrong, lads!" - - "All our stupidity, Yakov Alpatych," came the answers, and the -crowd began at once to disperse through the village. - -The two bound men were led off to the master's house. The two -drunken peasants followed them. - -"Aye, when I look at you!..." said one of them to Karp. - -"How can one talk to the masters like that? What were you thinking -of, you fool?" added the other--"A real fool!" - -Two hours later the carts were standing in the courtyard of the -Bogucharovo house. The peasants were briskly carrying out the -proprietor's goods and packing them on the carts, and Dron, -liberated at Princess Mary's wish from the cupboard where he had -been confined, was standing in the yard directing the men. - -"Don't put it in so carelessly," said one of the peasants, a man -with a round smiling face, taking a casket from a housemaid. "You know -it has cost money! How can you chuck it in like that or shove it under -the cord where it'll get rubbed? I don't like that way of doing -things. Let it all be done properly, according to rule. Look here, put -it under the bast matting and cover it with hay--that's the way!" - -"Eh, books, books!" said another peasant, bringing out Prince -Andrew's library cupboards. "Don't catch up against it! It's heavy, -lads--solid books." - -"Yes, they worked all day and didn't play!" remarked the tall, -round-faced peasant gravely, pointing with a significant wink at the -dictionaries that were on the top. - - -Unwilling to obtrude himself on the princess, Rostov did not go back -to the house but remained in the village awaiting her departure. -When her carriage drove out of the house, he mounted and accompanied -her eight miles from Bogucharovo to where the road was occupied by our -troops. At the inn at Yankovo he respectfully took leave of her, for -the first time permitting himself to kiss her hand. - -"How can you speak so!" he blushingly replied to Princess Mary's -expressions of gratitude for her deliverance, as she termed what had -occurred. "Any police officer would have done as much! If we had had -only peasants to fight, we should not have let the enemy come so far," -said he with a sense of shame and wishing to change the subject. "I am -only happy to have had the opportunity of making your acquaintance. -Good-by, Princess. I wish you happiness and consolation and hope to -meet you again in happier circumstances. If you don't want to make -me blush, please don't thank me!" - -But the princess, if she did not again thank him in words, thanked -him with the whole expression of her face, radiant with gratitude -and tenderness. She could not believe that there was nothing to -thank him for. On the contrary, it seemed to her certain that had he -not been there she would have perished at the hands of the mutineers -and of the French, and that he had exposed himself to terrible and -obvious danger to save her, and even more certain was it that he was a -man of lofty and noble soul, able to understand her position and her -sorrow. His kind, honest eyes, with the tears rising in them when -she herself had begun to cry as she spoke of her loss, did leave her -memory. - -When she had taken leave of him and remained alone she suddenly felt -her eyes filling with tears, and then not for the first time the -strange question presented itself to her: did she love him? - -On the rest of the way to Moscow, though the princess' position -was not a cheerful one, Dunyasha, who went with her in the carriage, -more than once noticed that her mistress leaned out of the window -and smiled at something with an expression of mingled joy and sorrow. - -"Well, supposing I do love him?" thought Princess Mary. - -Ashamed as she was of acknowledging to herself that she had fallen -in love with a man who would perhaps never love her, she comforted -herself with the thought that no one would ever know it and that she -would not be to blame if, without ever speaking of it to anyone, she -continued to the end of her life to love the man with whom she had -fallen in love for the first and last time in her life. - -Sometimes when she recalled his looks, his sympathy, and his -words, happiness did not appear impossible to her. It was at those -moments that Dunyasha noticed her smiling as she looked out of the -carriage window. - -"Was it not fate that brought him to Bogucharovo, and at that very -moment?" thought Princess Mary. "And that caused his sister to -refuse my brother?" And in all this Princess Mary saw the hand of -Providence. - -The impression the princess made on Rostov was a very agreeable one. -To remember her gave him pleasure, and when his comrades, hearing of -his adventure at Bogucharovo, rallied him on having gone to look for -hay and having picked up one of the wealthiest heiresses in Russia, he -grew angry. It made him angry just because the idea of marrying the -gentle Princess Mary, who was attractive to him and had an enormous -fortune, had against his will more than once entered his head. For -himself personally Nicholas could not wish for a better wife: by -marrying her he would make the countess his mother happy, would be -able to put his father's affairs in order, and would even--he felt it- -ensure Princess Mary's happiness. - -But Sonya? And his plighted word? That was why Rostov grew angry -when he was rallied about Princess Bolkonskaya. - - - - - -CHAPTER XV - - -On receiving command of the armies Kutuzov remembered Prince -Andrew and sent an order for him to report at headquarters. - -Prince Andrew arrived at Tsarevo-Zaymishche on the very day and at -the very hour that Kutuzov was reviewing the troops for the first -time. He stopped in the village at the priest's house in front of -which stood the commander in chief's carriage, and he sat down on -the bench at the gate awaiting his Serene Highness, as everyone now -called Kutuzov. From the field beyond the village came now sounds of -regimental music and now the roar of many voices shouting "Hurrah!" to -the new commander in chief. Two orderlies, a courier and a major-domo, -stood near by, some ten paces from Prince Andrew, availing -themselves of Kutuzov's absence and of the fine weather. A short, -swarthy lieutenant colonel of hussars with thick mustaches and -whiskers rode up to the gate and, glancing at Prince Andrew, -inquired whether his Serene Highness was putting up there and -whether he would soon be back. - -Prince Andrew replied that he was not on his Serene Highness' -staff but was himself a new arrival. The lieutenant colonel turned -to a smart orderly, who, with the peculiar contempt with which a -commander in chief's orderly speaks to officers, replied: - -"What? His Serene Highness? I expect he'll be here soon. What do you -want?" - -The lieutenant colonel of hussars smiled beneath his mustache at the -orderly's tone, dismounted, gave his horse to a dispatch runner, and -approached Bolkonski with a slight bow. Bolkonski made room for him on -the bench and the lieutenant colonel sat down beside him. - -"You're also waiting for the commander in chief?" said he. "They say -he weceives evewyone, thank God!... It's awful with those sausage -eaters! Ermolov had weason to ask to be pwomoted to be a German! Now -p'waps Wussians will get a look in. As it was, devil only knows what -was happening. We kept wetweating and wetweating. Did you take part in -the campaign?" he asked. - -"I had the pleasure," replied Prince Andrew, "not only of taking -part in the retreat but of losing in that retreat all I held dear--not -to mention the estate and home of my birth--my father, who died of -grief. I belong to the province of Smolensk." - -"Ah? You're Pwince Bolkonski? Vewy glad to make your acquaintance! -I'm Lieutenant Colonel Denisov, better known as 'Vaska,'" said -Denisov, pressing Prince Andrew's hand and looking into his face -with a particularly kindly attention. "Yes, I heard," said he -sympathetically, and after a short pause added: "Yes, it's Scythian -warfare. It's all vewy well--only not for those who get it in the -neck. So you are Pwince Andwew Bolkonski?" He swayed his head. "Vewy -pleased, Pwince, to make your acquaintance!" he repeated again, -smiling sadly, and he again pressed Prince Andrew's hand. - -Prince Andrew knew Denisov from what Natasha had told him of her -first suitor. This memory carried him sadly and sweetly back to -those painful feelings of which he had not thought lately, but which -still found place in his soul. Of late he had received so many new and -very serious impressions--such as the retreat from Smolensk, his visit -to Bald Hills, and the recent news of his father's death--and had -experienced so many emotions, that for a long time past those memories -had not entered his mind, and now that they did, they did not act on -him with nearly their former strength. For Denisov, too, the -memories awakened by the name of Bolkonski belonged to a distant, -romantic past, when after supper and after Natasha's singing he had -proposed to a little girl of fifteen without realizing what he was -doing. He smiled at the recollection of that time and of his love -for Natasha, and passed at once to what now interested him -passionately and exclusively. This was a plan of campaign he had -devised while serving at the outposts during the retreat. He had -proposed that plan to Barclay de Tolly and now wished to propose it to -Kutuzov. The plan was based on the fact that the French line of -operation was too extended, and it proposed that instead of, or -concurrently with, action on the front to bar the advance of the -French, we should attack their line of communication. He began -explaining his plan to Prince Andrew. - -"They can't hold all that line. It's impossible. I will undertake to -bweak thwough. Give me five hundwed men and I will bweak the line, -that's certain! There's only one way--guewilla warfare!" - -Denisov rose and began gesticulating as he explained his plan to -Bolkonski. In the midst of his explanation shouts were heard from -the army, growing more incoherent and more diffused, mingling with -music and songs and coming from the field where the review was held. -Sounds of hoofs and shouts were nearing the village. - -"He's coming! He's coming!" shouted a Cossack standing at the gate. - -Bolkonski and Denisov moved to the gate, at which a knot of soldiers -(a guard of honor) was standing, and they saw Kutuzov coming down -the street mounted on a rather small sorrel horse. A huge suite of -generals rode behind him. Barclay was riding almost beside him, and -a crowd of officers ran after and around them shouting, "Hurrah!" - -His adjutants galloped into the yard before him. Kutuzov was -impatiently urging on his horse, which ambled smoothly under his -weight, and he raised his hand to his white Horse Guard's cap with a -red band and no peak, nodding his head continually. When he came up to -the guard of honor, a fine set of Grenadiers mostly wearing -decorations, who were giving him the salute, he looked at them -silently and attentively for nearly a minute with the steady gaze of a -commander and then turned to the crowd of generals and officers -surrounding him. Suddenly his face assumed a subtle expression, he -shrugged his shoulders with an air of perplexity. - -"And with such fine fellows to retreat and retreat! Well, good-by, -General," he added, and rode into the yard past Prince Andrew and -Denisov. - -"Hurrah! hurrah! hurrah!" shouted those behind him. - -Since Prince Andrew had last seen him Kutuzov had grown still more -corpulent, flaccid, and fat. But the bleached eyeball, the scar, and -the familiar weariness of his expression were still the same. He was -wearing the white Horse Guard's cap and a military overcoat with a -whip hanging over his shoulder by a thin strap. He sat heavily and -swayed limply on his brisk little horse. - -"Whew... whew... whew!" he whistled just audibly as he rode into the -yard. His face expressed the relief of relaxed strain felt by a man -who means to rest after a ceremony. He drew his left foot out of the -stirrup and, lurching with his whole body and puckering his face -with the effort, raised it with difficulty onto the saddle, leaned -on his knee, groaned, and slipped down into the arms of the Cossacks -and adjutants who stood ready to assist him. - -He pulled himself together, looked round, screwing up his eyes, -glanced at Prince Andrew, and, evidently not recognizing him, moved -with his waddling gait to the porch. "Whew... whew... whew!" he -whistled, and again glanced at Prince Andrew. As often occurs with old -men, it was only after some seconds that the impression produced by -Prince Andrew's face linked itself up with Kutuzov's remembrance of -his personality. - -"Ah, how do you do, my dear prince? How do you do, my dear boy? Come -along..." said he, glancing wearily round, and he stepped onto the -porch which creaked under his weight. - -He unbuttoned his coat and sat down on a bench in the porch. - -"And how's your father?" - -"I received news of his death, yesterday," replied Prince Andrew -abruptly. - -Kutuzov looked at him with eyes wide open with dismay and then -took off his cap and crossed himself: - -"May the kingdom of Heaven be his! God's will be done to us all!" He -sighed deeply, his whole chest heaving, and was silent for a while. "I -loved him and respected him, and sympathize with you with all my -heart." - -He embraced Prince Andrew, pressing him to his fat breast, and for -some time did not let him go. When he released him Prince Andrew saw -that Kutuzov's flabby lips were trembling and that tears were in his -eyes. He sighed and pressed on the bench with both hands to raise -himself. - -"Come! Come with me, we'll have a talk," said he. - -But at that moment Denisov, no more intimidated by his superiors -than by the enemy, came with jingling spurs up the steps of the porch, -despite the angry whispers of the adjutants who tried to stop him. -Kutuzov, his hands still pressed on the seat, glanced at him glumly. -Denisov, having given his name, announced that he had to communicate -to his Serene Highness a matter of great importance for their -country's welfare. Kutuzov looked wearily at him and, lifting his -hands with a gesture of annoyance, folded them across his stomach, -repeating the words: "For our country's welfare? Well, what is it? -Speak!" Denisov blushed like a girl (it was strange to see the color -rise in that shaggy, bibulous, time-worn face) and boldly began to -expound his plan of cutting the enemy's lines of communication between -Smolensk and Vyazma. Denisov came from those parts and knew the -country well. His plan seemed decidedly a good one, especially from -the strength of conviction with which he spoke. Kutuzov looked down at -his own legs, occasionally glancing at the door of the adjoining hut -as if expecting something unpleasant to emerge from it. And from -that hut, while Denisov was speaking, a general with a portfolio under -his arm really did appear. - -"What?" said Kutuzov, in the midst of Denisov's explanations, "are -you ready so soon?" - -"Ready, your Serene Highness," replied the general. - -Kutuzov swayed his head, as much as to say: "How is one man to -deal with it all?" and again listened to Denisov. - -"I give my word of honor as a Wussian officer," said Denisov, -"that I can bweak Napoleon's line of communication!" - -"What relation are you to Intendant General Kiril Andreevich -Denisov?" asked Kutuzov, interrupting him. - -"He is my uncle, your Sewene Highness." - -"Ah, we were friends," said Kutuzov cheerfully. "All right, all -right, friend, stay here at the staff and tomorrow we'll have a talk." - -With a nod to Denisov he turned away and put out his hand for the -papers Konovnitsyn had brought him. - -"Would not your Serene Highness like to come inside?" said the -general on duty in a discontented voice, "the plans must be examined -and several papers have to be signed." - -An adjutant came out and announced that everything was in -readiness within. But Kutuzov evidently did not wish to enter that -room till he was disengaged. He made a grimace... - -"No, tell them to bring a small table out here, my dear boy. I'll -look at them here," said he. "Don't go away," he added, turning to -Prince Andrew, who remained in the porch and listened to the general's -report. - -While this was being given, Prince Andrew heard the whisper of a -woman's voice and the rustle of a silk dress behind the door. -Several times on glancing that way he noticed behind that door a -plump, rosy, handsome woman in a pink dress with a lilac silk kerchief -on her head, holding a dish and evidently awaiting the entrance of the -commander in chief. Kutuzov's adjutant whispered to Prince Andrew -that this was the wife of the priest whose home it was, and that she -intended to offer his Serene Highness bread and salt. "Her husband has -welcomed his Serene Highness with the cross at the church, and she -intends to welcome him in the house.... She's very pretty," added -the adjutant with a smile. At those words Kutuzov looked round. He was -listening to the general's report--which consisted chiefly of a -criticism of the position at Tsarevo-Zaymishche--as he had listened to -Denisov, and seven years previously had listened to the discussion -at the Austerlitz council of war. He evidently listened only because -he had ears which, though there was a piece of tow in one of them, -could not help hearing; but it was evident that nothing the general -could say would surprise or even interest him, that he knew all that -would be said beforehand, and heard it all only because he had to, -as one has to listen to the chanting of a service of prayer. All -that Denisov had said was clever and to the point. What the general -was saying was even more clever and to the point, but it was evident -that Kutuzov despised knowledge and cleverness, and knew of -something else that would decide the matter--something independent -of cleverness and knowledge. Prince Andrew watched the commander -in chief's face attentively, and the only expression he could see -there was one of boredom, curiosity as to the meaning of the -feminine whispering behind the door, and a desire to observe -propriety. It was evident that Kutuzov despised cleverness and -learning and even the patriotic feeling shown by Denisov, but despised -them not because of his own intellect, feelings, or knowledge--he -did not try to display any of these--but because of something else. He -despised them because of his old age and experience of life. The -only instruction Kutuzov gave of his own accord during that report -referred to looting by the Russian troops. At the end of the report -the general put before him for signature a paper relating to the -recovery of payment from army commanders for green oats mown down by -the soldiers, when landowners lodged petitions for compensation. - -After hearing the matter, Kutuzov smacked his lips together and -shook his head. - -"Into the stove... into the fire with it! I tell you once for all, -my dear fellow," said he, "into the fire with all such things! Let -them cut the crops and burn wood to their hearts' content. I don't -order it or allow it, but I don't exact compensation either. One can't -get on without it. 'When wood is chopped the chips will fly.'" He -looked at the paper again. "Oh, this German precision!" he muttered, -shaking his head. - - - - - -CHAPTER XVI - - -"Well, that's all!" said Kutuzov as he signed the last of the -documents, and rising heavily and smoothing out the folds in his fat -white neck he moved toward the door with a more cheerful expression. - -The priest's wife, flushing rosy red, caught up the dish she had -after all not managed to present at the right moment, though she had -so long been preparing for it, and with a low bow offered it to -Kutuzov. - -He screwed up his eyes, smiled, lifted her chin with his hand, and -said: - -"Ah, what a beauty! Thank you, sweetheart!" - -He took some gold pieces from his trouser pocket and put them on the -dish for her. "Well, my dear, and how are we getting on?" he asked, -moving to the door of the room assigned to him. The priest's wife -smiled, and with dimples in her rosy cheeks followed him into the -room. The adjutant came out to the porch and asked Prince Andrew to -lunch with him. Half an hour later Prince Andrew was again called to -Kutuzov. He found him reclining in an armchair, still in the same -unbuttoned overcoat. He had in his hand a French book which he -closed as Prince Andrew entered, marking the place with a knife. -Prince Andrew saw by the cover that it was Les Chevaliers du Cygne -by Madame de Genlis. - -"Well, sit down, sit down here. Let's have a talk," said Kutuzov. -"It's sad, very sad. But remember, my dear fellow, that I am a -father to you, a second father...." - -Prince Andrew told Kutuzov all he knew of his father's death, and -what he had seen at Bald Hills when he passed through it. - -"What... what they have brought us to!" Kutuzov suddenly cried in an -agitated voice, evidently picturing vividly to himself from Prince -Andrew's story the condition Russia was in. "But give me time, give me -time!" he said with a grim look, evidently not wishing to continue -this agitating conversation, and added: "I sent for you to keep you -with me." - -"I thank your Serene Highness, but I fear I am no longer fit for the -staff," replied Prince Andrew with a smile which Kutuzov noticed. - -Kutuzov glanced inquiringly at him. - -"But above all," added Prince Andrew, "I have grown used to my -regiment, am fond of the officers, and I fancy the men also like me. I -should be sorry to leave the regiment. If I decline the honor of being -with you, believe me..." - -A shrewd, kindly, yet subtly derisive expression lit up Kutuzov's -podgy face. He cut Bolkonski short. - -"I am sorry, for I need you. But you're right, you're right! It's -not here that men are needed. Advisers are always plentiful, but men -are not. The regiments would not be what they are if the would-be -advisers served there as you do. I remember you at Austerlitz.... I -remember, yes, I remember you with the standard!" said Kutuzov, and -a flush of pleasure suffused Prince Andrew's face at this -recollection. - -Taking his hand and drawing him downwards, Kutuzov offered his cheek -to be kissed, and again Prince Andrew noticed tears in the old man's -eyes. Though Prince Andrew knew that Kutuzov's tears came easily, -and that he was particularly tender to and considerate of him from a -wish to show sympathy with his loss, yet this reminder of Austerlitz -was both pleasant and flattering to him. - -"Go your way and God be with you. I know your path is the path of -honor!" He paused. "I missed you at Bucharest, but I needed someone to -send." And changing the subject, Kutuzov began to speak of the Turkish -war and the peace that had been concluded. "Yes, I have been much -blamed," he said, "both for that war and the peace... but everything -came at the right time. Tout vient a point a celui qui sait attendre.* -And there were as many advisers there as here..." he went on, -returning to the subject of "advisers" which evidently occupied him. -"Ah, those advisers!" said he. "If we had listened to them all we -should not have made peace with Turkey and should not have been -through with that war. Everything in haste, but more haste, less -speed. Kamenski would have been lost if he had not died. He stormed -fortresses with thirty thousand men. It is not difficult to capture -a fortress but it is difficult to win a campaign. For that, storming -and attacking but patience and time are wanted. Kamenski sent soldiers -to Rustchuk, but I only employed these two things and took more -fortresses than Kamenski and made them but eat horseflesh!" He swayed -his head. "And the French shall too, believe me," he went on, -growing warmer and beating his chest, "I'll make them eat horseflesh!" -And tears again dimmed his eyes. - - -*"Everything comes in time to him who knows how to wait." - - -"But shan't we have to accept battle?" remarked Prince Andrew. - -"We shall if everybody wants it; it can't be helped.... But -believe me, my dear boy, there is nothing stronger than those two: -patience and time, they will do it all. But the advisers n'entendent -pas de cette oreille, voila le mal.* Some want a thing--others -don't. What's one to do?" he asked, evidently expecting an answer. -"Well, what do you want us to do?" he repeated and his eye shone -with a deep, shrewd look. "I'll tell you what to do," he continued, as -Prince Andrew still did not reply: "I will tell you what to do, and -what I do. Dans le doute, mon cher," he paused, "abstiens-toi"*[2]--he -articulated the French proverb deliberately. - - -*"Don't see it that way, that's the trouble." - -*[2] "When in doubt, my dear fellow, do nothing." - - -"Well, good-by, my dear fellow; remember that with all my heart I -share your sorrow, and that for you I am not a Serene Highness, nor -a prince, nor a commander in chief, but a father! If you want anything -come straight to me. Good-by, my dear boy." - -Again he embraced and kissed Prince Andrew, but before the latter -had left the room Kutuzov gave a sigh of relief and went on with his -unfinished novel, Les Chevaliers du Cygne by Madame de Genlis. - -Prince Andrew could not have explained how or why it was, but -after that interview with Kutuzov he went back to his regiment -reassured as to the general course of affairs and as to the man to -whom it had been entrusted. The more he realized the absence of all -personal motive in that old man--in whom there seemed to remain only -the habit of passions, and in place of an intellect (grouping events -and drawing conclusions) only the capacity calmly to contemplate the -course of events--the more reassured he was that everything would be -as it should. "He will not bring in any plan of his own. He will not -devise or undertake anything," thought Prince Andrew, "but he will -hear everything, remember everything, and put everything in its place. -He will not hinder anything useful nor allow anything harmful. He -understands that there is something stronger and more important than -his own will--the inevitable course of events, and he can see them and -grasp their significance, and seeing that significance can refrain -from meddling and renounce his personal wish directed to something -else. And above all," thought Prince Andrew, "one believes in him -because he's Russian, despite the novel by Genlis and the French -proverbs, and because his voice shook when he said: 'What they have -brought us to!' and had a sob in it when he said he would 'make them -eat horseflesh!'" - -On such feelings, more or less dimly shared by all, the unanimity -and general approval were founded with which, despite court -influences, the popular choice of Kutuzov as commander in chief was -received. - - - - - -CHAPTER XVII - - -After the Emperor had left Moscow, life flowed on there in its usual -course, and its course was so very usual that it was difficult to -remember the recent days of patriotic elation and ardor, hard to -believe that Russia was really in danger and that the members of the -English Club were also sons of the Fatherland ready to sacrifice -everything for it. The one thing that recalled the patriotic fervor -everyone had displayed during the Emperor's stay was the call for -contributions of men and money, a necessity that as soon as the -promises had been made assumed a legal, official form and became -unavoidable. - -With the enemy's approach to Moscow, the Moscovites' view of their -situation did not grow more serious but on the contrary became even -more frivolous, as always happens with people who see a great danger -approaching. At the approach of danger there are always two voices -that speak with equal power in the human soul: one very reasonably -tells a man to consider the nature of the danger and the means of -escaping it; the other, still more reasonably, says that it is too -depressing and painful to think of the danger, since it is not in -man's power to foresee everything and avert the general course of -events, and it is therefore better to disregard what is painful till -it comes, and to think about what is pleasant. In solitude a man -generally listens to the first voice, but in society to the second. So -it was now with the inhabitants of Moscow. It was long since people -had been as gay in Moscow as that year. - -Rostopchin's broadsheets, headed by woodcuts of a drink shop, a -potman, and a Moscow burgher called Karpushka Chigirin, "who--having -been a militiaman and having had rather too much at the pub--heard -that Napoleon wished to come to Moscow, grew angry, abused the -French in very bad language, came out of the drink shop, and, under -the sign of the eagle, began to address the assembled people," were -read and discussed, together with the latest of Vasili Lvovich -Pushkin's bouts rimes. - -In the corner room at the Club, members gathered to read these -broadsheets, and some liked the way Karpushka jeered at the French, -saying: "They will swell up with Russian cabbage, burst with our -buckwheat porridge, and choke themselves with cabbage soup. They are -all dwarfs and one peasant woman will toss three of them with a -hayfork." Others did not like that tone and said it was stupid and -vulgar. It was said that Rostopchin had expelled all Frenchmen and -even all foreigners from Moscow, and that there had been some spies -and agents of Napoleon among them; but this was told chiefly to -introduce Rostopchin's witty remark on that occasion. The foreigners -were deported to Nizhni by boat, and Rostopchin had said to them in -French: "Rentrez en vousmemes; entrez dans la barque, et n'en faites -pas une barque de Charon."* There was talk of all the government -offices having been already removed from Moscow, and to this -Shinshin's witticism was added--that for that alone Moscow ought to be -grateful to Napoleon. It was said that Mamonov's regiment would cost -him eight hundred thousand rubles, and that Bezukhov had spent even -more on his, but that the best thing about Bezukhov's action was -that he himself was going to don a uniform and ride at the head of his -regiment without charging anything for the show. - - -*"Think it over; get into the barque, and take care not to make it a -barque of Charon." - - -"You don't spare anyone," said Julie Drubetskaya as she collected -and pressed together a bunch of raveled lint with her thin, beringed -fingers. - -Julie was preparing to leave Moscow next day and was giving a -farewell soiree. - -"Bezukhov est ridicule, but he is so kind and good-natured. What -pleasure is there to be so caustique?" - -"A forfeit!" cried a young man in militia uniform whom Julie -called "mon chevalier," and who was going with her to Nizhni. - -In Julie's set, as in many other circles in Moscow, it had been -agreed that they would speak nothing but Russian and that those who -made a slip and spoke French should pay fines to the Committee of -Voluntary Contributions. - -"Another forfeit for a Gallicism," said a Russian writer who was -present. "'What pleasure is there to be' is not Russian!" - -"You spare no one," continued Julie to the young man without heeding -the author's remark. - -"For caustique--I am guilty and will pay, and I am prepared to pay -again for the pleasure of telling you the truth. For Gallicisms I -won't be responsible," she remarked, turning to the author: "I have -neither the money nor the time, like Prince Galitsyn, to engage a -master to teach me Russian!" - -"Ah, here he is!" she added. "Quand on... No, no," she said to the -militia officer, "you won't catch me. Speak of the sun and you see its -rays!" and she smiled amiably at Pierre. "We were just talking of -you," she said with the facility in lying natural to a society -woman. "We were saying that your regiment would be sure to be better -than Mamonov's." - -"Oh, don't talk to me of my regiment," replied Pierre, kissing his -hostess' hand and taking a seat beside her. "I am so sick of it." - -"You will, of course, command it yourself?" said Julie, directing -a sly, sarcastic glance toward the militia officer. - -The latter in Pierre's presence had ceased to be caustic, and his -face expressed perplexity as to what Julie's smile might mean. In -spite of his absent-mindedness and good nature, Pierre's personality -immediately checked any attempt to ridicule him to his face. - -"No," said Pierre, with a laughing glance at his big, stout body. "I -should make too good a target for the French, besides I am afraid I -should hardly be able to climb onto a horse." - -Among those whom Julie's guests happened to choose to gossip about -were the Rostovs. - -"I hear that their affairs are in a very bad way," said Julie. -"And he is so unreasonable, the count himself I mean. The -Razumovskis wanted to buy his house and his estate near Moscow, but it -drags on and on. He asks too much." - -"No, I think the sale will come off in a few days," said someone. -"Though it is madness to buy anything in Moscow now." - -"Why?" asked Julie. "You don't think Moscow is in danger?" - -"Then why are you leaving?" - -"I? What a question! I am going because... well, because everyone is -going: and besides--I am not Joan of Arc or an Amazon." - -"Well, of course, of course! Let me have some more strips of linen." - -"If he manages the business properly he will be able to pay off -all his debts," said the militia officer, speaking of Rostov. - -"A kindly old man but not up to much. And why do they stay on so -long in Moscow? They meant to leave for the country long ago. -Natalie is quite well again now, isn't she?" Julie asked Pierre with a -knowing smile. - -"They are waiting for their younger son," Pierre replied. "He joined -Obolenski's Cossacks and went to Belaya Tserkov where the regiment -is being formed. But now they have had him transferred to my -regiment and are expecting him every day. The count wanted to leave -long ago, but the countess won't on any account leave Moscow till -her son returns." - -"I met them the day before yesterday at the Arkharovs'. Natalie -has recovered her looks and is brighter. She sang a song. How easily -some people get over everything!" - -"Get over what?" inquired Pierre, looking displeased. - -Julie smiled. - -"You know, Count, such knights as you are only found in Madame de -Souza's novels." - -"What knights? What do you mean?" demanded Pierre, blushing. - -"Oh, come, my dear count! C'est la fable de tout Moscou. Je vous -admire, ma parole d'honneur!"* - - -*"It is the talk of all Moscow. My word, I admire you!" - - -"Forfeit, forfeit!" cried the militia officer. - -"All right, one can't talk--how tiresome!" - -"What is 'the talk of all Moscow'?" Pierre asked angrily, rising -to his feet. - -"Come now, Count, you know!" - -"I don't know anything about it," said Pierre. - -"I know you were friendly with Natalie, and so... but I was always -more friendly with Vera--that dear Vera." - -"No, madame!" Pierre continued in a tone of displeasure, "I have not -taken on myself the role of Natalie Rostova's knight at all, and -have not been their house for nearly a month. But I cannot -understand the cruelty..." - -"Qui s'excuse s'accuse,"* said Julie, smiling and waving the lint -triumphantly, and to have the last word she promptly changed the -subject. "Do you know what I heard today? Poor Mary Bolkonskaya -arrived in Moscow yesterday. Do you know that she has lost her -father?" - - -*"Who excuses himself, accuses himself." - - -"Really? Where is she? I should like very much to see her," said -Pierre. - -"I spent the evening with her yesterday. She is going to their -estate near Moscow either today or tomorrow morning, with her nephew." - -"Well, and how is she?" asked Pierre. - -"She is well, but sad. But do you know who rescued her? It is -quite a romance. Nicholas Rostov! She was surrounded, and they -wanted to kill her and had wounded some of her people. He rushed in -and saved her...." - -"Another romance," said the militia officer. "Really, this general -flight has been arranged to get all the old maids married off. Catiche -is one and Princess Bolkonskaya another." - -"Do you know, I really believe she is un petit peu amoureuse du -jeune homme."* - - -*"A little bit in love with the young man." - - -"Forfeit, forfeit, forfeit!" - -"But how could one say that in Russian?" - - - - - -CHAPTER XVIII - - -When Pierre returned home he was handed two of Rostopchin's -broadsheets that had been brought that day. - -The first declared that the report that Count Rostopchin had -forbidden people to leave Moscow was false; on the contrary he was -glad that ladies and tradesmen's wives were leaving the city. "There -will be less panic and less gossip," ran the broadsheet "but I will -stake my life on it that that will not enter Moscow." These words -showed Pierre clearly for the first time that the French would enter -Moscow. The second broadsheet stated that our headquarters were at -Vyazma, that Count Wittgenstein had defeated the French, but that as -many of the inhabitants of Moscow wished to be armed, weapons were -ready for them at the arsenal: sabers, pistols, and muskets which -could be had at a low price. The tone of the proclamation was not as -jocose as in the former Chigirin talks. Pierre pondered over these -broadsheets. Evidently the terrible stormcloud he had desired with the -whole strength of his soul but which yet aroused involuntary horror in -him was drawing near. - -"Shall I join the army and enter the service, or wait?" he asked -himself for the hundredth time. He took a pack of cards that lay on -the table and began to lay them out for a game of patience. - -"If this patience comes out," he said to himself after shuffling the -cards, holding them in his hand, and lifting his head, "if it comes -out, it means... what does it mean?" - -He had not decided what it should mean when he heard the voice of -the eldest princess at the door asking whether she might come in. - -"Then it will mean that I must go to the army," said Pierre to -himself. "Come in, come in!" he added to the princess. - -Only the eldest princess, the one with the stony face and long -waist, was still living in Pierre's house. The two younger ones had -both married. - -"Excuse my coming to you, cousin," she said in a reproachful and -agitated voice. "You know some decision must be come to. What is going -to happen? Everyone has left Moscow and the people are rioting. How is -it that we are staying on?" - -"On the contrary, things seem satisfactory, ma cousine," said Pierre -in the bantering tone he habitually adopted toward her, always feeling -uncomfortable in the role of her benefactor. - -"Satisfactory, indeed! Very satisfactory! Barbara Ivanovna told me -today how our troops are distinguishing themselves. It certainly -does them credit! And the people too are quite mutinous--they no -longer obey, even my maid has taken to being rude. At this rate they -will soon begin beating us. One can't walk in the streets. But, -above all, the French will be here any day now, so what are we waiting -for? I ask just one thing of you, cousin," she went on, "arrange for -me to be taken to Petersburg. Whatever I may be, I can't live under -Bonaparte's rule." - -"Oh, come, ma cousine! Where do you get your information from? On -the contrary..." - -"I won't submit to your Napoleon! Others may if they please.... If -you don't want to do this..." - -"But I will, I'll give the order at once." - -The princess was apparently vexed at not having anyone to be angry -with. Muttering to herself, she sat down on a chair. - -"But you have been misinformed," said Pierre. "Everything is quiet -in the city and there is not the slightest danger. See! I've just been -reading..." He showed her the broadsheet. "Count Rostopchin writes -that he will stake his life on it that the enemy will not enter -Moscow." - -"Oh, that count of yours!" said the princess malevolently. "He is -a hypocrite, a rascal who has himself roused the people to riot. -Didn't he write in those idiotic broadsheets that anyone, 'whoever -it might be, should be dragged to the lockup by his hair'? (How -silly!) 'And honor and glory to whoever captures him,' he says. This -is what his cajolery has brought us to! Barbara Ivanovna told me the -mob near killed her because she said something in French." - -"Oh, but it's so... You take everything so to heart," said Pierre, -and began laying out his cards for patience. - -Although that patience did come out, Pierre did not join the army, -but remained in deserted Moscow ever in the same state of agitation, -irresolution, and alarm, yet at the same time joyfully expecting -something terrible. - -Next day toward evening the princess set off, and Pierre's head -steward came to inform him that the money needed for the equipment -of his regiment could not be found without selling one of the estates. -In general the head steward made out to Pierre that his project of -raising a regiment would ruin him. Pierre listened to him, scarcely -able to repress a smile. - -"Well then, sell it," said he. "What's to be done? I can't draw back -now!" - -The worse everything became, especially his own affairs, the -better was Pierre pleased and the more evident was it that the -catastrophe he expected was approaching. Hardly anyone he knew was -left in town. Julie had gone, and so had Princess Mary. Of his -intimate friends only the Rostovs remained, but he did not go to see -them. - -To distract his thoughts he drove that day to the village of -Vorontsovo to see the great balloon Leppich was constructing to -destroy the foe, and a trial balloon that was to go up next day. The -balloon was not yet ready, but Pierre learned that it was being -constructed by the Emperor's desire. The Emperor had written to -Count Rostopchin as follows: - - -As soon as Leppich is ready, get together a crew of reliable and -intelligent men for his car and send a courier to General Kutuzov to -let him know. I have informed him of the matter. - -Please impress upon Leppich to be very careful where he descends for -the first time, that he may not make a mistake and fall into the -enemy's hands. It is essential for him to combine his movements with -those of the commander in chief. - - -On his way home from Vorontsovo, as he was passing the Bolotnoe -Place Pierre, seeing a large crowd round the Lobnoe Place, stopped and -got out of his trap. A French cook accused of being a spy was being -flogged. The flogging was only just over, and the executioner was -releasing from the flogging bench a stout man with red whiskers, in -blue stockings and a green jacket, who was moaning piteously. -Another criminal, thin and pale, stood near. Judging by their faces -they were both Frenchmen. With a frightened and suffering look -resembling that on the thin Frenchman's face, Pierre pushed his way in -through the crowd. - -"What is it? Who is it? What is it for?" he kept asking. - -But the attention of the crowd--officials, burghers, shopkeepers, -peasants, and women in cloaks and in pelisses--was so eagerly centered -on what was passing in Lobnoe Place that no one answered him. The -stout man rose, frowned, shrugged his shoulders, and evidently -trying to appear firm began to pull on his jacket without looking -about him, but suddenly his lips trembled and he began to cry, in -the way full-blooded grown-up men cry, though angry with himself for -doing so. In the crowd people began talking loudly, to stifle their -feelings of pity as it seemed to Pierre. - -"He's cook to some prince." - -"Eh, mounseer, Russian sauce seems to be sour to a Frenchman... sets -his teeth on edge!" said a wrinkled clerk who was standing behind -Pierre, when the Frenchman began to cry. - -The clerk glanced round, evidently hoping that his joke would be -appreciated. Some people began to laugh, others continued to watch -in dismay the executioner who was undressing the other man. - -Pierre choked, his face puckered, and he turned hastily away, went -back to his trap muttering something to himself as he went, and took -his seat. As they drove along he shuddered and exclaimed several times -so audibly that the coachman asked him: - -"What is your pleasure?" - -"Where are you going?" shouted Pierre to the man, who was driving to -Lubyanka Street. - -"To the Governor's, as you ordered," answered the coachman. - -"Fool! Idiot!" shouted Pierre, abusing his coachman--a thing he -rarely did. "Home, I told you! And drive faster, blockhead!" "I must -get away this very day," he murmured to himself. - -At the sight of the tortured Frenchman and the crowd surrounding the -Lobnoe Place, Pierre had so definitely made up his mind that he -could no longer remain in Moscow and would leave for the army that -very day that it seemed to him that either he had told the coachman -this or that the man ought to have known it for himself. - -On reaching home Pierre gave orders to Evstafey--his head coachman -who knew everything, could do anything, and was known to all Moscow- -that he would leave that night for the army at Mozhaysk, and that -his saddle horses should be sent there. This could not all be arranged -that day, so on Evstafey's representation Pierre had to put off his -departure till next day to allow time for the relay horses to be -sent on in advance. - -On the twenty-fourth the weather cleared up after a spell of rain, -and after dinner Pierre left Moscow. When changing horses that night -in Perkhushkovo, he learned that there had been a great battle that -evening. (This was the battle of Shevardino.) He was told that there -in Perkhushkovo the earth trembled from the firing, but nobody could -answer his questions as to who had won. At dawn next day Pierre was -approaching Mozhaysk. - -Every house in Mozhaysk had soldiers quartered in it, and at the -hostel where Pierre was met by his groom and coachman there was no -room to be had. It was full of officers. - -Everywhere in Mozhaysk and beyond it, troops were stationed or on -the march. Cossacks, foot and horse soldiers, wagons, caissons, and -cannon were everywhere. Pierre pushed forward as fast as he could, and -the farther he left Moscow behind and the deeper he plunged into -that sea of troops the more was he overcome by restless agitation -and a new and joyful feeling he had not experienced before. It was a -feeling akin to what he had felt at the Sloboda Palace during the -Emperor's visit--a sense of the necessity of undertaking something and -sacrificing something. He now experienced a glad consciousness that -everything that constitutes men's happiness--the comforts of life, -wealth, even life itself--is rubbish it is pleasant to throw away, -compared with something... With what? Pierre could not say, and he did -not try to determine for whom and for what he felt such particular -delight in sacrificing everything. He was not occupied with the -question of what to sacrifice for; the fact of sacrificing in itself -afforded him a new and joyous sensation. - - - - - -CHAPTER XIX - - -On the twenty-fourth of August the battle of the Shevardino -Redoubt was fought, on the twenty-fifth not a shot was fired by either -side, and on the twenty-sixth the battle of Borodino itself took -place. - -Why and how were the battles of Shevardino and Borodino given and -accepted? Why was the battle of Borodino fought? There was not the -least sense in it for either the French or the Russians. Its immediate -result for the Russians was, and was bound to be, that we were brought -nearer to the destruction of Moscow--which we feared more than -anything in the world; and for the French its immediate result was -that they were brought nearer to the destruction of their whole -army--which they feared more than anything in the world. What the -result must be was quite obvious, and yet Napoleon offered and Kutuzov -accepted that battle. - -If the commanders had been guided by reason, it would seem that it -must have been obvious to Napoleon that by advancing thirteen -hundred miles and giving battle with a probability of losing a quarter -of his army, he was advancing to certain destruction, and it must have -been equally clear to Kutuzov that by accepting battle and risking the -loss of a quarter of his army he would certainly lose Moscow. For -Kutuzov this was mathematically clear, as it is that if when playing -draughts I have one man less and go on exchanging, I shall certainly -lose, and therefore should not exchange. When my opponent has -sixteen men and I have fourteen, I am only one eighth weaker than -he, but when I have exchanged thirteen more men he will be three times -as strong as I am. - -Before the battle of Borodino our strength in proportion to the -French was about as five to six, but after that battle it was little -more than one to two: previously we had a hundred thousand against a -hundred and twenty thousand; afterwards little more than fifty -thousand against a hundred thousand. Yet the shrewd and experienced -Kutuzov accepted the battle, while Napoleon, who was said to be a -commander of genius, gave it, losing a quarter of his army and -lengthening his lines of communication still more. If it is said -that he expected to end the campaign by occupying Moscow as he had -ended a previous campaign by occupying Vienna, there is much -evidence to the contrary. Napoleon's historians themselves tell us -that from Smolensk onwards he wished to stop, knew the danger of his -extended position, and knew that the occupation of Moscow would not be -the end of the campaign, for he had seen at Smolensk the state in -which Russian towns were left to him, and had not received a single -reply to his repeated announcements of his wish to negotiate. - -In giving and accepting battle at Borodino, Kutuzov acted -involuntarily and irrationally. But later on, to fit what had -occurred, the historians provided cunningly devised evidence of the -foresight and genius the generals who, of all the blind tools of -history were the most enslaved and involuntary. - -The ancients have left us model heroic poems in which the heroes -furnish the whole interest of the story, and we are still unable to -accustom ourselves to the fact that for our epoch histories of that -kind are meaningless. - -On the other question, how the battle of Borodino and the -preceding battle of Shevardino were fought, there also exists a -definite and well-known, but quite false, conception. All the -historians describe the affair as follows: - -The Russian army, they say, in its retreat from Smolensk sought -out for itself the best position for a general engagement and found -such a position at Borodino. - -The Russians, they say, fortified this position in advance on the -left of the highroad (from Moscow to Smolensk) and almost at a right -angle to it, from Borodino to Utitsa, at the very place where the -battle was fought. - -In front of this position, they say, a fortified outpost was set -up on the Shevardino mound to observe the enemy. On the twenty-fourth, -we are told, Napoleon attacked this advanced post and took it, and, on -the twenty-sixth, attacked the whole Russian army, which was in -position on the field of Borodino. - -So the histories say, and it is all quite wrong, as anyone who cares -to look into the matter can easily convince himself. - -The Russians did not seek out the best position but, on the -contrary, during the retreat passed many positions better than -Borodino. They did not stop at any one of these positions because -Kutuzov did not wish to occupy a position he had not himself chosen, -because the popular demand for a battle had not yet expressed itself -strongly enough, and because Miloradovich had not yet arrived with the -militia, and for many other reasons. The fact is that other -positions they had passed were stronger, and that the position at -Borodino (the one where the battle was fought), far from being strong, -was no more a position than any other spot one might find in the -Russian Empire by sticking a pin into the map at hazard. - -Not only did the Russians not fortify the position on the field of -Borodino to the left of, and at a right angle to, the highroad (that -is, the position on which the battle took place), but never till the -twenty-fifth of August, 1812, did they think that a battle might be -fought there. This was shown first by the fact that there were no -entrenchments there by the twenty fifth and that those begun on the -twenty-fifth and twenty-sixth were not completed, and secondly, by the -position of the Shevardino Redoubt. That redoubt was quite senseless -in front of the position where the battle was accepted. Why was it -more strongly fortified than any other post? And why were all -efforts exhausted and six thousand men sacrificed to defend it till -late at night on the twenty-fourth? A Cossack patrol would have -sufficed to observe the enemy. Thirdly, as proof that the position -on which the battle was fought had not been foreseen and that the -Shevardino Redoubt was not an advanced post of that position, we -have the fact that up to the twenty-fifth, Barclay de Tolly and -Bagration were convinced that the Shevardino Redoubt was the left -flank of the position, and that Kutuzov himself in his report, written -in hot haste after the battle, speaks of the Shevardino Redoubt as the -left flank of the position. It was much later, when reports on the -battle of Borodino were written at leisure, that the incorrect and -extraordinary statement was invented (probably to justify the mistakes -of a commander in chief who had to be represented as infallible) -that the Shevardino Redoubt was an advanced post--whereas in reality -it was simply a fortified point on the left flank--and that the battle -of Borodino was fought by us on an entrenched position previously -selected, where as it was fought on a quite unexpected spot which -was almost unentrenched. - -The case was evidently this: a position was selected along the river -Kolocha--which crosses the highroad not at a right angle but at an -acute angle--so that the left flank was at Shevardino, the right flank -near the village of Novoe, and the center at Borodino at the -confluence of the rivers Kolocha and Voyna. - -To anyone who looks at the field of Borodino without thinking of how -the battle was actually fought, this position, protected by the -river Kolocha, presents itself as obvious for an army whose object was -to prevent an enemy from advancing along the Smolensk road to Moscow. - -Napoleon, riding to Valuevo on the twenty-fourth, did not see (as -the history books say he did) the position of the Russians from Utitsa -to Borodino (he could not have seen that position because it did not -exist), nor did he see an advanced post of the Russian army, but while -pursuing the Russian rearguard he came upon the left flank of the -Russian position--at the Shevardino Redoubt--and unexpectedly for -the Russians moved his army across the Kolocha. And the Russians, -not having time to begin a general engagement, withdrew their left -wing from the position they had intended to occupy and took up a new -position which had not been foreseen and was not fortified. By -crossing to the other side of the Kolocha to the left of the highroad, -Napoleon shifted the whole forthcoming battle from right to left -(looking from the Russian side) and transferred it to the plain -between Utitsa, Semenovsk, and Borodino--a plain no more -advantageous as a position than any other plain in Russia--and there -the whole battle of the twenty-sixth of August took place. - -Had Napoleon not ridden out on the evening of the twenty-fourth to -the Kolocha, and had he not then ordered an immediate attack on the -redoubt but had begun the attack next morning, no one would have -doubted that the Shevardino Redoubt was the left flank of our and -the battle would have taken place where we expected it. In that case -we should probably have defended the Shevardino Redoubt--our left -flank--still more obstinately. We should have attacked Napoleon in the -center or on the right, and the engagement would have taken place on -the twenty-fifth, in the position we intended and had fortified. But -as the attack on our left flank took place in the evening after the -retreat of our rear guard (that is, immediately after the fight at -Gridneva), and as the Russian commanders did not wish, or were not -in time, to begin a general engagement then on the evening of the -twenty-fourth, the first and chief action of the battle of Borodino -was already lost on the twenty-fourth, and obviously led to the loss -of the one fought on the twenty-sixth. - -After the loss of the Shevardino Redoubt, we found ourselves on -the morning of the twenty-fifth without a position for our left flank, -and were forced to bend it back and hastily entrench it where it -chanced to be. - -Not only was the Russian army on the twenty-sixth defended by -weak, unfinished entrenchments, but the disadvantage of that -position was increased by the fact that the Russian commanders--not -having fully realized what had happened, namely the loss of our -position on the left flank and the shifting of the whole field of -the forthcoming battle from right to left--maintained their extended -position from the village of Novoe to Utitsa, and consequently had -to move their forces from right to left during the battle. So it -happened that throughout the whole battle the Russians opposed the -entire French army launched against our left flank with but half as -many men. (Poniatowski's action against Utitsa, and Uvarov's on the -right flank against the French, were actions distinct from the main -course of the battle.) So the battle of Borodino did not take place at -all as (in an effort to conceal our commanders' mistakes even at the -cost of diminishing the glory due to the Russian army and people) it -has been described. The battle of Borodino was not fought on a -chosen and entrenched position with forces only slightly weaker than -those of the enemy, but, as a result of the loss of the Shevardino -Redoubt, the Russians fought the battle of Borodino on an open and -almost unentrenched position, with forces only half as numerous as the -French; that is to say, under conditions in which it was not merely -unthinkable to fight for ten hours and secure an indecisive result, -but unthinkable to keep an army even from complete disintegration -and flight. - - - - - -CHAPTER XX - - -On the morning of the twenty-fifth Pierre was leaving Mozhaysk. At -the descent of the high steep hill, down which a winding road led -out of the town past the cathedral on the right, where a service was -being held and the bells were ringing, Pierre got out of his vehicle -and proceeded on foot. Behind him a cavalry regiment was coming down -the hill preceded by its singers. Coming up toward him was a train -of carts carrying men who had been wounded in the engagement the day -before. The peasant drivers, shouting and lashing their horses, kept -crossing from side to side. The carts, in each of which three or -four wounded soldiers were lying or sitting, jolted over the stones -that had been thrown on the steep incline to make it something like -a road. The wounded, bandaged with rags, with pale cheeks, -compressed lips, and knitted brows, held on to the sides of the -carts as they were jolted against one another. Almost all of them -stared with naive, childlike curiosity at Pierre's white hat and green -swallow-tail coat. - -Pierre's coachman shouted angrily at the convoy of wounded to keep -to one side of the road. The cavalry regiment, as it descended the -hill with its singers, surrounded Pierre's carriage and blocked the -road. Pierre stopped, being pressed against the side of the cutting in -which the road ran. The sunshine from behind the hill did not -penetrate into the cutting and there it was cold and damp, but above -Pierre's head was the bright August sunshine and the bells sounded -merrily. One of the carts with wounded stopped by the side of the road -close to Pierre. The driver in his bast shoes ran panting up to it, -placed a stone under one of its tireless hind wheels, and began -arranging the breech-band on his little horse. - -One of the wounded, an old soldier with a bandaged arm who was -following the cart on foot, caught hold of it with his sound hand -and turned to look at Pierre. - -"I say, fellow countryman! Will they set us down here or take us -on to Moscow?" he asked. - -Pierre was so deep in thought that he did not hear the question. -He was looking now at the cavalry regiment that had met the convoy -of wounded, now at the cart by which he was standing, in which two -wounded men were sitting and one was lying. One of those sitting up in -the cart had probably been wounded in the cheek. His whole head was -wrapped in rags and one cheek was swollen to the size of a baby's -head. His nose and mouth were twisted to one side. This soldier was -looking at the cathedral and crossing himself. Another, a young lad, a -fair-haired recruit as white as though there was no blood in his -thin face, looked at Pierre kindly, with a fixed smile. The third -lay prone so that his face was not visible. The cavalry singers were -passing close by: - - Ah lost, quite lost... is my head so keen, - Living in a foreign land. - -they sang their soldiers' dance song. - -As if responding to them but with a different sort of merriment, the -metallic sound of the bells reverberated high above and the hot rays -of the sun bathed the top of the opposite slope with yet another -sort of merriment. But beneath the slope, by the cart with the wounded -near the panting little nag where Pierre stood, it was damp, somber, -and sad. - -The soldier with the swollen cheek looked angrily at the cavalry -singers. - -"Oh, the coxcombs!" he muttered reproachfully. - -"It's not the soldiers only, but I've seen peasants today, too.... -The peasants--even they have to go," said the soldier behind the cart, -addressing Pierre with a sad smile. "No distinctions made nowadays.... -They want the whole nation to fall on them--in a word, it's Moscow! -They want to make an end of it." - -In spite of the obscurity of the soldier's words Pierre understood -what he wanted to say and nodded approval. - -The road was clear again; Pierre descended the hill and drove on. - -He kept looking to either side of the road for familiar faces, but -only saw everywhere the unfamiliar faces of various military men of -different branches of the service, who all looked with astonishment at -his white hat and green tail coat. - -Having gone nearly three miles he at last met an acquaintance and -eagerly addressed him. This was one of the head army doctors. He was -driving toward Pierre in a covered gig, sitting beside a young -surgeon, and on recognizing Pierre he told the Cossack who occupied -the driver's seat to pull up. - -"Count! Your excellency, how come you to be here?" asked the doctor. - -"Well, you know, I wanted to see..." - -"Yes, yes, there will be something to see...." - -Pierre got out and talked to the doctor, explaining his intention of -taking part in a battle. - -The doctor advised him to apply direct to Kutuzov. - -"Why should you be God knows where out of sight, during the battle?" -he said, exchanging glances with his young companion. "Anyhow his -Serene Highness knows you and will receive you graciously. That's what -you must do." - -The doctor seemed tired and in a hurry. - -"You think so?... Ah, I also wanted to ask you where our position is -exactly?" said Pierre. - -"The position?" repeated the doctor. "Well, that's not my line. -Drive past Tatarinova, a lot of digging is going on there. Go up the -hillock and you'll see." - -"Can one see from there?... If you would..." - -But the doctor interrupted him and moved toward his gig. - -"I would go with you but on my honor I'm up to here"--and he pointed -to his throat. "I'm galloping to the commander of the corps. How do -matters stand?... You know, Count, there'll be a battle tomorrow. -Out of an army of a hundred thousand we must expect at least twenty -thousand wounded, and we haven't stretchers, or bunks, or dressers, or -doctors enough for six thousand. We have ten thousand carts, but we -need other things as well--we must manage as best we can!" - -The strange thought that of the thousands of men, young and old, who -had stared with merry surprise at his hat (perhaps the very men he had -noticed), twenty thousand were inevitably doomed to wounds and death -amazed Pierre. - -"They may die tomorrow; why are they thinking of anything but -death?" And by some latent sequence of thought the descent of the -Mozhaysk hill, the carts with the wounded, the ringing bells, the -slanting rays of the sun, and the songs of the cavalrymen vividly -recurred to his mind. - -"The cavalry ride to battle and meet the wounded and do not for a -moment think of what awaits them, but pass by, winking at the wounded. -Yet from among these men twenty thousand are doomed to die, and they -wonder at my hat! Strange!" thought Pierre, continuing his way to -Tatarinova. - -In front of a landowner's house to the left of the road stood -carriages, wagons, and crowds of orderlies and sentinels. The -commander in chief was putting up there, but just when Pierre -arrived he was not in and hardly any of the staff were there--they had -gone to the church service. Pierre drove on toward Gorki. - -When he had ascended the hill and reached the little village street, -he saw for the first time peasant militiamen in their white shirts and -with crosses on their caps, who, talking and laughing loudly, animated -and perspiring, were at work on a huge knoll overgrown with grass to -the right of the road. - -Some of them were digging, others were wheeling barrowloads of earth -along planks, while others stood about doing nothing. - -Two officers were standing on the knoll, directing the men. On -seeing these peasants, who were evidently still amused by the -novelty of their position as soldiers, Pierre once more thought of the -wounded men at Mozhaysk and understood what the soldier had meant when -he said: "They want the whole nation to fall on them." The sight of -these bearded peasants at work on the battlefield, with their queer, -clumsy boots and perspiring necks, and their shirts opening from the -left toward the middle, unfastened, exposing their sunburned -collarbones, impressed Pierre more strongly with the solemnity and -importance of the moment than anything he had yet seen or heard. - - - - - -CHAPTER XXI - - -Pierre stepped out of his carriage and, passing the toiling -militiamen, ascended the knoll from which, according to the doctor, -the battlefield could be seen. - -It was about eleven o'clock. The sun shone somewhat to the left -and behind him and brightly lit up the enormous panorama which, rising -like an amphitheater, extended before him in the clear rarefied -atmosphere. - -From above on the left, bisecting that amphitheater, wound the -Smolensk highroad, passing through a village with a white church -some five hundred paces in front of the knoll and below it. This was -Borodino. Below the village the road crossed the river by a bridge -and, winding down and up, rose higher and higher to the village of -Valuevo visible about four miles away, where Napoleon was then -stationed. Beyond Valuevo the road disappeared into a yellowing forest -on the horizon. Far in the distance in that birch and fir forest to -the right of the road, the cross and belfry of the Kolocha Monastery -gleamed in the sun. Here and there over the whole of that blue -expanse, to right and left of the forest and the road, smoking -campfires could be seen and indefinite masses of troops--ours and -the enemy's. The ground to the right--along the course of the -Kolocha and Moskva rivers--was broken and hilly. Between the hollows -the villages of Bezubova and Zakharino showed in the distance. On -the left the ground was more level; there were fields of grain, and -the smoking ruins of Semenovsk, which had been burned down, could be -seen. - -All that Pierre saw was so indefinite that neither the left nor -the right side of the field fully satisfied his expectations. -Nowhere could he see the battlefield he had expected to find, but only -fields, meadows, troops, woods, the smoke of campfires, villages, -mounds, and streams; and try as he would he could descry no military -"position" in this place which teemed with life, nor could he even -distinguish our troops from the enemy's. - -"I must ask someone who knows," he thought, and addressed an officer -who was looking with curiosity at his huge unmilitary figure. - -"May I ask you," said Pierre, "what village that is in front?" - -"Burdino, isn't it?" said the officer, turning to his companion. - -"Borodino," the other corrected him. - -The officer, evidently glad of an opportunity for a talk, moved up -to Pierre. - -"Are those our men there?" Pierre inquired. - -"Yes, and there, further on, are the French," said the officer. -"There they are, there... you can see them." - -"Where? Where?" asked Pierre. - -"One can see them with the naked eye... Why, there!" - -The officer pointed with his hand to the smoke visible on the left -beyond the river, and the same stern and serious expression that -Pierre had noticed on many of the faces he had met came into his face. - -"Ah, those are the French! And over there?..." Pierre pointed to a -knoll on the left, near which some troops could be seen. - -"Those are ours." - -"Ah, ours! And there?..." Pierre pointed to another knoll in the -distance with a big tree on it, near a village that lay in a hollow -where also some campfires were smoking and something black was -visible. - -"That's his again," said the officer. (It was the Shevardino -Redoubt.) "It was ours yesterday, but now it is his." - -"Then how about our position?" - -"Our position?" replied the officer with a smile of satisfaction. "I -can tell you quite clearly, because I constructed nearly all our -entrenchments. There, you see? There's our center, at Borodino, just -there," and he pointed to the village in front of them with the -white church. "That's where one crosses the Kolocha. You see down -there where the rows of hay are lying in the hollow, there's the -bridge. That's our center. Our right flank is over there"--he -pointed sharply to the right, far away in the broken ground--"That's -where the Moskva River is, and we have thrown up three redoubts there, -very strong ones. The left flank..." here the officer paused. "Well, -you see, that's difficult to explain.... Yesterday our left flank -was there at Shevardino, you see, where the oak is, but now we have -withdrawn our left wing--now it is over there, do you see that village -and the smoke? That's Semenovsk, yes, there," he pointed to -Raevski's knoll. "But the battle will hardly be there. His having -moved his troops there is only a ruse; he will probably pass round -to the right of the Moskva. But wherever it may be, many a man will be -missing tomorrow!" he remarked. - -An elderly sergeant who had approached the officer while he was -giving these explanations had waited in silence for him to finish -speaking, but at this point, evidently not liking the officer's -remark, interrupted him. - -"Gabions must be sent for," said he sternly. - -The officer appeared abashed, as though he understood that one might -think of how many men would be missing tomorrow but ought not to speak -to speak of it. - -"Well, send number three company again," the officer replied -hurriedly. - -"And you, are you one of the doctors?" - -"No, I've come on my own," answered Pierre, and he went down the -hill again, passing the militiamen. - -"Oh, those damned fellows!" muttered the officer who followed him, -holding his nose as he ran past the men at work. - -"There they are... bringing her, coming... There they are... They'll -be here in a minute..." voices were suddenly heard saying; and -officers, soldiers, and militiamen began running forward along the -road. - -A church procession was coming up the hill from Borodino. First -along the dusty road came the infantry in ranks, bareheaded and with -arms reversed. From behind them came the sound of church singing. - -Soldiers and militiamen ran bareheaded past Pierre toward the -procession. - -"They are bringing her, our Protectress!... The Iberian Mother of -God!" someone cried. - -"The Smolensk Mother of God," another corrected him. - -The militiamen, both those who had been in the village and those who -had been at work on the battery, threw down their spades and ran to -meet the church procession. Following the battalion that marched along -the dusty road came priests in their vestments--one little old man -in a hood with attendants and singers. Behind them soldiers and -officers bore a large, dark-faced icon with an embossed metal cover. -This was the icon that had been brought from and had since accompanied -the army. Behind, before, and on both sides, crowds of militiamen with -bared heads walked, ran, and bowed to the ground. - -At the summit of the hill they stopped with the icon; the men who -had been holding it up by the linen bands attached to it were relieved -by others, the chanters relit their censers, and service began. The -hot rays of the sun beat down vertically and a fresh soft wind -played with the hair of the bared heads and with the ribbons -decorating the icon. The singing did not sound loud under the open -sky. An immense crowd of bareheaded officers, soldiers, and militiamen -surrounded the icon. Behind the priest and a chanter stood the -notabilities on a spot reserved for them. A bald general with -general with a St. George's Cross on his neck stood just behind the -priest's back, and without crossing himself (he was evidently a -German) patiently awaited the end of the service, which he -considered it necessary to hear to the end, probably to arouse the -patriotism of the Russian people. Another general stood in a martial -pose, crossing himself by shaking his hand in front of his chest while -looking about him. Standing among the crowd of peasants, Pierre -recognized several acquaintances among these notables, but did not -look at them--his whole attention was absorbed in watching the serious -expression on the faces of the crowd of soldiers and militiamen who -were all gazing eagerly at the icon. As soon as the tired chanters, -who were singing the service for the twentieth time that day, began -lazily and mechanically to sing: "Save from calamity Thy servants, O -Mother of God," and the priest and deacon chimed in: "For to Thee -under God we all flee as to an inviolable bulwark and protection," -there again kindled in all those faces the same expression of -consciousness of the solemnity of the impending moment that Pierre had -seen on the faces at the foot of the hill at Mozhaysk and -momentarily on many and many faces he had met that morning; and -heads were bowed more frequently and hair tossed back, and sighs and -the sound men made as they crossed themselves were heard. - -The crowd round the icon suddenly parted and pressed against Pierre. -Someone, a very important personage judging by the haste with which -way was made for him, was approaching the icon. - -It was Kutuzov, who had been riding round the position and on his -way back to Tatarinova had stopped where the service was being held. -Pierre recognized him at once by his peculiar figure, which -distinguished him from everybody else. - -With a long overcoat on his his exceedingly stout, -round-shouldered body, with uncovered white head and puffy face -showing the white ball of the eye he had lost, Kutuzov walked with -plunging, swaying gait into the crowd and stopped behind the priest. -He crossed himself with an accustomed movement, bent till he touched -the ground with his hand, and bowed his white head with a deep sigh. -Behind Kutuzov was Bennigsen and the suite. Despite the presence of -the commander in chief, who attracted the attention of all the -superior officers, the militiamen and soldiers continued their prayers -without looking at him. - -When the service was over, Kutuzov stepped up to the icon, sank -heavily to his knees, bowed to the ground, and for a long time tried -vainly to rise, but could not do so on account of his weakness and -weight. His white head twitched with the effort. At last he rose, -kissed the icon as a child does with naively pouting lips, and again -bowed till he touched the ground with his hand. The other generals -followed his example, then the officers, and after them with excited -faces, pressing on one another, crowding, panting, and pushing, -scrambled the soldiers and militiamen. - - - - - -CHAPTER XXII - - -Staggering amid the crush, Pierre looked about him. - -"Count Peter Kirilovich! How did you get here?" said a voice. - -Pierre looked round. Boris Drubetskoy, brushing his knees with his -hand (he had probably soiled them when he, too, had knelt before the -icon), came up to him smiling. Boris was elegantly dressed, with a -slightly martial touch appropriate to a campaign. He wore a long -coat and like Kutuzov had a whip slung across his shoulder. - -Meanwhile Kutuzov had reached the village and seated himself in -the shade of the nearest house, on a bench which one Cossack had run -to fetch and another had hastily covered with a rug. An immense and -brilliant suite surrounded him. - -The icon was carried further, accompanied by the throng. Pierre -stopped some thirty paces from Kutuzov, talking to Boris. - -He explained his wish to be present at the battle and to see the -position. - -"This is what you must do," said Boris. "I will do the honors of the -camp to you. You will see everything best from where Count Bennigsen -will be. I am in attendance on him, you know; I'll mention it to -him. But if you want to ride round the position, come along with us. -We are just going to the left flank. Then when we get back, do spend -the night with me and we'll arrange a game of cards. Of course you -know Dmitri Sergeevich? Those are his quarters," and he pointed to the -third house in the village of Gorki. - -"But I should like to see the right flank. They say it's very -strong," said Pierre. "I should like to start from the Moskva River -and ride round the whole position." - -"Well, you can do that later, but the chief thing is the left -flank." - -"Yes, yes. But where is Prince Bolkonski's regiment? Can you point -it out to me?" - -"Prince Andrew's? We shall pass it and I'll take you to him." - -"What about the left flank?" asked Pierre - -"To tell you the truth, between ourselves, God only knows what state -our left flank is in," said Boris confidentially lowering his voice. -"It is not at all what Count Bennigsen intended. He meant to fortify -that knoll quite differently, but..." Boris shrugged his shoulders, -"his Serene Highness would not have it, or someone persuaded him. -You see..." but Boris did not finish, for at that moment Kaysarov, -Kutuzov's adjutant, came up to Pierre. "Ah, Kaysarov!" said Boris, -addressing him with an unembarrassed smile, "I was just trying to -explain our position to the count. It is amazing how his Serene -Highness could so the intentions of the French!" - -"You mean the left flank?" asked Kaysarov. - - -"Yes, exactly; the left flank is now extremely strong." - -Though Kutuzov had dismissed all unnecessary men from the staff, -Boris had contrived to remain at headquarters after the changes. He -had established himself with Count Bennigsen, who, like all on whom -Boris had been in attendance, considered young Prince Drubetskoy an -invaluable man. - -In the higher command there were two sharply defined parties: -Kutuzov's party and that of Bennigsen, the chief of staff. Boris -belonged to the latter and no one else, while showing servile -respect to Kutuzov, could so create an impression that the old -fellow was not much good and that Bennigsen managed everything. Now -the decisive moment of battle had come when Kutuzov would be destroyed -and the power pass to Bennigsen, or even if Kutuzov won the battle -it would be felt that everything was done by Bennigsen. In any case -many great rewards would have to be given for tomorrow's action, and -new men would come to the front. So Boris was full of nervous vivacity -all day. - -After Kaysarov, others whom Pierre knew came up to him, and he had -not time to reply to all the questions about Moscow that were showered -upon him, or to listen to all that was told him. The faces all -expressed animation and apprehension, but it seemed to Pierre that the -cause of the excitement shown in some of these faces lay chiefly in -questions of personal success; his mind, however, was occupied by -the different expression he saw on other faces--an expression that -spoke not of personal matters but of the universal questions of life -and death. Kutuzov noticed Pierre's figure and the group gathered -round him. - -"Call him to me," said Kutuzov. - -An adjutant told Pierre of his Serene Highness' wish, and Pierre -went toward Kutuzov's bench. But a militiaman got there before him. It -was Dolokhov. - -"How did that fellow get here?" asked Pierre. - -"He's a creature that wriggles in anywhere!" was the answer. "He has -been degraded, you know. Now he wants to bob up again. He's been -proposing some scheme or other and has crawled into the enemy's picket -line at night.... He's a brave fellow." - -Pierre took off his hat and bowed respectfully to Kutuzov. - -"I concluded that if I reported to your Serene Highness you might -send me away or say that you knew what I was reporting, but then I -shouldn't lose anything..." Dolokhov was saying. - -"Yes, yes." - -"But if I were right, I should be rendering a service to my -Fatherland for which I am ready to die." - -"Yes, yes." - -"And should your Serene Highness require a man who will not spare -his skin, please think of me.... Perhaps I may prove useful to your -Serene Highness." - -"Yes... Yes..." Kutuzov repeated, his laughing eye narrowing more -and more as he looked at Pierre. - -Just then Boris, with his courtierlike adroitness, stepped up to -Pierre's side near Kutuzov and in a most natural manner, without -raising his voice, said to Pierre, as though continuing an interrupted -conversation: - -"The militia have put on clean white shirts to be ready to die. What -heroism, Count!" - -Boris evidently said this to Pierre in order to be overheard by -his Serene Highness. He knew Kutuzov's attention would be caught by -those words, and so it was. - -"What are you saying about the militia?" he asked Boris. - -"Preparing for tomorrow, your Serene Highness--for death--they -have put on clean shirts." - -"Ah... a wonderful, a matchless people!" said Kutuzov; and he closed -his eyes and swayed his head. "A matchless people!" he repeated with a -sigh. - -"So you want to smell gunpowder?" he said to Pierre. "Yes, it's a -pleasant smell. I have the honor to be one of your wife's adorers. -Is she well? My quarters are at your service." - -And as often happens with old people, Kutuzov began looking about -absent-mindedly as if forgetting all he wanted to say or do. - -Then, evidently remembering what he wanted, he beckoned to Andrew -Kaysarov, his adjutant's brother. - -"Those verses... those verses of Marin's... how do they go, eh? -Those he wrote about Gerakov: 'Lectures for the corps inditing'... -Recite them, recite them!" said he, evidently preparing to laugh. - -Kaysarov recited.... Kutuzov smilingly nodded his head to the rhythm -of the verses. - -When Pierre had left Kutuzov, Dolokhov came up to him and took his -hand. - -"I am very glad to meet you here, Count," he said aloud, -regardless of the presence of strangers and in a particularly resolute -and solemn tone. "On the eve of a day when God alone knows who of us -is fated to survive, I am glad of this opportunity to tell you that -I regret the misunderstandings that occurred between us and should -wish you not to have any ill feeling for me. I beg you to forgive me." - -Pierre looked at Dolokhov with a smile, not knowing what to say to -him. With tears in his eyes Dolokhov embraced Pierre and kissed him. - -Boris said a few words to his general, and Count Bennigsen turned to -Pierre and proposed that he should ride with him along the line. - -"It will interest you," said he. - -"Yes, very much," replied Pierre. - -Half an hour later Kutuzov left for Tatarinova, and Bennigsen and -his suite, with Pierre among them, set out on their ride along the -line. - - - - - -CHAPTER XXIII - - -From Gorki, Bennigsen descended the highroad to the bridge which, -when they had looked it from the hill, the officer had pointed out -as being the center of our position and where rows of fragrant -new-mown hay lay by the riverside. They rode across that bridge into -the village of Borodino and thence turned to the left, passing an -enormous number of troops and guns, and came to a high knoll where -militiamen were digging. This was the redoubt, as yet unnamed, which -afterwards became known as the Raevski Redoubt, or the Knoll -Battery, but Pierre paid no special attention to it. He did not know -that it would become more memorable to him than any other spot on -the plain of Borodino. - -They then crossed the hollow to Semenovsk, where the soldiers were -dragging away the last logs from the huts and barns. Then they rode -downhill and uphill, across a ryefield trodden and beaten down as if -by hail, following a track freshly made by the artillery over the -furrows of the plowed land, and reached some fleches* which were still -being dug. - - -*A kind of entrenchment. - - -At the fleches Bennigsen stopped and began looking at the Shevardino -Redoubt opposite, which had been ours the day before and where several -horsemen could be descried. The officers said that either Napoleon -or Murat was there, and they all gazed eagerly at this little group of -horsemen. Pierre also looked at them, trying to guess which of the -scarcely discernible figures was Napoleon. At last those mounted men -rode away from the mound and disappeared. - -Bennigsen spoke to a general who approached him, and began -explaining the whole position of our troops. Pierre listened to him, -straining each faculty to understand the essential points of the -impending battle, but was mortified to feel that his mental capacity -was inadequate for the task. He could make nothing of it. Bennigsen -stopped speaking and, noticing that Pierre was listening, suddenly -said to him: - -"I don't think this interests you?" - -"On the contrary it's very interesting!" replied Pierre not quite -truthfully. - -From the fleches they rode still farther to the left, along a road -winding through a thick, low-growing birch wood. In the middle of -the wood a brown hare with white feet sprang out and, scared by the -tramp of the many horses, grew so confused that it leaped along the -road in front of them for some time, arousing general attention and -laughter, and only when several voices shouted at it did it dart to -one side and disappear in the thicket. After going through the wood -for about a mile and a half they came out on a glade where troops of -Tuchkov's corps were stationed to defend the left flank. - -Here, at the extreme left flank, Bennigsen talked a great deal and -with much heat, and, as it seemed to Pierre, gave orders of great -military importance. In front of Tuchkov's troops was some high ground -not occupied by troops. Bennigsen loudly criticized this mistake, -saying that it was madness to leave a height which commanded the -country around unoccupied and to place troops below it. Some of the -generals expressed the same opinion. One in particular declared with -martial heat that they were put there to be slaughtered. Bennigsen -on his own authority ordered the troops to occupy the high ground. -This disposition on the left flank increased Pierre's doubt of his own -capacity to understand military matters. Listening to Bennigsen and -the generals criticizing the position of the troops behind the hill, -he quite understood them and shared their opinion, but for that very -reason he could not understand how the man who put them there behind -the hill could have made so gross and palpable a blunder. - -Pierre did not know that these troops were not, as Bennigsen -supposed, put there to defend the position, but were in a concealed -position as an ambush, that they should not be seen and might be -able to strike an approaching enemy unexpectedly. Bennigsen did not -know this and moved the troops forward according to his own ideas -without mentioning the matter to the commander in chief. - - - - - -CHAPTER XXIV - - -On that bright evening of August 25, Prince Andrew lay leaning on -his elbow in a broken-down shed in the village of Knyazkovo at the -further end of his regiment's encampment. Through a gap in the -broken wall he could see, beside the wooden fence, a row of thirty -year-old birches with their lower branches lopped off, a field on -which shocks of oats were standing, and some bushes near which rose -the smoke of campfires--the soldiers' kitchens. - -Narrow and burdensome and useless to anyone as his life now seemed -to him, Prince Andrew on the eve of battle felt agitated and irritable -as he had done seven years before at Austerlitz. - -He had received and given the orders for next day's battle and had -nothing more to do. But his thoughts--the simplest, clearest, and -therefore most terrible thoughts--would give him no peace. He knew -that tomorrow's battle would be the most terrible of all he had -taken part in, and for the first time in his life the possibility of -death presented itself to him--not in relation to any worldly matter -or with reference to its effect on others, but simply in relation to -himself, to his own soul--vividly, plainly, terribly, and almost as -a certainty. And from the height of this perception all that had -previously tormented and preoccupied him suddenly became illumined -by a cold white light without shadows, without perspective, without -distinction of outline. All life appeared to him like magic-lantern -pictures at which he had long been gazing by artificial light -through a glass. Now he suddenly saw those badly daubed pictures in -clear daylight and without a glass. "Yes, yes! There they are, those -false images that agitated, enraptured, and tormented me," said he -to himself, passing in review the principal pictures of the magic -lantern of life and regarding them now in the cold white daylight of -his clear perception of death. "There they are, those rudely painted -figures that once seemed splendid and mysterious. Glory, the good of -society, love of a woman, the Fatherland itself--how important these -pictures appeared to me, with what profound meaning they seemed to -be filled! And it is all so simple, pale, and crude in the cold -white light of this morning which I feel is dawning for me." The three -great sorrows of his life held his attention in particular: his love -for a woman, his father's death, and the French invasion which had -overrun half Russia. "Love... that little girl who seemed to me -brimming over with mystic forces! Yes, indeed, I loved her. I made -romantic plans of love and happiness with her! Oh, what a boy I -was!" he said aloud bitterly. "Ah me! I believed in some ideal love -which was to keep her faithful to me for the whole year of my absence! -Like the gentle dove in the fable she was to pine apart from me.... -But it was much simpler really.... It was all very simple and -horrible." - -"When my father built Bald Hills he thought the place was his: his -land, his air, his peasants. But Napoleon came and swept him aside, -unconscious of his existence, as he might brush a chip from his -path, and his Bald Hills and his whole life fell to pieces. Princess -Mary says it is a trial sent from above. What is the trial for, when -he is not here and will never return? He is not here! For whom then is -the trial intended? The Fatherland, the destruction of Moscow! And -tomorrow I shall be killed, perhaps not even by a Frenchman but by one -of our own men, by a soldier discharging a musket close to my ear as -one of them did yesterday, and the French will come and take me by -head and heels and fling me into a hole that I may not stink under -their noses, and new conditions of life will arise, which will seem -quite ordinary to others and about which I shall know nothing. I shall -not exist..." - -He looked at the row of birches shining in the sunshine, with -their motionless green and yellow foliage and white bark. "To die... -to be killed tomorrow... That I should not exist... That all this -should still be, but no me...." - -And the birches with their light and shade, the curly clouds, the -smoke of the campfires, and all that was around him changed and seemed -terrible and menacing. A cold shiver ran down his spine. He rose -quickly, went out of the shed, and began to walk about. - -After he had returned, voices were heard outside the shed. "Who's -that?" he cried. - -The red-nosed Captain Timokhin, formerly Dolokhov's squadron -commander, but now from lack of officers a battalion commander, - -shyly entered the shed followed by an adjutant and the regimental -paymaster. - -Prince Andrew rose hastily, listened to the business they had come -about, gave them some further instructions, and was about to dismiss -them when he heard a familiar, lisping, voice behind the shed. - -"Devil take it!" said the voice of a man stumbling over something. - -Prince Andrew looked out of the shed and saw Pierre, who had tripped -over a pole on the ground and had nearly fallen, coming his way. It -was unpleasant to Prince Andrew to meet people of his own set in -general, and Pierre especially, for he reminded him of all the painful -moments of his last visit to Moscow. - -"You? What a surprise!" said he. "What brings you here? This is -unexpected!" - -As he said this his eyes and face expressed more than coldness--they -expressed hostility, which Pierre noticed at once. He had approached -the shed full of animation, but on seeing Prince Andrew's face he felt -constrained and ill at ease. - -"I have come... simply... you know... come... it interests me," said -Pierre, who had so often that day senselessly repeated that word -"interesting." "I wish to see the battle." - -"Oh yes, and what do the Masonic brothers say about war? How would -they stop it?" said Prince Andrew sarcastically. "Well, and how's -Moscow? And my people? Have they reached Moscow at last?" he asked -seriously. - -"Yes, they have. Julie Drubetskaya told me so. I went to see them, -but missed them. They have gone to your estate near Moscow." - - - - - -CHAPTER XXV - - -The officers were about to take leave, but Prince Andrew, apparently -reluctant to be left alone with his friend, asked them to stay and -have tea. Seats were brought in and so was the tea. The officers gazed -with surprise at Pierre's huge stout figure and listened to his talk -of Moscow and the position of our army, round which he had ridden. -Prince Andrew remained silent, and his expression was so forbidding -that Pierre addressed his remarks chiefly to the good-natured -battalion commander. - -"So you understand the whole position of our troops?" Prince -Andrew interrupted him. - -"Yes--that is, how do you mean?" said Pierre. "Not being a -military man I can't say I have understood it fully, but I -understand the general position." - -"Well, then, you know more than anyone else, be it who it may," said -Prince Andrew. - -"Oh!" said Pierre, looking over his spectacles in perplexity at -Prince Andrew. "Well, and what do think of Kutuzov's appointment?" -he asked. - -"I was very glad of his appointment, that's all I know," replied -Prince Andrew. - -"And tell me your opinion of Barclay de Tolly. In Moscow they are -saying heaven knows what about him.... What do you think of him?" - -"Ask them," replied Prince Andrew, indicating the officers. - -Pierre looked at Timokhin with the condescendingly interrogative -smile with which everybody involuntarily addressed that officer. - -"We see light again, since his Serenity has been appointed, your -excellency," said Timokhin timidly, and continually turning to -glance at his colonel. - -"Why so?" asked Pierre. - -"Well, to mention only firewood and fodder, let me inform you. -Why, when we were retreating from Sventsyani we dare not touch a stick -or a wisp of hay or anything. You see, we were going away, so he would -get it all; wasn't it so, your excellency?" and again Timokhin -turned to the prince. "But we daren't. In our regiment two officers -were court-martialed for that kind of thing. But when his Serenity -took command everything became straight forward. Now we see light..." - -"Then why was it forbidden?" - -Timokhin looked about in confusion, not knowing what or how to -answer such a question. Pierre put the same question to Prince Andrew. - -"Why, so as not to lay waste the country we were abandoning to the -enemy," said Prince Andrew with venomous irony. "It is very sound: one -can't permit the land to be pillaged and accustom the troops to -marauding. At Smolensk too he judged correctly that the French might -outflank us, as they had larger forces. But he could not understand -this," cried Prince Andrew in a shrill voice that seemed to escape him -involuntarily: "he could not understand that there, for the first -time, we were fighting for Russian soil, and that there was a spirit -in the men such as I had never seen before, that we had held the -French for two days, and that that success had increased our -strength tenfold. He ordered us to retreat, and all our efforts and -losses went for nothing. He had no thought of betraying us, he tried -to do the best he could, he thought out everything, and that is why he -is unsuitable. He is unsuitable now, just because he plans out -everything very thoroughly and accurately as every German has to. -How can I explain?... Well, say your father has a German valet, and he -is a splendid valet and satisfies your father's requirements better -than you could, then it's all right to let him serve. But if your -father is mortally sick you'll send the valet away and attend to -your father with your own unpracticed, awkward hands, and will -soothe him better than a skilled man who is a stranger could. So it -has been with Barclay. While Russia was well, a foreigner could -serve her and be a splendid minister; but as soon as she is in -danger she needs one of her own kin. But in your Club they have been -making him out a traitor! They slander him as a traitor, and the -only result will be that afterwards, ashamed of their false -accusations, they will make him out a hero or a genius instead of a -traitor, and that will be still more unjust. He is an honest and -very punctilious German." - -"And they say he's a skillful commander," rejoined Pierre. - -"I don't understand what is meant by 'a skillful commander,'" -replied Prince Andrew ironically. - -"A skillful commander?" replied Pierre. "Why, one who foresees all -contingencies... and foresees the adversary's intentions." - -"But that's impossible," said Prince Andrew as if it were a matter -settled long ago. - -Pierre looked at him in surprise. - -"And yet they say that war is like a game of chess?" he remarked. - -"Yes," replied Prince Andrew, "but with this little difference, that -in chess you may think over each move as long as you please and are -not limited for time, and with this difference too, that a knight is -always stronger than a pawn, and two pawns are always stronger than -one, while in war a battalion is sometimes stronger than a division -and sometimes weaker than a company. The relative strength of bodies -of troops can never be known to anyone. Believe me," he went on, "if -things depended on arrangements made by the staff, I should be there -making arrangements, but instead of that I have the honor to serve -here in the regiment with these gentlemen, and I consider that on us -tomorrow's battle will depend and not on those others.... Success -never depends, and never will depend, on position, or equipment, or -even on numbers, and least of all on position." - -"But on what then?" - -"On the feeling that is in me and in him," he pointed to Timokhin, -"and in each soldier." - -Prince Andrew glanced at Timokhin, who looked at his commander in -alarm and bewilderment. In contrast to his former reticent taciturnity -Prince Andrew now seemed excited. He could apparently not refrain from -expressing the thoughts that had suddenly occurred to him. - -"A battle is won by those who firmly resolve to win it! Why did we -lose the battle at Austerlitz? The French losses were almost equal -to ours, but very early we said to ourselves that we were losing the -battle, and we did lose it. And we said so because we had nothing to -fight for there, we wanted to get away from the battlefield as soon as -we could. 'We've lost, so let us run,' and we ran. If we had not -said that till the evening, heaven knows what might not have happened. -But tomorrow we shan't say it! You talk about our position, the left -flank weak and the right flank too extended," he went on. "That's -all nonsense, there's nothing of the kind. But what awaits us -tomorrow? A hundred million most diverse chances which will be decided -on the instant by the fact that our men or theirs run or do not run, -and that this man or that man is killed, but all that is being done at -present is only play. The fact is that those men with whom you have -ridden round the position not only do not help matters, but hinder. -They are only concerned with their own petty interests." - -"At such a moment?" said Pierre reproachfully. - -"At such a moment!" Prince Andrew repeated. "To them it is only a -moment affording opportunities to undermine a rival and obtain an -extra cross or ribbon. For me tomorrow means this: a Russian army of a -hundred thousand and a French army of a hundred thousand have met to -fight, and the thing is that these two hundred thousand men will fight -and the side that fights more fiercely and spares itself least will -win. And if you like I will tell you that whatever happens and -whatever muddles those at the top may make, we shall win tomorrow's -battle. Tomorrow, happen what may, we shall win!" - -"There now, your excellency! That's the truth, the real truth," said -Timokhin. "Who would spare himself now? The soldiers in my -battalion, believe me, wouldn't drink their vodka! 'It's not the day -for that!' they say." - -All were silent. The officers rose. Prince Andrew went out of the -shed with them, giving final orders to the adjutant. After they had -gone Pierre approached Prince Andrew and was about to start a -conversation when they heard the clatter of three horses' hoofs on the -road not far from the shed, and looking in that direction Prince -Andrew recognized Wolzogen and Clausewitz accompanied by a Cossack. -They rode close by continuing to converse, and Prince Andrew -involuntarily heard these words: - -"Der Krieg muss in Raum verlegt werden. Der Ansicht kann ich nicht -genug Preis geben,"* said one of them. - - -*"The war must be extended widely. I cannot sufficiently commend -that view." - - -"Oh, ja," said the other, "der Zweck ist nur den Feind zu schwachen, -so kann man gewiss nicht den Verlust der Privat-Personen in Achtung -nehmen."* - - -*"Oh, yes, the only aim is to weaken the enemy, so of course one -cannot take into account the loss of private individuals." - - -"Oh, no," agreed the other. - -"Extend widely!" said Prince Andrew with an angry snort, when they -had ridden past. "In that 'extend' were my father, son, and sister, at -Bald Hills. That's all the same to him! That's what I was saying to -you--those German gentlemen won't win the battle tomorrow but will -only make all the mess they can, because they have nothing in their -German heads but theories not worth an empty eggshell and haven't in -their hearts the one thing needed tomorrow--that which Timokhin has. -They have yielded up all Europe to him, and have now come to teach us. -Fine teachers!" and again his voice grew shrill. - -"So you think we shall win tomorrow's battle?" asked Pierre. - -"Yes, yes," answered Prince Andrew absently. "One thing I would do - -if I had the power," he began again, "I would not take prisoners. -Why take prisoners? It's chivalry! The French have destroyed my home -and are on their way to destroy Moscow, they have outraged and are -outraging me every moment. They are my enemies. In my opinion they are -all criminals. And so thinks Timokhin and the whole army. They -should be executed! Since they are my foes they cannot be my -friends, whatever may have been said at Tilsit." - -"Yes, yes," muttered Pierre, looking with shining eyes at Prince -Andrew. "I quite agree with you!" - -The question that had perturbed Pierre on the Mozhaysk hill and -all that day now seemed to him quite clear and completely solved. He -now understood the whole meaning and importance of this war and of the -impending battle. All he had seen that day, all the significant and -stern expressions on the faces he had seen in passing, were lit up for -him by a new light. He understood that latent heat (as they say in -physics) of patriotism which was present in all these men he had seen, -and this explained to him why they all prepared for death calmly, -and as it were lightheartedly. - -"Not take prisoners," Prince Andrew continued: "That by itself would -quite change the whole war and make it less cruel. As it is we have -played at war--that's what's vile! We play at magnanimity and all that -stuff. Such magnanimity and sensibility are like the magnanimity and -sensibility of a lady who faints when she sees a calf being killed: -she is so kind-hearted that she can't look at blood, but enjoys eating -the calf served up with sauce. They talk to us of the rules of war, of -chivalry, of flags of truce, of mercy to the unfortunate and so on. -It's all rubbish! I saw chivalry and flags of truce in 1805; they -humbugged us and we humbugged them. They plunder other people's -houses, issue false paper money, and worst of all they kill my -children and my father, and then talk of rules of war and -magnanimity to foes! Take no prisoners, but kill and be killed! He who -has come to this as I have through the same sufferings..." - -Prince Andrew, who had thought it was all the same to him whether or -not Moscow was taken as Smolensk had been, was suddenly checked in his -speech by an unexpected cramp in his throat. He paced up and down a -few times in silence, but his eyes glittered feverishly and his lips -quivered as he began speaking. - -"If there was none of this magnanimity in war, we should go to war -only when it was worth while going to certain death, as now. Then -there would not be war because Paul Ivanovich had offended Michael -Ivanovich. And when there was a war, like this one, it would be war! -And then the determination of the troops would be quite different. -Then all these Westphalians and Hessians whom Napoleon is leading -would not follow him into Russia, and we should not go to fight in -Austria and Prussia without knowing why. War is not courtesy but the -most horrible thing in life; and we ought to understand that and not -play at war. We ought to accept this terrible necessity sternly and -seriously. It all lies in that: get rid of falsehood and let war be -war and not a game. As it is now, war is the favorite pastime of the -idle and frivolous. The military calling is the most highly honored. - -"But what is war? What is needed for success in warfare? What are -the habits of the military? The aim of war is murder; the methods of -war are spying, treachery, and their encouragement, the ruin of a -country's inhabitants, robbing them or stealing to provision the army, -and fraud and falsehood termed military craft. The habits of the -military class are the absence of freedom, that is, discipline, -idleness, ignorance, cruelty, debauchery, and drunkenness. And in -spite of all this it is the highest class, respected by everyone. -All the kings, except the Chinese, wear military uniforms, and he -who kills most people receives the highest rewards. - -"They meet, as we shall meet tomorrow, to murder one another; they -kill and maim tens of thousands, and then have thanksgiving services -for having killed so many people (they even exaggerate the number), -and they announce a victory, supposing that the more people they -have killed the greater their achievement. How does God above look -at them and hear them?" exclaimed Prince Andrew in a shrill, -piercing voice. "Ah, my friend, it has of late become hard for me to -live. I see that I have begun to understand too much. And it doesn't -do for man to taste of the tree of knowledge of good and evil.... -Ah, well, it's not for long!" he added. - -"However, you're sleepy, and it's time for me to sleep. Go back to -Gorki!" said Prince Andrew suddenly. - -"Oh no!" Pierre replied, looking at Prince Andrew with frightened, -compassionate eyes. - -"Go, go! Before a battle one must have one's sleep out," repeated -Prince Andrew. - -He came quickly up to Pierre and embraced and kissed him. -"Good-by, be off!" he shouted. "Whether we meet again or not..." -and turning away hurriedly he entered the shed. - -It was already dark, and Pierre could not make out whether the -expression of Prince Andrew's face was angry or tender. - -For some time he stood in silence considering whether he should -follow him or go away. "No, he does not want it!" Pierre concluded. -"And I know that this is our last meeting!" He sighed deeply and -rode back to Gorki. - -On re-entering the shed Prince Andrew lay down on a rug, but he -could not sleep. - -He closed his eyes. One picture succeeded another in his -imagination. On one of them he dwelt long and joyfully. He vividly -recalled an evening in Petersburg. Natasha with animated and excited -face was telling him how she had gone to look for mushrooms the -previous summer and had lost her way in the big forest. She -incoherently described the depths of the forest, her feelings, and a -talk with a beekeeper she met, and constantly interrupted her story to -say: "No, I can't! I'm not telling it right; no, you don't -understand," though he encouraged her by saying that he did -understand, and he really had understood all she wanted to say. But -Natasha was not satisfied with her own words: she felt that they did -not convey the passionately poetic feeling she had experienced that -day and wished to convey. "He was such a delightful old man, and it -was so dark in the forest... and he had such kind... No, I can't -describe it," she had said, flushed and excited. Prince Andrew -smiled now the same happy smile as then when he had looked into her -eyes. "I understood her," he thought. "I not only understood her, -but it was just that inner, spiritual force, that sincerity, that -frankness of soul--that very soul of hers which seemed to be -fettered by her body--it was that soul I loved in her... loved so -strongly and happily..." and suddenly he remembered how his love had -ended. "He did not need anything of that kind. He neither saw nor -understood anything of the sort. He only saw in her a pretty and fresh -young girl, with whom he did not deign to unite his fate. And I?... -and he is still alive and gay!" - -Prince Andrew jumped up as if someone had burned him, and again -began pacing up and down in front of the shed. - - - - - -CHAPTER XXVI - - -On August 25, the eve of the battle of Borodino, M. de Beausset, -prefect of the French Emperor's palace, arrived at Napoleon's quarters -at Valuevo with Colonel Fabvier, the former from Paris and the -latter from Madrid. - -Donning his court uniform, M. de Beausset ordered a box he had -brought for the Emperor to be carried before him and entered the first -compartment of Napoleon's tent, where he began opening the box while -conversing with Napoleon's aides-de-camp who surrounded him. - -Fabvier, not entering the tent, remained at the entrance talking -to some generals of his acquaintance. - -The Emperor Napoleon had not yet left his bedroom and was -finishing his toilet. Slightly snorting and grunting, he presented now -his back and now his plump hairy chest to the brush with which his -valet was rubbing him down. Another valet, with his finger over the -mouth of a bottle, was sprinkling Eau de Cologne on the Emperor's -pampered body with an expression which seemed to say that he alone -knew where and how much Eau de Cologne should be sprinkled. Napoleon's -short hair was wet and matted on the forehead, but his face, though -puffy and yellow, expressed physical satisfaction. "Go on, harder, -go on!" he muttered to the valet who was rubbing him, slightly -twitching and grunting. An aide-de-camp, who had entered the bedroom -to report to the Emperor the number of prisoners taken in -yesterday's action, was standing by the door after delivering his -message, awaiting permission to withdraw. Napoleon, frowning, looked -at him from under his brows. - -"No prisoners!" said he, repeating the aide-de-camp's words. "They -are forcing us to exterminate them. So much the worse for the -Russian army.... Go on... harder, harder!" he muttered, hunching his -back and presenting his fat shoulders. - -"All right. Let Monsieur de Beausset enter, and Fabvier too," he -said, nodding to the aide-de-camp. - -"Yes, sire," and the aide-de-camp disappeared through the door of -the tent. - -Two valets rapidly dressed His Majesty, and wearing the blue uniform -of the Guards he went with firm quick steps to the reception room. - -De Beausset's hands meanwhile were busily engaged arranging the -present he had brought from the Empress, on two chairs directly in -front of the entrance. But Napoleon had dressed and come out with such -unexpected rapidity that he had not time to finish arranging the -surprise. - -Napoleon noticed at once what they were about and guessed that -they were not ready. He did not wish to deprive them of the pleasure -of giving him a surprise, so he pretended not to see de Beausset and -called Fabvier to him, listening silently and with a stern frown to -what Fabvier told him of the heroism and devotion of his troops -fighting at Salamanca, at the other end of Europe, with but one -thought--to be worthy of their Emperor--and but one fear--to fail to -please him. The result of that battle had been deplorable. Napoleon -made ironic remarks during Fabvier's account, as if he had not -expected that matters could go otherwise in his absence. - -"I must make up for that in Moscow," said Napoleon. "I'll see you -later," he added, and summoned de Beausset, who by that time had -prepared the surprise, having placed something on the chairs and -covered it with a cloth. - -De Beausset bowed low, with that courtly French bow which only the -old retainers of the Bourbons knew how to make, and approached him, -presenting an envelope. - -Napoleon turned to him gaily and pulled his ear. - -"You have hurried here. I am very glad. Well, what is Paris saying?" -he asked, suddenly changing his former stern expression for a most -cordial tone. - -"Sire, all Paris regrets your absence," replied de Beausset as was -proper. - -But though Napoleon knew that de Beausset had to say something of -this kind, and though in his lucid moments he knew it was untrue, he -was pleased to hear it from him. Again he honored him by touching -his ear. - -"I am very sorry to have made you travel so far," said he. - -"Sire, I expected nothing less than to find you at the gates of -Moscow," replied de Beausset. - -Napoleon smiled and, lifting his head absentmindedly, glanced to the -right. An aide-de-camp approached with gliding steps and offered him a -gold snuffbox, which he took. - -"Yes, it has happened luckily for you," he said, raising the open -snuffbox to his nose. "You are fond of travel, and in three days you -will see Moscow. You surely did not expect to see that Asiatic -capital. You will have a pleasant journey." - -De Beausset bowed gratefully at this regard for his taste for travel -(of which he had not till then been aware). - -"Ha, what's this?" asked Napoleon, noticing that all the courtiers -were looking at something concealed under a cloth. - -With courtly adroitness de Beausset half turned and without -turning his back to the Emperor retired two steps, twitching off the -cloth at the same time, and said: - -"A present to Your Majesty from the Empress." - -It was a portrait, painted in bright colors by Gerard, of the son -borne to Napoleon by the daughter of the Emperor of Austria, the boy -whom for some reason everyone called "The King of Rome." - -A very pretty curly-headed boy with a look of the Christ in the -Sistine Madonna was depicted playing at stick and ball. The ball -represented the terrestrial globe and the stick in his other hand a -scepter. - -Though it was not clear what the artist meant to express by -depicting the so-called King of Rome spiking the earth with a stick, -the allegory apparently seemed to Napoleon, as it had done to all -who had seen it in Paris, quite clear and very pleasing. - -"The King of Rome!" he said, pointing to the portrait with a -graceful gesture. "Admirable!" - -With the natural capacity of an Italian for changing the -expression of his face at will, he drew nearer to the portrait and -assumed a look of pensive tenderness. He felt that what he now said -and did would be historical, and it seemed to him that it would now be -best for him--whose grandeur enabled his son to play stick and ball -with the terrestrial globe--to show, in contrast to that grandeur, the -simplest paternal tenderness. His eyes grew dim, he moved forward, -glanced round at a chair (which seemed to place itself under him), and -sat down on it before the portrait. At a single gesture from him -everyone went out on tiptoe, leaving the great man to himself and -his emotion. - -Having sat still for a while he touched--himself not knowing why- -the thick spot of paint representing the highest light in the -portrait, rose, and recalled de Beausset and the officer on duty. He -ordered the portrait to be carried outside his tent, that the Old -Guard, stationed round it, might not be deprived of the pleasure of -seeing the King of Rome, the son and heir of their adored monarch. - -And while he was doing M. de Beausset the honor of breakfasting with -him, they heard, as Napoleon had anticipated, the rapturous cries of -the officers and men of the Old Guard who had run up to see the -portrait. - -"Vive l'Empereur! Vive le roi de Rome! Vive l'Empereur!" came -those ecstatic cries. - -After breakfast Napoleon in de Beausset's presence dictated his -order of the day to the army. - -"Short and energetic!" he remarked when he had read over the -proclamation which he had dictated straight off without corrections. -It ran: - - -Soldiers! This is the battle you have so longed for. Victory depends -on you. It is essential for us; it will give us all we need: -comfortable quarters and a speedy return to our country. Behave as you -did at Austerlitz, Friedland, Vitebsk, and Smolensk. Let our -remotest posterity recall your achievements this day with pride. Let -it be said of each of you: "He was in the great battle before Moscow!" - - -"Before Moscow!" repeated Napoleon, and inviting M. de Beausset, who -was so fond of travel, to accompany him on his ride, he went out of -the tent to where the horses stood saddled. - -"Your Majesty is too kind!" replied de Beausset to the invitation to -accompany the Emperor; he wanted to sleep, did not know how to ride -and was afraid of doing so. - -But Napoleon nodded to the traveler, and de Beausset had to mount. -When Napoleon came out of the tent the shouting of the Guards before -his son's portrait grew still louder. Napoleon frowned. - -"Take him away!" he said, pointing with a gracefully majestic -gesture to the portrait. "It is too soon for him to see a field of -battle." - -De Beausset closed his eyes, bowed his head, and sighed deeply, to -indicate how profoundly he valued and comprehended the Emperor's -words. - - - - - -CHAPTER XXVII - - -On the twenty-fifth of August, so his historians tell us, Napoleon -spent the whole day on horseback inspecting the locality, -considering plans submitted to him by his marshals, and personally -giving commands to his generals. - -The original line of the Russian forces along the river Kolocha -had been dislocated by the capture of the Shevardino Redoubt on the -twenty-fourth, and part of the line--the left flank--had been drawn -back. That part of the line was not entrenched and in front of it -the ground was more open and level than elsewhere. It was evident to -anyone, military or not, that it was here the French should attack. It -would seem that not much consideration was needed to reach this -conclusion, nor any particular care or trouble on the part of the -Emperor and his marshals, nor was there any need of that special and -supreme quality called genius that people are so apt to ascribe to -Napoleon; yet the historians who described the event later and the men -who then surrounded Napoleon, and he himself, thought otherwise. - -Napoleon rode over the plain and surveyed the locality with a -profound air and in silence, nodded with approval or shook his head -dubiously, and without communicating to the generals around him the -profound course of ideas which guided his decisions merely gave them -his final conclusions in the form of commands. Having listened to a -suggestion from Davout, who was now called Prince d'Eckmuhl, to turn -the Russian left wing, Napoleon said it should not be done, without -explaining why not. To a proposal made by General Campan (who was to -attack the fleches) to lead his division through the woods, Napoleon -agreed, though the so-called Duke of Elchingen (Ney) ventured to -remark that a movement through the woods was dangerous and might -disorder the division. - -Having inspected the country opposite the Shevardino Redoubt, -Napoleon pondered a little in silence and then indicated the spots -where two batteries should be set up by the morrow to act against -the Russian entrenchments, and the places where, in line with them, -the field artillery should be placed. - -After giving these and other commands he returned to his tent, and -the dispositions for the battle were written down from his dictation. - -These dispositions, of which the French historians write with -enthusiasm and other historians with profound respect, were as -follows: - - -At dawn the two new batteries established during the night on the -plain occupied by the Prince d'Eckmuhl will open fire on the -opposing batteries of the enemy. - -At the same time the commander of the artillery of the 1st Corps, -General Pernetti, with thirty cannon of Campan's division and all -the howitzers of Dessaix's and Friant's divisions, will move -forward, open fire, and overwhelm with shellfire the enemy's -battery, against which will operate: - - 24 guns of the artillery of the Guards - 30 guns of Campan's division - -and 8 guns of Friant's and Dessaix's divisions - -- - -in all 62 guns. - - -The commander of the artillery of the 3rd Corps, General Fouche, -will place the howitzers of the 3rd and 8th Corps, sixteen in all, -on the flanks of the battery that is to bombard the entrenchment on -the left, which will have forty guns in all directed against it. - -General Sorbier must be ready at the first order to advance with all -the howitzers of the Guard's artillery against either one or other -of the entrenchments. - -During the cannonade Prince Poniatowski is to advance through the -wood on the village and turn the enemy's position. - -General Campan will move through the wood to seize the first -fortification. - -After the advance has begun in this manner, orders will be given -in accordance with the enemy's movements. - -The cannonade on the left flank will begin as soon as the guns of -the right wing are heard. The sharpshooters of Morand's division and -of the vice-King's division will open a heavy fire on seeing the -attack commence on the right wing. - -The vice-King will occupy the village and cross by its three -bridges, advancing to the same heights as Morand's and Gibrard's -divisions, which under his leadership will be directed against the -redoubt and come into line with the rest of the forces. - -All this must be done in good order (le tout se fera avec ordre et -methode) as far as possible retaining troops in reserve. - The Imperial Camp near Mozhaysk, - September, 6, 1812. - - -These dispositions, which are very obscure and confused if one -allows oneself to regard the arrangements without religious awe of his -genius, related to Napoleon's orders to deal with four points--four -different orders. Not one of these was, or could be, carried out. - -In the disposition it is said first that the batteries placed on the -spot chosen by Napoleon, with the guns of Pernetti and Fouche; which -were to come in line with them, 102 guns in all, were to open fire and -shower shells on the Russian fleches and redoubts. This could not be -done, as from the spots selected by Napoleon the projectiles did not -carry to the Russian works, and those 102 guns shot into the air until -the nearest commander, contrary to Napoleon's instructions, moved them -forward. - -The second order was that Poniatowski, moving to the village through -the wood, should turn the Russian left flank. This could not be done -and was not done, because Poniatowski, advancing on the village -through the wood, met Tuchkov there barring his way, and could not and -did not turn the Russian position. - -The third order was: General Campan will move through the wood to -seize the first fortification. General Campan's division did not seize -the first fortification but was driven back, for on emerging from -the wood it had to reform under grapeshot, of which Napoleon was -unaware. - -The fourth order was: The vice-King will occupy the village -(Borodino) and cross by its three bridges, advancing to the same -heights as Morand's and Gdrard's divisions (for whose movements no -directions are given), which under his leadership will be directed -against the redoubt and come into line with the rest of the forces. - -As far as one can make out, not so much from this unintelligible -sentence as from the attempts the vice-King made to execute the orders -given him, he was to advance from the left through Borodino to the -redoubt while the divisions of Morand and Gerard were to advance -simultaneously from the front. - -All this, like the other parts of the disposition, was not and could -not be executed. After passing through Borodino the vice-King was -driven back to the Kolocha and could get no farther; while the -divisions of Morand and Gerard did not take the redoubt but were -driven back, and the redoubt was only taken at the end of the battle -by the cavalry (a thing probably unforeseen and not heard of by -Napoleon). So not one of the orders in the disposition was, or could -be, executed. But in the disposition it is said that, after the -fight has commenced in this manner, orders will be given in accordance -with the enemy's movements, and so it might be supposed that all -necessary arrangements would be made by Napoleon during the battle. -But this was not and could not be done, for during the whole battle -Napoleon was so far away that, as appeared later, he could not know -the course of the battle and not one of his orders during the fight -could be executed. - - - - - -CHAPTER XXVIII - - -Many historians say that the French did not win the battle of -Borodino because Napoleon had a cold, and that if he had not had a -cold the orders he gave before and during the battle would have been -still more full of genius and Russia would have been lost and the face -of the world have been changed. To historians who believe that -Russia was shaped by the will of one man--Peter the Great--and that -France from a republic became an empire and French armies went to -Russia at the will of one man--Napoleon--to say that Russia remained a -power because Napoleon had a bad cold on the twenty-fourth of August -may seem logical and convincing. - -If it had depended on Napoleon's will to fight or not to fight the -battle of Borodino, and if this or that other arrangement depended -on his will, then evidently a cold affecting the manifestation of -his will might have saved Russia, and consequently the valet who -omitted to bring Napoleon his waterproof boots on the twenty-fourth -would have been the savior of Russia. Along that line of thought -such a deduction is indubitable, as indubitable as the deduction -Voltaire made in jest (without knowing what he was jesting at) when he -saw that the Massacre of St. Bartholomew was due to Charles IX's -stomach being deranged. But to men who do not admit that Russia was -formed by the will of one man, Peter I, or that the French Empire -was formed and the war with Russia begun by the will of one man, -Napoleon, that argument seems not merely untrue and irrational, but -contrary to all human reality. To the question of what causes historic -events another answer presents itself, namely, that the course of -human events is predetermined from on high--depends on the coincidence -of the wills of all who take part in the events, and that a Napoleon's -influence on the course of these events is purely external and -fictitious. - -Strange as at first glance it may seem to suppose that the -Massacre of St. Bartholomew was not due to Charles IX's will, though -he gave the order for it and thought it was done as a result of that -order; and strange as it may seem to suppose that the slaughter of -eighty thousand men at Borodino was not due to Napoleon's will, though -he ordered the commencement and conduct of the battle and thought it -was done because he ordered it; strange as these suppositions -appear, yet human dignity--which tells me that each of us is, if not -more at least not less a man than the great Napoleon--demands the -acceptance of that solution of the question, and historic -investigation abundantly confirms it. - -At the battle of Borodino Napoleon shot at no one and killed no one. -That was all done by the soldiers. Therefore it was not he who -killed people. - -The French soldiers went to kill and be killed at the battle of -Borodino not because of Napoleon's orders but by their own volition. -The whole army--French, Italian, German, Polish, and Dutch--hungry, -ragged, and weary of the campaign, felt at the sight of an army -blocking their road to Moscow that the wine was drawn and must be -drunk. Had Napoleon then forbidden them to fight the Russians, they -would have killed him and have proceeded to fight the Russians because -it was inevitable. - -When they heard Napoleon's proclamation offering them, as -compensation for mutilation and death, the words of posterity about -their having been in the battle before Moscow, they cried "Vive -l'Empereur!" just as they had cried "Vive l'Empereur!" at the sight of -the portrait of the boy piercing the terrestrial globe with a toy -stick, and just as they would have cried "Vive l'Empereur!" at any -nonsense that might be told them. There was nothing left for them to -do but cry "Vive l'Empereur!" and go to fight, in order to get food -and rest as conquerors in Moscow. So it was not because of -Napoleon's commands that they killed their fellow men. - -And it was not Napoleon who directed the course of the battle, for -none of his orders were executed and during the battle he did not know -what was going on before him. So the way in which these people -killed one another was not decided by Napoleon's will but occurred -independently of him, in accord with the will of hundreds of thousands -of people who took part in the common action. It only seemed to -Napoleon that it all took place by his will. And so the question -whether he had or had not a cold has no more historic interest than -the cold of the least of the transport soldiers. - -Moreover, the assertion made by various writers that his cold was -the cause of his dispositions not being as well planned as on former -occasions, and of his orders during the battle not being as good as -previously, is quite baseless, which again shows that Napoleon's -cold on the twenty-sixth of August was unimportant. - -The dispositions cited above are not at all worse, but are even -better, than previous dispositions by which he had won victories. -His pseudo-orders during the battle were also no worse than -formerly, but much the same as usual. These dispositions and orders -only seem worse than previous ones because the battle of Borodino -was the first Napoleon did not win. The profoundest and most excellent -dispositions and orders seem very bad, and every learned militarist -criticizes them with looks of importance, when they relate to a -battle that has been lost, and the very worst dispositions and -orders seem very good, and serious people fill whole volumes to -demonstrate their merits, when they relate to a battle that has been -won. - -The dispositions drawn up by Weyrother for the battle of -Austerlitz were a model of perfection for that kind of composition, -but still they were criticized--criticized for their very -perfection, for their excessive minuteness. - -Napoleon at the battle of Borodino fulfilled his office as -representative of authority as well as, and even better than, at other -battles. He did nothing harmful to the progress of the battle; he -inclined to the most reasonable opinions, he made no confusion, did -not contradict himself, did not get frightened or run away from the -field of battle, but with his great tact and military experience -carried out his role of appearing to command, calmly and with dignity. - - - - - -CHAPTER XXIX - - -On returning from a second inspection of the lines, Napoleon -remarked: - -"The chessmen are set up, the game will begin tomorrow!" - -Having ordered punch and summoned de Beausset, he began to talk to -him about Paris and about some changes he meant to make the Empress' -household, surprising the prefect by his memory of minute details -relating to the court. - -He showed an interest in trifles, joked about de Beausset's love -of travel, and chatted carelessly, as a famous, self-confident surgeon -who knows his job does when turning up his sleeves and putting on -his apron while a patient is being strapped to the operating table. -"The matter is in my hands and is clear and definite in my head. -When the times comes to set to work I shall do it as no one else -could, but now I can jest, and the more I jest and the calmer I am the -more tranquil and confident you ought to be, and the more amazed at my -genius." - -Having finished his second glass of punch, Napoleon went to rest -before the serious business which, he considered, awaited him next -day. He was so much interested in that task that he was unable to -sleep, and in spite of his cold which had grown worse from the -dampness of the evening, he went into the large division of the tent -at three o'clock in the morning, loudly blowing his nose. He asked -whether the Russians had not withdrawn, and was told that the -enemy's fires were still in the same places. He nodded approval. - -The adjutant in attendance came into the tent. - -"Well, Rapp, do you think we shall do good business today?" Napoleon -asked him. - -"Without doubt, sire," replied Rapp. - -Napoleon looked at him. - -"Do you remember, sire, what you did me the honor to say at -Smolensk?" continued Rapp. "The wine is drawn and must be drunk." - -Napoleon frowned and sat silent for a long time leaning his head -on his hand. - -"This poor army!" he suddenly remarked. "It has diminished greatly -since Smolensk. Fortune is frankly a courtesan, Rapp. I have always -said so and I am beginning to experience it. But the Guards, Rapp, the -Guards are intact?" he remarked interrogatively. - -"Yes, sire," replied Rapp. - -Napoleon took a lozenge, put it in his mouth, and glanced at his -watch. He was not sleepy and it was still not nearly morning. It was -impossible to give further orders for the sake of killing time, for -the orders had all been given and were now being executed. - -"Have the biscuits and rice been served out to the regiments of -the Guards?" asked Napoleon sternly. - -"Yes, sire." - -"The rice too?" - -Rapp replied that he had given the Emperor's order about the rice, -but Napoleon shook his head in dissatisfaction as if not believing -that his order had been executed. An attendant came in with punch. -Napoleon ordered another glass to be brought for Rapp, and silently -sipped his own. - -"I have neither taste nor smell," he remarked, sniffing at his -glass. "This cold is tiresome. They talk about medicine--what is the -good of medicine when it can't cure a cold! Corvisart gave me these -lozenges but they don't help at all. What can doctors cure? One -can't cure anything. Our body is a machine for living. It is organized -for that, it is its nature. Let life go on in it unhindered and let it -defend itself, it will do more than if you paralyze it by -encumbering it with remedies. Our body is like a perfect watch that -should go for a certain time; watchmaker cannot open it, he can only -adjust it by fumbling, and that blindfold.... Yes, our body is just -a machine for living, that is all." - -And having entered on the path of definition, of which he was -fond, Napoleon suddenly and unexpectedly gave a new one. - -"Do you know, Rapp, what military art is?" asked he. "It is the -art of being stronger than the enemy at a given moment. That's all." - -Rapp made no reply. - -"Tomorrow we shall have to deal with Kutuzov!" said Napoleon. "We -shall see! Do you remember at Braunau he commanded an army for three -weeks and did not once mount a horse to inspect his -entrenchments.... We shall see!" - -He looked at his watch. It was still only four o'clock. He did not -feel sleepy. The punch was finished and there was still nothing to do. -He rose, walked to and fro, put on a warm overcoat and a hat, and went -out of the tent. The night was dark and damp, a scarcely perceptible -moisture was descending from above. Near by, the campfires were -dimly burning among the French Guards, and in the distance those of -the Russian line shone through the smoke. The weather was calm, and -the rustle and tramp of the French troops already beginning to move to -take up their positions were clearly audible. - -Napoleon walked about in front of his tent, looked at the fires -and listened to these sounds, and as he was passing a tall guardsman -in a shaggy cap, who was standing sentinel before his tent and had -drawn himself up like a black pillar at sight of the Emperor, Napoleon -stopped in front of him. - -"What year did you enter the service?" he asked with that -affectation of military bluntness and geniality with which he always -addressed the soldiers. - -The man answered the question. - -"Ah! One of the old ones! Has your regiment had its rice?" - -"It has, Your Majesty." - -Napoleon nodded and walked away. - - -At half-past five Napoleon rode to the village of Shevardino. - -It was growing light, the sky was clearing, only a single cloud -lay in the east. The abandoned campfires were burning themselves out -in the faint morning light. - -On the right a single deep report of a cannon resounded and died -away in the prevailing silence. Some minutes passed. A second and a -third report shook the air, then a fourth and a fifth boomed -solemnly near by on the right. - -The first shots had not yet ceased to reverberate before others rang -out and yet more were heard mingling with and overtaking one another. - -Napoleon with his suite rode up to the Shevardino Redoubt where he -dismounted. The game had begun. - - - - - -CHAPTER XXX - - -On returning to Gorki after having seen Prince Andrew, Pierre -ordered his groom to get the horses ready and to call him early in the -morning, and then immediately fell asleep behind a partition in a -corner Boris had given up to him. - -Before he was thoroughly awake next morning everybody had already -left the hut. The panes were rattling in the little windows and his -groom was shaking him. - -"Your excellency! Your excellency! Your excellency!" he kept -repeating pertinaciously while he shook Pierre by the shoulder without -looking at him, having apparently lost hope of getting him to wake up. - -"What? Has it begun? Is it time?" Pierre asked, waking up. - -"Hear the firing," said the groom, a discharged soldier. "All the -gentlemen have gone out, and his Serene Highness himself rode past -long ago." - -Pierre dressed hastily and ran out to the porch. Outside all was -bright, fresh, dewy, and cheerful. The sun, just bursting forth from -behind a cloud that had concealed it, was shining, with rays still -half broken by the clouds, over the roofs of the street opposite, on -the dew-besprinkled dust of the road, on the walls of the houses, on -the windows, the fence, and on Pierre's horses standing before the -hut. The roar of guns sounded more distinct outside. An adjutant -accompanied by a Cossack passed by at a sharp trot. - -"It's time, Count; it's time!" cried the adjutant. - -Telling the groom to follow him with the horses, Pierre went down -the street to the knoll from which he had looked at the field of -battle the day before. A crowd of military men was assembled there, -members of the staff could be heard conversing in French, and -Kutuzov's gray head in a white cap with a red band was visible, his -gray nape sunk between his shoulders. He was looking through a field -glass down the highroad before him. - -Mounting the steps to the knoll Pierre looked at the scene before -him, spellbound by beauty. It was the same panorama he had admired -from that spot the day before, but now the whole place was full of -troops and covered by smoke clouds from the guns, and the slanting -rays of the bright sun, rising slightly to the left behind Pierre, -cast upon it through the clear morning air penetrating streaks of -rosy, golden tinted light and long dark shadows. The forest at the -farthest extremity of the panorama seemed carved in some precious -stone of a yellowish-green color; its undulating outline was -silhouetted against the horizon and was pierced beyond Valuevo by -the Smolensk highroad crowded with troops. Nearer at hand glittered -golden cornfields interspersed with copses. There were troops to be -seen everywhere, in front and to the right and left. All this was -vivid, majestic, and unexpected; but what impressed Pierre most of all -was the view of the battlefield itself, of Borodino and the hollows on -both sides of the Kolocha. - -Above the Kolocha, in Borodino and on both sides of it, especially -to the left where the Voyna flowing between its marshy banks falls -into the Kolocha, a mist had spread which seemed to melt, to dissolve, -and to become translucent when the brilliant sun appeared and -magically colored and outlined everything. The smoke of the guns -mingled with this mist, and over the whole expanse and through that -mist the rays of the morning sun were reflected, flashing back like -lightning from the water, from the dew, and from the bayonets of the -troops crowded together by the riverbanks and in Borodino. A white -church could be seen through the mist, and here and there the roofs of -huts in Borodino as well as dense masses of soldiers, or green -ammunition chests and ordnance. And all this moved, or seemed to move, -as the smoke and mist spread out over the whole space. Just as in -the mist-enveloped hollow near Borodino, so along the entire line -outside and above it and especially in the woods and fields to the -left, in the valleys and on the summits of the high ground, clouds -of powder smoke seemed continually to spring up out of nothing, now -singly, now several at a time, some translucent, others dense, -which, swelling, growing, rolling, and blending, extended over the -whole expanse. - -These puffs of smoke and (strange to say) the sound of -the firing produced the chief beauty of the spectacle. - -"Puff!"--suddenly a round compact cloud of smoke was seen merging -from violet into gray and milky white, and "boom!" came the report a -second later. - -"Puff! puff!"--and two clouds arose pushing one another and blending -together; and "boom, boom!" came the sounds confirming what the eye -had seen. - -Pierre glanced round at the first cloud, which he had seen as a -round compact ball, and in its place already were balloons of smoke -floating to one side, and--"puff" (with a pause)--"puff, puff!" -three and then four more appeared and then from each, with the same -interval--"boom--boom, boom!" came the fine, firm, precise sounds in -reply. It seemed as if those smoke clouds sometimes ran and -sometimes stood still while woods, fields, and glittering bayonets ran -past them. From the left, over fields and bushes, those large balls of -smoke were continually appearing followed by their solemn reports, -while nearer still, in the hollows and woods, there burst from the -muskets small cloudlets that had no time to become balls, but had -their little echoes in just the same way. "Trakh-ta-ta-takh!" came the -frequent crackle of musketry, but it was irregular and feeble in -comparison with the reports of the cannon. - -Pierre wished to be there with that smoke, those shining bayonets, -that movement, and those sounds. He turned to look at Kutuzov and -his suite, to compare his impressions with those of others. They -were all looking at the field of battle as he was, and, as it seemed -to him, with the same feelings. All their faces were now shining -with that latent warmth of feeling Pierre had noticed the day before -and had fully understood after his talk with Prince Andrew. - -"Go, my dear fellow, go... and Christ be with you!" Kutuzov was -saying to a general who stood beside him, not taking his eye from -the battlefield. - -Having received this order the general passed by Pierre on his way -down the knoll. - -"To the crossing!" said the general coldly and sternly in reply to -one of the staff who asked where he was going. - -"I'll go there too, I too!" thought Pierre, and followed the -general. - -The general mounted a horse a Cossack had brought him. Pierre went -to his groom who was holding his horses and, asking which was the -quietest, clambered onto it, seized it by the mane, and turning out -his toes pressed his heels against its sides and, feeling that his -spectacles were slipping off but unable to let go of the mane and -reins, he galloped after the general, causing the staff officers to -smile as they watched him from the knoll. - - - - - -CHAPTER XXXI - - -Having descended the hill the general after whom Pierre was -galloping turned sharply to the left, and Pierre, losing sight of him, -galloped in among some ranks of infantry marching ahead of him. He -tried to pass either in front of them or to the right or left, but -there were soldiers everywhere, all with expression and busy with some -unseen but evidently important task. They all gazed with the same -dissatisfied and inquiring expression at this stout man in a white -hat, who for some unknown reason threatened to trample them under -his horse's hoofs. - -"Why ride into the middle of the battalion?" one of them shouted -at him. - -Another prodded his horse with the butt end of a musket, and Pierre, -bending over his saddlebow and hardly able to control his shying -horse, galloped ahead of the soldiers where there was a free space. - -There was a bridge ahead of him, where other soldiers stood -firing. Pierre rode up to them. Without being aware of it he had -come to the bridge across the Kolocha between Gorki and Borodino, -which the French (having occupied Borodino) were attacking in the -first phase of the battle. Pierre saw that there was a bridge in front -of him and that soldiers were doing something on both sides of it -and in the meadow, among the rows of new-mown hay which he had taken -no notice of amid the smoke of the campfires the day before; but -despite the incessant firing going on there he had no idea that this -was the field of battle. He did not notice the sound of the bullets -whistling from every side, or the projectiles that flew over him, -did not see the enemy on the other side of the river, and for a long -time did not notice the killed and wounded, though many fell near him. -He looked about him with a smile which did not leave his face. - -"Why's that fellow in front of the line?" shouted somebody at him -again. - -"To the left!... Keep to the right!" the men shouted to him. - -Pierre went to the right, and unexpectedly encountered one of -Raevski's adjutants whom he knew. The adjutant looked angrily at -him, evidently also intending to shout at him, but on recognizing -him he nodded. - -"How have you got here?" he said, and galloped on. - -Pierre, feeling out of place there, having nothing to do, and afraid -of getting in someone's way again, galloped after the adjutant. - -"What's happening here? May I come with you?" he asked. - -"One moment, one moment!" replied the adjutant, and riding up to a -stout colonel who was standing in the meadow, he gave him some message -and then addressed Pierre. - -"Why have you come here, Count?" he asked with a smile. "Still -inquisitive?" - -"Yes, yes," assented Pierre. - -But the adjutant turned his horse about and rode on. - -"Here it's tolerable," said he, "but with Bagration on the left -flank they're getting it frightfully hot." - -"Really?" said Pierre. "Where is that?" - -"Come along with me to our knoll. We can get a view from there and -in our battery it is still bearable," said the adjutant. "Will you -come?" - -"Yes, I'll come with you," replied Pierre, looking round for his -groom. - -It was only now that he noticed wounded men staggering along or -being carried on stretchers. On that very meadow he had ridden over -the day before, a soldier was lying athwart the rows of scented hay, -with his head thrown awkwardly back and his shako off. - -"Why haven't they carried him away?" Pierre was about to ask, but -seeing the stern expression of the adjutant who was also looking -that way, he checked himself. - -Pierre did not find his groom and rode along the hollow with the -adjutant to Raevski's Redoubt. His horse lagged behind the -adjutant's and jolted him at every step. - -"You don't seem to be used to riding, Count?" remarked the adjutant. - -"No it's not that, but her action seems so jerky," said Pierre in -a puzzled tone. - -"Why... she's wounded!" said the adjutant. "In the off foreleg above -the knee. A bullet, no doubt. I congratulate you, Count, on your -baptism of fire!" - -Having ridden in the smoke past the Sixth Corps, behind the -artillery which had been moved forward and was in action, deafening -them with the noise of firing, they came to a small wood. There it was -cool and quiet, with a scent of autumn. Pierre and the adjutant -dismounted and walked up the hill on foot. - -"Is the general here?" asked the adjutant on reaching the knoll. - -"He was here a minute ago but has just gone that way," someone -told him, pointing to the right. - -The adjutant looked at Pierre as if puzzled what to do with him now. - -"Don't trouble about me," said Pierre. "I'll go up onto the knoll if -I may?" - -"Yes, do. You'll see everything from there and it's less -dangerous, and I'll come for you." - -Pierre went to the battery and the adjutant rode on. They did not -meet again, and only much later did Pierre learn that he lost an arm -that day. - -The knoll to which Pierre ascended was that famous one afterwards -known to the Russians as the Knoll Battery or Raevski's Redoubt, and -to the French as la grande redoute, la fatale redoute, la redoute du -centre, around which tens of thousands fell, and which the French -regarded as the key to the whole position. - -This redoubt consisted of a knoll, on three sides of which -trenches had been dug. Within the entrenchment stood ten guns that -were being fired through openings in the earthwork. - -In line with the knoll on both sides stood other guns which also -fired incessantly. A little behind the guns stood infantry. When -ascending that knoll Pierre had no notion that this spot, on which -small trenches had been dug and from which a few guns were firing, was -the most important point of the battle. - -On the contrary, just because he happened to be there he thought -it one of the least significant parts of the field. - -Having reached the knoll, Pierre sat down at one end of a trench -surrounding the battery and gazed at what was going on around him with -an unconsciously happy smile. Occasionally he rose and walked about -the battery still with that same smile, trying not to obstruct the -soldiers who were loading, hauling the guns, and continually running -past him with bags and charges. The guns of that battery were being -fired continually one after another with a deafening roar, -enveloping the whole neighborhood in powder smoke. - -In contrast with the dread felt by the infantrymen placed in -support, here in the battery where a small number of men busy at their -work were separated from the rest by a trench, everyone experienced -a common and as it were family feeling of animation. - -The intrusion of Pierre's nonmilitary figure in a white hat made -an unpleasant impression at first. The soldiers looked askance at -him with surprise and even alarm as they went past him. The senior -artillery officer, a tall, long-legged, pockmarked man, moved over -to Pierre as if to see the action of the farthest gun and looked at -him with curiosity. - -A young round-faced officer, quite a boy still and evidently only -just out of the Cadet College, who was zealously commanding the two -guns entrusted to him, addressed Pierre sternly. - -"Sir," he said, "permit me to ask you to stand aside. You must not -be here." - -The soldiers shook their heads disapprovingly as they looked at -Pierre. But when they had convinced themselves that this man in the -white hat was doing no harm, but either sat quietly on the slope of -the trench with a shy smile or, politely making way for the -soldiers, paced up and down the battery under fire as calmly as if -he were on a boulevard, their feeling of hostile distrust gradually -began to change into a kindly and bantering sympathy, such as soldiers -feel for their dogs, cocks, goats, and in general for the animals that -live with the regiment. The men soon accepted Pierre into their -family, adopted him, gave him a nickname ("our gentleman"), and made -kindly fun of him among themselves. - -A shell tore up the earth two paces from Pierre and he looked around -with a smile as he brushed from his clothes some earth it had thrown -up. - -"And how's it you're not afraid, sir, really now?" a red-faced, -broad-shouldered soldier asked Pierre, with a grin that disclosed a -set of sound, white teeth. - -"Are you afraid, then?" said Pierre. - -"What else do you expect?" answered the soldier. "She has no -mercy, you know! When she comes spluttering down, out go your innards. -One can't help being afraid," he said laughing. - -Several of the men, with bright kindly faces, stopped beside Pierre. -They seemed not to have expected him to talk like anybody else, and -the discovery that he did so delighted them. - -"It's the business of us soldiers. But in a gentleman it's -wonderful! There's a gentleman for you!" - -"To your places!" cried the young officer to the men gathered -round Pierre. - -The young officer was evidently exercising his duties for the -first or second time and therefore treated both his superiors and -the men with great precision and formality. - -The booming cannonade and the fusillade of musketry were growing -more intense over the whole field, especially to the left where -Bagration's fleches were, but where Pierre was the smoke of the firing -made it almost impossible to distinguish anything. Moreover, his whole -attention was engrossed by watching the family circle--separated -from all else--formed by the men in the battery. His first unconscious -feeling of joyful animation produced by the sights and sounds of the -battlefield was now replaced by another, especially since he had -seen that soldier lying alone in the hayfield. Now, seated on the -slope of the trench, he observed the faces of those around him. - -By ten o'clock some twenty men had already been carried away from -the battery; two guns were smashed and cannon balls fell more and more -frequently on the battery and spent bullets buzzed and whistled -around. But the men in the battery seemed not to notice this, and -merry voices and jokes were heard on all sides. - -"A live one!" shouted a man as a whistling shell approached. - -"Not this way! To the infantry!" added another with loud laughter, -seeing the shell fly past and fall into the ranks of the supports. - -"Are you bowing to a friend, eh?" remarked another, chaffing a -peasant who ducked low as a cannon ball flew over. - -Several soldiers gathered by the wall of the trench, looking out -to see what was happening in front. - -"They've withdrawn the front line, it has retired," said they, -pointing over the earthwork. - -"Mind your own business," an old sergeant shouted at them. "If -they've retired it's because there's work for them to do farther -back." - -And the sergeant, taking one of the men by the shoulders, gave him a -shove with his knee. This was followed by a burst of laughter. - -"To the fifth gun, wheel it up!" came shouts from one side. - -"Now then, all together, like bargees!" rose the merry voices of -those who were moving the gun. - -"Oh, she nearly knocked our gentleman's hat off!" cried the -red-faced humorist, showing his teeth chaffing Pierre. "Awkward -baggage!" he added reproachfully to a cannon ball that struck a cannon -wheel and a man's leg. - -"Now then, you foxes!" said another, laughing at some militiamen -who, stooping low, entered the battery to carry away the wounded man. - -"So this gruel isn't to your taste? Oh, you crows! You're scared!" -they shouted at the militiamen who stood hesitating before the man -whose leg had been torn off. - -"There, lads... oh, oh!" they mimicked the peasants, "they don't -like it at all!" - -Pierre noticed that after every ball that hit the redoubt, and after -every loss, the liveliness increased more and more. - -As the flames of the fire hidden within come more and more vividly -and rapidly from an approaching thundercloud, so, as if in -opposition to what was taking place, the lightning of hidden fire -growing more and more intense glowed in the faces of these men. - -Pierre did not look out at the battlefield and was not concerned -to know what was happening there; he was entirely absorbed in watching -this fire which burned ever more brightly and which he felt was -flaming up in the same way in his own soul. - -At ten o'clock the infantry that had been among the bushes in -front of the battery and along the Kamenka streamlet retreated. From -the battery they could be seen running back past it carrying their -wounded on their muskets. A general with his suite came to the -battery, and after speaking to the colonel gave Pierre an angry look -and went away again having ordered the infantry supports behind the -battery to lie down, so as to be less exposed to fire. After this from -amid the ranks of infantry to the right of the battery came the -sound of a drum and shouts of command, and from the battery one saw -how those ranks of infantry moved forward. - -Pierre looked over the wall of the trench and was particularly -struck by a pale young officer who, letting his sword hang down, was -walking backwards and kept glancing uneasily around. - -The ranks of the infantry disappeared amid the smoke but their -long-drawn shout and rapid musketry firing could still be heard. A few -minutes later crowds of wounded men and stretcher-bearers came back -from that direction. Projectiles began to fall still more frequently -in the battery. Several men were lying about who had not been removed. -Around the cannon the men moved still more briskly and busily. No -one any longer took notice of Pierre. Once or twice he was shouted -at for being in the way. The senior officer moved with big, rapid -strides from one gun to another with a frowning face. The young -officer, with his face still more flushed, commanded the men more -scrupulously than ever. The soldiers handed up the charges, turned, -loaded, and did their business with strained smartness. They gave -little jumps as they walked, as though they were on springs. - -The stormcloud had come upon them, and in every face the fire -which Pierre had watched kindle burned up brightly. Pierre standing -beside the commanding officer. The young officer, his hand to his -shako, ran up to his superior. - -"I have the honor to report, sir, that only eight rounds are left. -Are we to continue firing?" he asked. - -"Grapeshot!" the senior shouted, without answering the question, -looking over the wall of the trench. - -Suddenly something happened: the young officer gave a gasp and -bending double sat down on the ground like a bird shot on the wing. -Everything became strange, confused, and misty in Pierre's eyes. - -One cannon ball after another whistled by and struck the -earthwork, a soldier, or a gun. Pierre, who had not noticed these -sounds before, now heard nothing else. On the right of the battery -soldiers shouting "Hurrah!" were running not forwards but backwards, -it seemed to Pierre. - -A cannon ball struck the very end of the earth work by which he -was standing, crumbling down the earth; a black ball flashed before -his eyes and at the same instant plumped into something. Some -militiamen who were entering the battery ran back. - -"All with grapeshot!" shouted the officer. - -The sergeant ran up to the officer and in a frightened whisper -informed him (as a butler at dinner informs his master that there is -no more of some wine asked for) that there were no more charges. - -"The scoundrels! What are they doing?" shouted the officer, -turning to Pierre. - -The officer's face was red and perspiring and his eyes glittered -under his frowning brow. - -"Run to the reserves and bring up the ammunition boxes!" he -yelled, angrily avoiding Pierre with his eyes and speaking to his men. - -"I'll go," said Pierre. - -The officer, without answering him, strode across to the opposite -side. - -"Don't fire.... Wait!" he shouted. - -The man who had been ordered to go for ammunition stumbled against -Pierre. - -"Eh, sir, this is no place for you," said he, and ran down the -slope. - -Pierre ran after him, avoiding the spot where the young officer -was sitting. - -One cannon ball, another, and a third flew over him, falling in -front, beside, and behind him. Pierre ran down the slope. "Where am -I going?" he suddenly asked himself when he was already near the green -ammunition wagons. He halted irresolutely, not knowing whether to -return or go on. Suddenly a terrible concussion threw him backwards to -the ground. At the same instant he was dazzled by a great flash of -flame, and immediately a deafening roar, crackling, and whistling made -his ears tingle. - -When he came to himself he was sitting on the ground leaning on -his hands; the ammunition wagons he had been approaching no longer -existed, only charred green boards and rags littered the scorched -grass, and a horse, dangling fragments of its shaft behind it, -galloped past, while another horse lay, like Pierre, on the ground, -uttering prolonged and piercing cries. - - - - - -CHAPTER XXXII - - -Beside himself with terror Pierre jumped up and ran back to the -battery, as to the only refuge from the horrors that surrounded him. - -On entering the earthwork he noticed that there were men doing -something there but that no shots were being fired from the battery. -He had no time to realize who these men were. He saw the senior -officer lying on the earth wall with his back turned as if he were -examining something down below and that one of the soldiers he had -noticed before was struggling forward shouting "Brothers!" and -trying to free himself from some men who were holding him by the -arm. He also saw something else that was strange. - -But he had not time to realize that the colonel had been killed, -that the soldier shouting "Brothers!" was a prisoner, and that another -man had been bayoneted in the back before his eyes, for hardly had -he run into the redoubt before a thin, sallow-faced, perspiring man in -a blue uniform rushed on him sword in hand, shouting something. -Instinctively guarding against the shock--for they had been running -together at full speed before they saw one another--Pierre put out his -hands and seized the man (a French officer) by the shoulder with one -hand and by the throat with the other. The officer, dropping his -sword, seized Pierre by his collar. - -For some seconds they gazed with frightened eyes at one another's -unfamiliar faces and both were perplexed at what they had done and -what they were to do next. "Am I taken prisoner or have I taken him -prisoner?" each was thinking. But the French officer was evidently -more inclined to think he had been taken prisoner because Pierre's -strong hand, impelled by instinctive fear, squeezed his throat ever -tighter and tighter. The Frenchman was about to say something, when -just above their heads, terrible and low, a cannon ball whistled, -and it seemed to Pierre that the French officer's head had been torn -off, so swiftly had he ducked it. - -Pierre too bent his head and let his hands fall. Without further -thought as to who had taken whom prisoner, the Frenchman ran back to -the battery and Pierre ran down the slope stumbling over the dead -and wounded who, it seemed to him, caught at his feet. But before he -reached the foot of the knoll he was met by a dense crowd of Russian -soldiers who, stumbling, tripping up, and shouting, ran merrily and -wildly toward the battery. (This was the attack for which Ermolov -claimed the credit, declaring that only his courage and good luck made -such a feat possible: it was the attack in which he was said to have -thrown some St. George's Crosses he had in his pocket into the battery -for the first soldiers to take who got there.) - -The French who had occupied the battery fled, and our troops -shouting "Hurrah!" pursued them so far beyond the battery that it -was difficult to call them back. - -The prisoners were brought down from the battery and among them -was a wounded French general, whom the officers surrounded. Crowds -of wounded--some known to Pierre and some unknown--Russians and -French, with faces distorted by suffering, walked, crawled, and were -carried on stretchers from the battery. Pierre again went up onto -the knoll where he had spent over an hour, and of that family circle -which had received him as a member he did not find a single one. There -were many dead whom he did not know, but some he recognized. The young -officer still sat in the same way, bent double, in a pool of blood -at the edge of the earth wall. The red-faced man was still -twitching, but they did not carry him away. - -Pierre ran down the slope once more. - -"Now they will stop it, now they will be horrified at what they have -done!" he thought, aimlessly going toward a crowd of stretcher bearers -moving from the battlefield. - -But behind the veil of smoke the sun was still high, and in front -and especially to the left, near Semenovsk, something seemed to be -seething in the smoke, and the roar of cannon and musketry did not -diminish, but even increased to desperation like a man who, -straining himself, shrieks with all his remaining strength. - - - - - -CHAPTER XXXIII - - -The chief action of the battle of Borodino was fought within the -seven thousand feet between Borodino and Bagration's fleches. Beyond -that space there was, on the one side, a demonstration made by the -Russians with Uvarov's cavalry at midday, and on the other side, -beyond Utitsa, Poniatowski's collision with Tuchkov; but these two -were detached and feeble actions in comparison with what took place in -the center of the battlefield. On the field between Borodino and the -fleches, beside the wood, the chief action of the day took place on an -open space visible from both sides and was fought in the simplest -and most artless way. - -The battle began on both sides with a cannonade from several hundred -guns. - -Then when the whole field was covered with smoke, two divisions, -Campan's and Dessaix's, advanced from the French right, while -Murat's troops advanced on Borodino from their left. - -From the Shevardino Redoubt where Napoleon was standing the -fleches were two thirds of a mile away, and it was more than a mile as -the crow flies to Borodino, so that Napoleon could not see what was -happening there, especially as the smoke mingling with the mist hid -the whole locality. The soldiers of Dessaix's division advancing -against the fleches could only be seen till they had entered the -hollow that lay between them and the fleches. As soon as they had -descended into that hollow, the smoke of the guns and musketry on -the fleches grew so dense that it covered the whole approach on that -side of it. Through the smoke glimpses could be caught of something -black--probably men--and at times the glint of bayonets. But whether -they were moving or stationary, whether they were French or Russian, -could not be discovered from the Shevardino Redoubt. - -The sun had risen brightly and its slanting rays struck straight -into Napoleon's face as, shading his eyes with his hand, he looked -at the fleches. The smoke spread out before them, and at times it -looked as if the smoke were moving, at times as if the troops moved. -Sometimes shouts were heard through the firing, but it was -impossible to tell what was being done there. - -Napoleon, standing on the knoll, looked through a field glass, and -in its small circlet saw smoke and men, sometimes his own and -sometimes Russians, but when he looked again with the naked eye, he -could not tell where what he had seen was. - -He descended the knoll and began walking up and down before it. - -Occasionally he stopped, listened to the firing, and gazed -intently at the battlefield. - -But not only was it impossible to make out what was happening from -where he was standing down below, or from the knoll above on which -some of his generals had taken their stand, but even from the -fleches themselves--in which by this time there were now Russian and -now French soldiers, alternately or together, dead, wounded, alive, -frightened, or maddened--even at those fleches themselves it was -impossible to make out what was taking place. There for several -hours amid incessant cannon and musketry fire, now Russians were -seen alone, now Frenchmen alone, now infantry, and now cavalry: they -appeared, fired, fell, collided, not knowing what to do with one -another, screamed, and ran back again. - -From the battlefield adjutants he had sent out, and orderlies from -his marshals, kept galloping up to Napoleon with reports of the -progress of the action, but all these reports were false, both because -it was impossible in the heat of battle to say what was happening at -any given moment and because many of the adjutants did not go to the -actual place of conflict but reported what they had heard from others; -and also because while an adjutant was riding more than a mile to -Napoleon circumstances changed and the news he brought was already -becoming false. Thus an adjutant galloped up from Murat with tidings -that Borodino had been occupied and the bridge over the Kolocha was in -the hands of the French. The adjutant asked whether Napoleon wished -the troops to cross it? Napoleon gave orders that the troops should -form up on the farther side and wait. But before that order was given- -almost as soon in fact as the adjutant had left Borodino--the bridge -had been retaken by the Russians and burned, in the very skirmish at -which Pierre had been present at the beginning of the battle. - -An adjutant galloped up from the fleches with a pale and -frightened face and reported to Napoleon that their attack had been -repulsed, Campan wounded, and Davout killed; yet at the very time -the adjutant had been told that the French had been repulsed, the -fleches had in fact been recaptured by other French troops, and Davout -was alive and only slightly bruised. On the basis of these necessarily -untrustworthy reports Napoleon gave his orders, which had either -been executed before he gave them or could not be and were not -executed. - -The marshals and generals, who were nearer to the field of battle -but, like Napoleon, did not take part in the actual fighting and -only occasionally went within musket range, made their own -arrangements without asking Napoleon and issued orders where and in -what direction to fire and where cavalry should gallop and infantry -should run. But even their orders, like Napoleon's, were seldom -carried out, and then but partially. For the most part things happened -contrary to their orders. Soldiers ordered to advance ran back on -meeting grapeshot; soldiers ordered to remain where they were, -suddenly, seeing Russians unexpectedly before them, sometimes rushed -back and sometimes forward, and the cavalry dashed without orders in -pursuit of the flying Russians. In this way two cavalry regiments -galloped through the Semenovsk hollow and as soon as they reached -the top of the incline turned round and galloped full speed back -again. The infantry moved in the same way, sometimes running to -quite other places than those they were ordered to go to. All orders -as to where and when to move the guns, when to send infantry to -shoot or horsemen to ride down the Russian infantry--all such orders -were given by the officers on the spot nearest to the units concerned, -without asking either Ney, Davout, or Murat, much less Napoleon. -They did not fear getting into trouble for not fulfilling orders or -for acting on their own initiative, for in battle what is at stake -is what is dearest to man--his own life--and it sometimes seems that -safety lies in running back, sometimes in running forward; and these -men who were right in the heat of the battle acted according to the -mood of the moment. In reality, however, all these movements forward -and backward did not improve or alter the position of the troops. -All their rushing and galloping at one another did little harm, the -harm of disablement and death was caused by the balls and bullets that -flew over the fields on which these men were floundering about. As -soon as they left the place where the balls and bullets were flying -about, their superiors, located in the background, re-formed them -and brought them under discipline and under the influence of that -discipline led them back to the zone of fire, where under the -influence of fear of death they lost their discipline and rushed about -according to the chance promptings of the throng. - - - - - -CHAPTER XXXIV - - -Napoleon's generals--Davout, Ney, and Murat, who were near that -region of fire and sometimes even entered it--repeatedly led into it -huge masses of well-ordered troops. But contrary to what had always -happened in their former battles, instead of the news they expected of -the enemy's flight, these orderly masses returned thence as -disorganized and terrified mobs. The generals re-formed them, but -their numbers constantly decreased. In the middle of the day Murat -sent his adjutant to Napoleon to demand reinforcements. - -Napoleon sat at the foot of the knoll, drinking punch, when -Murat's adjutant galloped up with an assurance that the Russians would -be routed if His Majesty would let him have another division. - -"Reinforcements?" said Napoleon in a tone of stern surprise, looking -at the adjutant--a handsome lad with long black curls arranged like -Murat's own--as though he did not understand his words. - -"Reinforcements!" thought Napoleon to himself. "How can they need -reinforcements when they already have half the army directed against a -weak, unentrenched Russian wing?" - -"Tell the King of Naples," said he sternly, "that it is not noon -yet, and I don't yet see my chessboard clearly. Go!..." - -The handsome boy adjutant with the long hair sighed deeply without -removing his hand from his hat and galloped back to where men were -being slaughtered. - -Napoleon rose and having summoned Caulaincourt and Berthier began -talking to them about matters unconnected with the battle. - -In the midst of this conversation, which was beginning to interest -Napoleon, Berthier's eyes turned to look at a general with a suite, -who was galloping toward the knoll on a lathering horse. It was -Belliard. Having dismounted he went up to the Emperor with rapid -strides and in a loud voice began boldly demonstrating the necessity -of sending reinforcements. He swore on his honor that the Russians -were lost if the Emperor would give another division. - -Napoleon shrugged his shoulders and continued to pace up and down -without replying. Belliard began talking loudly and eagerly to the -generals of the suite around him. - -"You are very fiery, Belliard," said Napoleon, when he again came up -to the general. "In the heat of a battle it is easy to make a mistake. -Go and have another look and then come back to me." - -Before Belliard was out of sight, a messenger from another part of -the battlefield galloped up. - -"Now then, what do you want?" asked Napoleon in the tone of a man -irritated at being continually disturbed. - -"Sire, the prince..." began the adjutant. - -"Asks for reinforcements?" said Napoleon with an angry gesture. - -The adjutant bent his head affirmatively and began to report, but -the Emperor turned from him, took a couple of steps, stopped, came -back, and called Berthier. - -"We must give reserves," he said, moving his arms slightly apart. -"Who do you think should be sent there?" he asked of Berthier (whom he -subsequently termed "that gosling I have made an eagle"). - -"Send Claparede's division, sire," replied Berthier, who knew all -the divisions regiments, and battalions by heart. - -Napoleon nodded assent. - -The adjutant galloped to Claparede's division and a few minutes -later the Young Guards stationed behind the knoll moved forward. -Napoleon gazed silently in that direction. - -"No!" he suddenly said to Berthier. "I can't send Claparede. Send -Friant's division." - -Though there was no advantage in sending Friant's division instead -of Claparede's, and even in obvious inconvenience and delay in -stopping Claparede and sending Friant now, the order was carried out -exactly. Napoleon did not notice that in regard to his army he was -playing the part of a doctor who hinders by his medicines--a role he -so justly understood and condemned. - -Friant's division disappeared as the others had done into the -smoke of the battlefield. From all sides adjutants continued to arrive -at a gallop and as if by agreement all said the same thing. They all -asked for reinforcements and all said that the Russians were holding -their positions and maintaining a hellish fire under which the -French army was melting away. - -Napoleon sat on a campstool, wrapped in thought. - -M. de Beausset, the man so fond of travel, having fasted since -morning, came up to the Emperor and ventured respectfully to suggest -lunch to His Majesty. - -"I hope I may now congratulate Your Majesty on a victory?" said he. - -Napoleon silently shook his head in negation. Assuming the -negation to refer only to the victory and not to the lunch, M. de -Beausset ventured with respectful jocularity to remark that there is -no reason for not having lunch when one can get it. - -"Go away..." exclaimed Napoleon suddenly and morosely, and turned -aside. - -A beatific smile of regret, repentance, and ecstasy beamed on M. -de Beausset's face and he glided away to the other generals. - -Napoleon was experiencing a feeling of depression like that of an -ever-lucky gambler who, after recklessly flinging money about and -always winning, suddenly just when he has calculated all the chances -of the game, finds that the more he considers his play the more surely -he loses. - -His troops were the same, his generals the same, the same -preparations had been made, the same dispositions, and the same -proclamation courte et energique, he himself was still the same: he -knew that and knew that he was now even more experienced and -skillful than before. Even the enemy was the same as at Austerlitz and -Friedland--yet the terrible stroke of his arm had supernaturally -become impotent. - -All the old methods that had been unfailingly crowned with -success: the concentration of batteries on one point, an attack by -reserves to break the enemy's line, and a cavalry attack by "the men -of iron," all these methods had already been employed, yet not only -was there no victory, but from all sides came the same news of -generals killed and wounded, of reinforcements needed, of the -impossibility of driving back the Russians, and of disorganization -among his own troops. - -Formerly, after he had given two or three orders and uttered a few -phrases, marshals and adjutants had come galloping up with -congratulations and happy faces, announcing the trophies taken, the -corps of prisoners, bundles of enemy eagles and standards, cannon -and stores, and Murat had only begged leave to loose the cavalry to -gather in the baggage wagons. So it had been at Lodi, Marengo, Arcola, -Jena, Austerlitz, Wagram, and so on. But now something strange was -happening to his troops. - -Despite news of the capture of the fleches, Napoleon saw that this -was not the same, not at all the same, as what had happened in his -former battles. He saw that what he was feeling was felt by all the -men about him experienced in the art of war. All their faces looked -dejected, and they all shunned one another's eyes--only a de -Beausset could fail to grasp the meaning of what was happening. - -But Napoleon with his long experience of war well knew the meaning -of a battle not gained by the attacking side in eight hours, after all -efforts had been expended. He knew that it was a lost battle and -that the least accident might now--with the fight balanced on such a -strained center--destroy him and his army. - -When he ran his mind over the whole of this strange Russian campaign -in which not one battle had been won, and in which not a flag, or -cannon, or army corps had been captured in two months, when he -looked at the concealed depression on the faces around him and heard -reports of the Russians still holding their ground--a terrible feeling -like a nightmare took possession of him, and all the unlucky accidents -that might destroy him occurred to his mind. The Russians might fall -on his left wing, might break through his center, he himself might -be killed by a stray cannon ball. All this was possible. In former -battles he had only considered the possibilities of success, but now -innumerable unlucky chances presented themselves, and he expected them -all. Yes, it was like a dream in which a man fancies that a ruffian is -coming to attack him, and raises his arm to strike that ruffian a -terrible blow which he knows should annihilate him, but then feels -that his arm drops powerless and limp like a rag, and the horror of -unavoidable destruction seizes him in his helplessness. - -The news that the Russians were attacking the left flank of the -French army aroused that horror in Napoleon. He sat silently on a -campstool below the knoll, with head bowed and elbows on his knees. -Berthier approached and suggested that they should ride along the line -to ascertain the position of affairs. - -"What? What do you say?" asked Napoleon. "Yes, tell them to bring me -my horse." - -He mounted and rode toward Semenovsk. - -Amid the powder smoke, slowly dispersing over the whole space -through which Napoleon rode, horses and men were lying in pools of -blood, singly or in heaps. Neither Napoleon nor any of his generals -had ever before seen such horrors or so many slain in such a small -area. The roar of guns, that had not ceased for ten hours, wearied the -ear and gave a peculiar significance to the spectacle, as music does -to tableaux vivants. Napoleon rode up the high ground at Semenovsk, -and through the smoke saw ranks of men in uniforms of a color -unfamiliar to him. They were Russians. - -The Russians stood in serried ranks behind Semenovsk village and its -knoll, and their guns boomed incessantly along their line and sent -forth clouds of smoke. It was no longer a battle: it was a -continuous slaughter which could be of no avail either to the French -or the Russians. Napoleon stopped his horse and again fell into the -reverie from which Berthier had aroused him. He could not stop what -was going on before him and around him and was supposed to be directed -by him and to depend on him, and from its lack of success this affair, -for the first time, seemed to him unnecessary and horrible. - -One of the generals rode up to Napoleon and ventured to offer to -lead the Old Guard into action. Ney and Berthier, standing near -Napoleon, exchanged looks and smiled contemptuously at this -general's senseless offer. - -Napoleon bowed his head and remained silent a long time. - -"At eight hundred leagues from France, I will not have my Guard -destroyed!" he said, and turning his horse rode back to Shevardino. - - - - - -CHAPTER XXXV - - -On the rug-covered bench where Pierre had seen him in the morning -sat Kutuzov, his gray head hanging, his heavy body relaxed. He gave no -orders, but only assented to or dissented from what others suggested. - -"Yes, yes, do that," he replied to various proposals. "Yes, yes: go, -dear boy, and have a look," he would say to one or another of those -about him; or, "No, don't, we'd better wait!" He listened to the -reports that were brought him and gave directions when his -subordinates demanded that of him; but when listening to the reports -it seemed as if he were not interested in the import of the words -spoken, but rather in something else--in the expression of face and -tone of voice of those who were reporting. By long years of military -experience he knew, and with the wisdom of age understood, that it -is impossible for one man to direct hundreds of thousands of others -struggling with death, and he knew that the result of a battle is -decided not by the orders of a commander in chief, nor the place where -the troops are stationed, nor by the number of cannon or of -slaughtered men, but by that intangible force called the spirit of the -army, and he watched this force and guided it in as far as that was in -his power. - -Kutuzov's general expression was one of concentrated quiet -attention, and his face wore a strained look as if he found it -difficult to master the fatigue of his old and feeble body. - -At eleven o'clock they brought him news that the fleches captured by -the French had been retaken, but that Prince Bagration was wounded. -Kutuzov groaned and swayed his head. - -"Ride over to Prince Peter Ivanovich and find out about it exactly," -he said to one of his adjutants, and then turned to the Duke of -Wurttemberg who was standing behind him. - -"Will Your Highness please take command of the first army?" - -Soon after the duke's departure--before he could possibly have -reached Semenovsk--his adjutant came back from him and told Kutuzov -that the duke asked for more troops. - -Kutuzov made a grimace and sent an order to Dokhturov to take over -the command of the first army, and a request to the duke--whom he said -he could not spare at such an important moment--to return to him. When -they brought him news that Murat had been taken prisoner, and the -staff officers congratulated him, Kutuzov smiled. - -"Wait a little, gentlemen," said he. "The battle is won, and there -is nothing extraordinary in the capture of Murat. Still, it is -better to wait before we rejoice." - -But he sent an adjutant to take the news round the army. - -When Scherbinin came galloping from the left flank with news that -the French had captured the fleches and the village of Semenovsk, -Kutuzov, guessing by the sounds of the battle and by Scherbinin's -looks that the news was bad, rose as if to stretch his legs and, -taking Scherbinin's arm, led him aside. - -"Go, my dear fellow," he said to Ermolov, "and see whether something -can't be done." - -Kutuzov was in Gorki, near the center of the Russian position. The -attack directed by Napoleon against our left flank had been several -times repulsed. In the center the French had not got beyond -Borodino, and on their left flank Uvarov's cavalry had put the -French to flight. - -Toward three o'clock the French attacks ceased. On the faces of -all who came from the field of battle, and of those who stood around -him, Kutuzov noticed an expression of extreme tension. He was -satisfied with the day's success--a success exceeding his -expectations, but the old man's strength was failing him. Several -times his head dropped low as if it were falling and he dozed off. -Dinner was brought him. - -Adjutant General Wolzogen, the man who when riding past Prince -Andrew had said, "the war should be extended widely," and whom -Bagration so detested, rode up while Kutuzov was at dinner. Wolzogen -had come from Barclay de Tolly to report on the progress of affairs on -the left flank. The sagacious Barclay de Tolly, seeing crowds of -wounded men running back and the disordered rear of the army, -weighed all the circumstances, concluded that the battle was lost, and -sent his favorite officer to the commander in chief with that news. - -Kutuzov was chewing a piece of roast chicken with difficulty and -glanced at Wolzogen with eyes that brightened under their puckering -lids. - -Wolzogen, nonchalantly stretching his legs, approached Kutuzov -with a half-contemptuous smile on his lips, scarcely touching the peak -of his cap. - -He treated his Serene Highness with a somewhat affected -nonchalance intended to show that, as a highly trained military man, -he left it to Russians to make an idol of this useless old man, but -that he knew whom he was dealing with. "Der alte Herr" (as in their -own set the Germans called Kutuzov) "is making himself very -comfortable," thought Wolzogen, and looking severely at the dishes -in front of Kutuzov he began to report to "the old gentleman" the -position of affairs on the left flank as Barclay had ordered him to -and as he himself had seen and understood it. - -"All the points of our position are in the enemy's hands and we -cannot dislodge them for lack of troops, the men are running away -and it is impossible to stop them," he reported. - -Kutuzov ceased chewing and fixed an astonished gaze on Wolzogen, -as if not understand what was said to him. Wolzogen, noticing "the old -gentleman's" agitation, said with a smile: - -"I have not considered it right to conceal from your Serene Highness -what I have seen. The troops are in complete disorder..." - -"You have seen? You have seen?..." Kutuzov shouted frowning, and -rising quickly he went up to Wolzogen. - -"How... how dare you!..." he shouted, choking and making a -threatening gesture with his trembling arms: "How dare you, sir, say -that to me? You know nothing about it. Tell General Barclay from me -that his information is incorrect and that the real course of the -battle is better known to me, the commander in chief, than to him." - -Wolzogen was about to make a rejoinder, but Kutuzov interrupted him. - -"The enemy has been repulsed on the left and defeated on the right -flank. If you have seen amiss, sir, do not allow yourself to say -what you don't know! Be so good as to ride to General Barclay and -inform him of my firm intention to attack the enemy tomorrow," said -Kutuzov sternly. - -All were silent, and the only sound audible was the heavy -breathing of the panting old general. - -"They are repulsed everywhere, for which I thank God and our brave -army! The enemy is beaten, and tomorrow we shall drive him from the -sacred soil of Russia," said Kutuzov crossing himself, and he suddenly -sobbed as his eyes filled with tears. - -Wolzogen, shrugging his shoulders and curling his lips, stepped -silently aside, marveling at "the old gentleman's" conceited -stupidity. - -"Ah, here he is, my hero!" said Kutuzov to a portly, handsome, -dark-haired general who was just ascending the knoll. - -This was Raevski, who had spent the whole day at the most -important part of the field of Borodino. - -Raevski reported that the troops were firmly holding their ground -and that the French no longer ventured to attack. - -After hearing him, Kutuzov said in French: - -"Then you do not think, like some others, that we must retreat?" - -"On the contrary, your Highness, in indecisive actions it is -always the most stubborn who remain victors," replied Raevski, "and in -my opinion..." - -"Kaysarov!" Kutuzov called to his adjutant. "Sit down and write -out the order of the day for tomorrow. And you," he continued, -addressing another, "ride along the line and that tomorrow we attack." - -While Kutuzov was talking to Raevski and dictating the order of -the day, Wolzogen returned from Barclay and said that General -Barclay wished to have written confirmation of the order the field -marshal had given. - -Kutuzov, without looking at Wolzogen, gave directions for the -order to be written out which the former commander in chief, to -avoid personal responsibility, very judiciously wished to receive. - -And by means of that mysterious indefinable bond which maintains -throughout an army one and the same temper, known as "the spirit of -the army," and which constitutes the sinew of war, Kutuzov's words, -his order for a battle next day, immediately became known from one end -of the army to the other. - -It was far from being the same words or the same order that -reached the farthest links of that chain. The tales passing from mouth -to mouth at different ends of the army did not even resemble what -Kutuzov had said, but the sense of his words spread everywhere because -what he said was not the outcome of cunning calculations, but of a -feeling that lay in the commander in chief's soul as in that of -every Russian. - -And on learning that tomorrow they were to attack the enemy, and -hearing from the highest quarters a confirmation of what they wanted -to believe, the exhausted, wavering men felt comforted and inspirited. - - - - - -CHAPTER XXXVI - - -Prince Andrew's regiment was among the reserves which till after one -o'clock were stationed inactive behind Semenovsk, under heavy -artillery fire. Toward two o'clock the regiment, having already lost -more than two hundred men, was moved forward into a trampled -oatfield in the gap between Semenovsk and the Knoll Battery, where -thousands of men perished that day and on which an intense, -concentrated fire from several hundred enemy guns was directed between -one and two o'clock. - -Without moving from that spot or firing a single shot the regiment -here lost another third of its men. From in front and especially -from the right, in the unlifting smoke the guns boomed, and out of the -mysterious domain of smoke that overlay the whole space in front, -quick hissing cannon balls and slow whistling shells flew unceasingly. -At times, as if to allow them a respite, a quarter of an hour passed -during which the cannon balls and shells all flew overhead, but -sometimes several men were torn from the regiment in a minute and -the slain were continually being dragged away and the wounded -carried off. - -With each fresh blow less and less chance of life remained for those -not yet killed. The regiment stood in columns of battalion, three -hundred paces apart, but nevertheless the men were always in one and -the same mood. All alike were taciturn and morose. Talk was rarely -heard in the ranks, and it ceased altogether every time the thud of -a successful shot and the cry of "stretchers!" was heard. Most of -the time, by their officers' order, the men sat on the ground. One, -having taken off his shako, carefully loosened the gathers of its -lining and drew them tight again; another, rubbing some dry clay -between his palms, polished his bayonet; another fingered the strap -and pulled the buckle of his bandolier, while another smoothed and -refolded his leg bands and put his boots on again. Some built little -houses of the tufts in the plowed ground, or plaited baskets from -the straw in the cornfield. All seemed fully absorbed in these -pursuits. When men were killed or wounded, when rows of stretchers -went past, when some troops retreated, and when great masses of the -enemy came into view through the smoke, no one paid any attention to -these things. But when our artillery or cavalry advanced or some of -our infantry were seen to move forward, words of approval were heard -on all sides. But the liveliest attention was attracted by occurrences -quite apart from, and unconnected with, the battle. It was as if the -minds of these morally exhausted men found relief in everyday, -commonplace occurrences. A battery of artillery was passing in front -of the regiment. The horse of an ammunition cart put its leg over a -trace. "Hey, look at the trace horse!... Get her leg out! She'll -fall.... Ah, they don't see it!" came identical shouts from the -ranks all along the regiment. Another time, general attention was -attracted by a small brown dog, coming heaven knows whence, which -trotted in a preoccupied manner in front of the ranks with tail -stiffly erect till suddenly a shell fell close by, when it yelped, -tucked its tail between its legs, and darted aside. Yells and -shrieks of laughter rose from the whole regiment. But such -distractions lasted only a moment, and for eight hours the men had -been inactive, without food, in constant fear of death, and their pale -and gloomy faces grew ever paler and gloomier. - -Prince Andrew, pale and gloomy like everyone in the regiment, -paced up and down from the border of one patch to another, at the edge -of the meadow beside an oatfield, with head bowed and arms behind -his back. There was nothing for him to do and no orders to be given. -Everything went on of itself. The killed were dragged from the -front, the wounded carried away, and the ranks closed up. If any -soldiers ran to the rear they returned immediately and hastily. At -first Prince Andrew, considering it his duty to rouse the courage of -the men and to set them an example, walked about among the ranks, -but he soon became convinced that this was unnecessary and that -there was nothing he could teach them. All the powers of his soul, -as of every soldier there, were unconsciously bent on avoiding the -contemplation of the horrors of their situation. He walked along the -meadow, dragging his feet, rustling the grass, and gazing at the -dust that covered his boots; now he took big strides trying to keep to -the footprints left on the meadow by the mowers, then he counted his -steps, calculating how often he must walk from one strip to another to -walk a mile, then he stripped the flowers from the wormwood that -grew along a boundary rut, rubbed them in his palms, and smelled their -pungent, sweetly bitter scent. Nothing remained of the previous -day's thoughts. He thought of nothing. He listened with weary ears -to the ever-recurring sounds, distinguishing the whistle of flying -projectiles from the booming of the reports, glanced at the tiresomely -familiar faces of the men of the first battalion, and waited. "Here it -comes... this one is coming our way again!" he thought, listening to -an approaching whistle in the hidden region of smoke. "One, another! -Again! It has hit...." He stopped and looked at the ranks. "No, it has -gone over. But this one has hit!" And again he started trying to reach -the boundary strip in sixteen paces. A whizz and a thud! Five paces -from him, a cannon ball tore up the dry earth and disappeared. A chill -ran down his back. Again he glanced at the ranks. Probably many had -been hit--a large crowd had gathered near the second battalion. - -"Adjutant!" he shouted. "Order them not to crowd together." - -The adjutant, having obeyed this instruction, approached Prince -Andrew. From the other side a battalion commander rode up. - -"Look out!" came a frightened cry from a soldier and, like a bird -whirring in rapid flight and alighting on the ground, a shell -dropped with little noise within two steps of Prince Andrew and -close to the battalion commander's horse. The horse first, -regardless of whether it was right or wrong to show fear, snorted, -reared almost throwing the major, and galloped aside. The horse's -terror infected the men. - -"Lie down!" cried the adjutant, throwing himself flat on the ground. - -Prince Andrew hesitated. The smoking shell spun like a top between -him and the prostrate adjutant, near a wormwood plant between the -field and the meadow. - -"Can this be death?" thought Prince Andrew, looking with a quite -new, envious glance at the grass, the wormwood, and the streamlet of -smoke that curled up from the rotating black ball. "I cannot, I do not -wish to die. I love life--I love this grass, this earth, this air...." -He thought this, and at the same time remembered that people were -looking at him. - -"It's shameful, sir!" he said to the adjutant. "What..." - -He did not finish speaking. At one and the same moment came the -sound of an explosion, a whistle of splinters as from a breaking -window frame, a suffocating smell of powder, and Prince Andrew started -to one side, raising his arm, and fell on his chest. Several -officers ran up to him. From the right side of his abdomen, blood -was welling out making a large stain on the grass. - -The militiamen with stretchers who were called up stood behind the -officers. Prince Andrew lay on his chest with his face in the grass, -breathing heavily and noisily. - -"What are you waiting for? Come along!" - -The peasants went up and took him by his shoulders and legs, but -he moaned piteously and, exchanging looks, they set him down again. - -"Pick him up, lift him, it's all the same!" cried someone. - -They again took him by the shoulders and laid him on the stretcher. - -"Ah, God! My God! What is it? The stomach? That means death! My -God!"--voices among the officers were heard saying. - -"It flew a hair's breadth past my ear," said the adjutant. - -The peasants, adjusting the stretcher to their shoulders, started -hurriedly along the path they had trodden down, to the dressing -station. - -"Keep in step! Ah... those peasants!" shouted an officer, seizing by -their shoulders and checking the peasants, who were walking unevenly -and jolting the stretcher. - -"Get into step, Fedor... I say, Fedor!" said the foremost peasant. - -"Now that's right!" said the one behind joyfully, when he had got -into step. - -"Your excellency! Eh, Prince!" said the trembling voice of Timokhin, -who had run up and was looking down on the stretcher. - -Prince Andrew opened his eyes and looked up at the speaker from -the stretcher into which his head had sunk deep and again his -eyelids drooped. - - -The militiamen carried Prince Andrew to dressing station by the -wood, where wagons were stationed. The dressing station consisted of -three tents with flaps turned back, pitched at the edge of a birch -wood. In the wood, wagons and horses were standing. The horses were -eating oats from their movable troughs and sparrows flew down and -pecked the grains that fell. Some crows, scenting blood, flew among -the birch trees cawing impatiently. Around the tents, over more than -five acres, bloodstained men in various garbs stood, sat, or lay. -Around the wounded stood crowds of soldier stretcher-bearers with -dismal and attentive faces, whom the officers keeping order tried in -vain to drive from the spot. Disregarding the officers' orders, the -soldiers stood leaning against their stretchers and gazing intently, -as if trying to comprehend the difficult problem of what was taking -place before them. From the tents came now loud angry cries and now -plaintive groans. Occasionally dressers ran out to fetch water, or -to point out those who were to be brought in next. The wounded men -awaiting their turn outside the tents groaned, sighed, wept, screamed, -swore, or asked for vodka. Some were delirious. Prince Andrew's -bearers, stepping over the wounded who had not yet been bandaged, took -him, as a regimental commander, close up to one of the tents and there -stopped, awaiting instructions. Prince Andrew opened his eyes and -for a long time could not make out what was going on around him. He -remembered the meadow, the wormwood, the field, the whirling black -ball, and his sudden rush of passionate love of life. Two steps from -him, leaning against a branch and talking loudly and attracting -general attention, stood a tall, handsome, black-haired -noncommissioned officer with a bandaged head. He had been wounded in -the head and leg by bullets. Around him, eagerly listening to his -talk, a crowd of wounded and stretcher-bearers was gathered. - -"We kicked him out from there so that he chucked everything, we -grabbed the King himself!" cried he, looking around him with eyes that -glittered with fever. "If only reserves had come up just then, lads, -there wouldn't have been nothing left of him! I tell you surely..." - -Like all the others near the speaker, Prince Andrew looked at him -with shining eyes and experienced a sense of comfort. "But isn't it -all the same now?" thought he. "And what will be there, and what has -there been here? Why was I so reluctant to part with life? There was -something in this life I did not and do not understand." - - - - - -CHAPTER XXXVII - - -One of the doctors came out of the tent in a bloodstained apron, -holding a cigar between the thumb and little finger of one of his -small bloodstained hands, so as not to smear it. He raised his head -and looked about him, but above the level of the wounded men. He -evidently wanted a little respite. After turning his head from right -to left for some time, he sighed and looked down. - -"All right, immediately," he replied to a dresser who pointed Prince -Andrew out to him, and he told them to carry him into the tent. - -Murmurs arose among the wounded who were waiting. - -"It seems that even in the next world only the gentry are to have -a chance!" remarked one. - -Prince Andrew was carried in and laid on a table that had only -just been cleared and which a dresser was washing down. Prince -Andrew could not make out distinctly what was in that tent. The -pitiful groans from all sides and the torturing pain in his thigh, -stomach, and back distracted him. All he saw about him merged into a -general impression of naked, bleeding human bodies that seemed to fill -the whole of the low tent, as a few weeks previously, on that hot -August day, such bodies had filled the dirty pond beside the -Smolensk road. Yes, it was the same flesh, the same chair a canon, the -sight of which had even then filled him with horror, as by a -presentiment. - -There were three operating tables in the tent. Two were occupied, -and on the third they placed Prince Andrew. For a little while he -was left alone and involuntarily witnessed what was taking place on -the other two tables. On the nearest one sat a Tartar, probably a -Cossack, judging by the uniform thrown down beside him. Four -soldiers were holding him, and a spectacled doctor was cutting into -his muscular brown back. - -"Ooh, ooh, ooh!" grunted the Tartar, and suddenly lifting up his -swarthy snub-nosed face with its high cheekbones, and baring his white -teeth, he began to wriggle and twitch his body and utter piercing, -ringing, and prolonged yells. On the other table, round which many -people were crowding, a tall well-fed man lay on his back with his -head thrown back. His curly hair, its color, and the shape of his head -seemed strangely familiar to Prince Andrew. Several dressers were -pressing on his chest to hold him down. One large, white, plump leg -twitched rapidly all the time with a feverish tremor. The man was -sobbing and choking convulsively. Two doctors--one of whom was pale -and trembling--were silently doing something to this man's other, gory -leg. When he had finished with the Tartar, whom they covered with an -overcoat, the spectacled doctor came up to Prince Andrew, wiping his -hands. - -He glanced at Prince Andrew's face and quickly turned away. - -"Undress him! What are you waiting for?" he cried angrily to the -dressers. - -His very first, remotest recollections of childhood came back to -Prince Andrew's mind when the dresser with sleeves rolled up began -hastily to undo the buttons of his clothes and undressed him. The -doctor bent down over the wound, felt it, and sighed deeply. Then he -made a sign to someone, and the torturing pain in his abdomen caused -Prince Andrew to lose consciousness. When he came to himself the -splintered portions of his thighbone had been extracted, the torn -flesh cut away, and the wound bandaged. Water was being sprinkled on -his face. As soon as Prince Andrew opened his eyes, the doctor bent -over, kissed him silently on the lips, and hurried away. - -After the sufferings he had been enduring, Prince Andrew enjoyed a -blissful feeling such as he had not experienced for a long time. All -the best and happiest moments of his life--especially his earliest -childhood, when he used to be undressed and put to bed, and when -leaning over him his nurse sang him to sleep and he, burying his -head in the pillow, felt happy in the mere consciousness of life- -returned to his memory, not merely as something past but as -something present. - -The doctors were busily engaged with the wounded man the shape of -whose head seemed familiar to Prince Andrew: they were lifting him -up and trying to quiet him. - -"Show it to me.... Oh, ooh... Oh! Oh, ooh!" his frightened moans -could be heard, subdued by suffering and broken by sobs. - -Hearing those moans Prince Andrew wanted to weep. -Whether because he was dying without glory, or because he was sorry to -part with life, or because of those memories of a childhood that could -not return, or because he was suffering and others were suffering -and that man near him was groaning so piteously--he felt like -weeping childlike, kindly, and almost happy tears. - -The wounded man was shown his amputated leg stained with clotted -blood and with the boot still on. - -"Oh! Oh, ooh!" he sobbed, like a woman. - -The doctor who had been standing beside him, preventing Prince -Andrew from seeing his face, moved away. - -"My God! What is this? Why is he here?" said Prince Andrew to -himself. - -In the miserable, sobbing, enfeebled man whose leg had just been -amputated, he recognized Anatole Kuragin. Men were supporting him in -their arms and offering him a glass of water, but his trembling, -swollen lips could not grasp its rim. Anatole was sobbing painfully. -"Yes, it is he! Yes, that man is somehow closely and painfully -connected with me," thought Prince Andrew, not yet clearly grasping -what he saw before him. "What is the connection of that man with my -childhood and life?" he asked himself without finding an answer. And -suddenly a new unexpected memory from that realm of pure and loving -childhood presented itself to him. He remembered Natasha as he had -seen her for the first time at the ball in 1810, with her slender neck -and arms and with a frightened happy face ready for rapture, and -love and tenderness for her, stronger and more vivid than ever, -awoke in his soul. He now remembered the connection that existed -between himself and this man who was dimly gazing at him through tears -that filled his swollen eyes. He remembered everything, and ecstatic -pity and love for that man overflowed his happy heart. - -Prince Andrew could no longer restrain himself and wept tender -loving tears for his fellow men, for himself, and for his own and -their errors. - -"Compassion, love of our brothers, for those who love us and for -those who hate us, love of our enemies; yes, that love which God -preached on earth and which Princess Mary taught me and I did not -understand--that is what made me sorry to part with life, that is what -remained for me had I lived. But now it is too late. I know it!" - - - - - -CHAPTER XXXVIII - - -The terrible spectacle of the battlefield covered with dead and -wounded, together with the heaviness of his head and the news that -some twenty generals he knew personally had been killed or wounded, -and the consciousness of the impotence of his once mighty arm, -produced an unexpected impression on Napoleon who usually liked to -look at the killed and wounded, thereby, he considered, testing his -strength of mind. This day the horrible appearance of the -battlefield overcame that strength of mind which he thought -constituted his merit and his greatness. He rode hurriedly from the -battlefield and returned to the Shevardino knoll, where he sat on -his campstool, his sallow face swollen and heavy, his eyes dim, his -nose red, and his voice hoarse, involuntarily listening, with downcast -eyes, to the sounds of firing. With painful dejection he awaited the -end of this action, in which he regarded himself as a participant -and which he was unable to arrest. A personal, human feeling for a -brief moment got the better of the artificial phantasm of life he -had served so long. He felt in his own person the sufferings and death -he had witnessed on the battlefield. The heaviness of his head and -chest reminded him of the possibility of suffering and death for -himself. At that moment he did not desire Moscow, or victory, or glory -(what need had he for any more glory?). The one thing he wished for -was rest, tranquillity, and freedom. But when he had been on the -Semenovsk heights the artillery commander had proposed to him to bring -several batteries of artillery up to those heights to strengthen the -fire on the Russian troops crowded in front of Knyazkovo. Napoleon had -assented and had given orders that news should be brought to him of -the effect those batteries produced. - -An adjutant came now to inform him that the fire of two hundred guns -had been concentrated on the Russians, as he had ordered, but that -they still held their ground. - -"Our fire is mowing them down by rows, but still they hold on," said -the adjutant. - -"They want more!..." said Napoleon in a hoarse voice. - -"Sire?" asked the adjutant who had not heard the remark. - -"They want more!" croaked Napoleon frowning. "Let them have it!" - -Even before he gave that order the thing he did not desire, and -for which he gave the order only because he thought it was expected of -him, was being done. And he fell back into that artificial realm of -imaginary greatness, and again--as a horse walking a treadmill -thinks it is doing something for itself--he submissively fulfilled the -cruel, sad, gloomy, and inhuman role predestined for him. - -And not for that day and hour alone were the mind and conscience -darkened of this man on whom the responsibility for what was happening -lay more than on all the others who took part in it. Never to the -end of his life could he understand goodness, beauty, or truth, or the -significance of his actions which were too contrary to goodness and -truth, too remote from everything human, for him ever to be able to -grasp their meaning. He could not disavow his actions, belauded as -they were by half the world, and so he had to repudiate truth, -goodness, and all humanity. - -Not only on that day, as he rode over the battlefield strewn with -men killed and maimed (by his will as he believed), did he reckon as -he looked at them how many Russians there were for each Frenchman and, -deceiving himself, find reason for rejoicing in the calculation that -there were five Russians for every Frenchman. Not on that day alone -did he write in a letter to Paris that "the battle field was -superb," because fifty thousand corpses lay there, but even on the -island of St. Helena in the peaceful solitude where he said he -intended to devote his leisure to an account of the great deeds he had -done, he wrote: - - -The Russian war should have been the most popular war of modern -times: it was a war of good sense, for real interests, for the -tranquillity and security of all; it was purely pacific and -conservative. - -It was a war for a great cause, the end of uncertainties and the -beginning of security. A new horizon and new labors were opening -out, full of well-being and prosperity for all. The European system -was already founded; all that remained was to organize it. - -Satisfied on these great points and with tranquility everywhere, I -too should have had my Congress and my Holy Alliance. Those ideas were -stolen from me. In that reunion of great sovereigns we should have -discussed our interests like one family, and have rendered account -to the peoples as clerk to master. - -Europe would in this way soon have been, in fact, but one people, -and anyone who traveled anywhere would have found himself always in -the common fatherland. I should have demanded the freedom of all -navigable rivers for everybody, that the seas should be common to all, -and that the great standing armies should be reduced henceforth to -mere guards for the sovereigns. - -On returning to France, to the bosom of the great, strong, -magnificent, peaceful, and glorious fatherland, I should have -proclaimed her frontiers immutable; all future wars purely -defensive, all aggrandizement antinational. I should have associated -my son in the Empire; my dictatorship would have been finished, and -his constitutional reign would have begun. - -Paris would have been the capital of the world, and the French the -envy of the nations! - -My leisure then, and my old age, would have been devoted, in company -with the Empress and during the royal apprenticeship of my son, to -leisurely visiting, with our own horses and like a true country -couple, every corner of the Empire, receiving complaints, redressing -wrongs, and scattering public buildings and benefactions on all -sides and everywhere. - - -Napoleon, predestined by Providence for the gloomy role of -executioner of the peoples, assured himself that the aim of his -actions had been the peoples' welfare and that he could control the -fate of millions and by the employment of power confer benefactions. - - -"Of four hundred thousand who crossed the Vistula," he wrote further -of the Russian war, "half were Austrians, Prussians, Saxons, Poles, -Bavarians, Wurttembergers, Mecklenburgers, Spaniards, Italians, and -Neapolitans. The Imperial army, strictly speaking, was one third -composed of Dutch, Belgians, men from the borders of the Rhine, -Piedmontese, Swiss, Genevese, Tuscans, Romans, inhabitants of the -Thirty-second Military Division, of Bremen, of Hamburg, and so on: -it included scarcely a hundred and forty thousand who spoke French. -The Russian expedition actually cost France less than fifty thousand -men; the Russian army in its retreat from Vilna to Moscow lost in -the various battles four times more men than the French army; the -burning of Moscow cost the lives of a hundred thousand Russians who -died of cold and want in the woods; finally, in its march from -Moscow to the Oder the Russian army also suffered from the severity of -the season; so that by the the time it reached Vilna it numbered -only fifty thousand, and at Kalisch less than eighteen thousand." - - -He imagined that the war with Russia came about by his will, and the -horrors that occurred did not stagger his soul. He boldly took the -whole responsibility for what happened, and his darkened mind found -justification in the belief that among the hundreds of thousands who -perished there were fewer Frenchmen than Hessians and Bavarians. - - - - - -CHAPTER XXXIX - - -Several tens of thousands of the slain lay in diverse postures and -various uniforms on the fields and meadows belonging to the Davydov -family and to the crown serfs--those fields and meadows where for -hundreds of years the peasants of Borodino, Gorki, Shevardino, and -Semenovsk had reaped their harvests and pastured their cattle. At -the dressing stations the grass and earth were soaked with blood for a -space of some three acres around. Crowds of men of various arms, -wounded and unwounded, with frightened faces, dragged themselves -back to Mozhaysk from the one army and back to Valuevo from the other. -Other crowds, exhausted and hungry, went forward led by their -officers. Others held their ground and continued to fire. - -Over the whole field, previously so gaily beautiful with the glitter -of bayonets and cloudlets of smoke in the morning sun, there now -spread a mist of damp and smoke and a strange acid smell of -saltpeter and blood. Clouds gathered and drops of rain began to fall -on the dead and wounded, on the frightened, exhausted, and -hesitating men, as if to say: "Enough, men! Enough! Cease... bethink -yourselves! What are you doing?" - -To the men of both sides alike, worn out by want of food and rest, -it began equally to appear doubtful whether they should continue to -slaughter one another; all the faces expressed hesitation, and the -question arose in every soul: "For what, for whom, must I kill and -be killed?... You may go and kill whom you please, but I don't want to -do so anymore!" By evening this thought had ripened in every soul. -At any moment these men might have been seized with horror at what -they were doing and might have thrown up everything and run away -anywhere. - -But though toward the end of the battle the men felt all the -horror of what they were doing, though they would have been glad to -leave off, some incomprehensible, mysterious power continued to -control them, and they still brought up the charges, loaded, aimed, -and applied the match, though only one artilleryman survived out of -every three, and though they stumbled and panted with fatigue, -perspiring and stained with blood and powder. The cannon balls flew -just as swiftly and cruelly from both sides, crushing human bodies, -and that terrible work which was not done by the will of a man but -at the will of Him who governs men and worlds continued. - -Anyone looking at the disorganized rear of the Russian army would -have said that, if only the French made one more slight effort, it -would disappear; and anyone looking at the rear of the French army -would have said that the Russians need only make one more slight -effort and the French would be destroyed. But neither the French nor -the Russians made that effort, and the flame of battle burned slowly -out. - -The Russians did not make that effort because they were not -attacking the French. At the beginning of the battle they stood -blocking the way to Moscow and they still did so at the end of the -battle as at the beginning. But even had the aim of the Russians -been to drive the French from their positions, they could not have -made this last effort, for all the Russian troops had been broken -up, there was no part of the Russian army that had not suffered in the -battle, and though still holding their positions they had lost ONE -HALF of their army. - -The French, with the memory of all their former victories during -fifteen years, with the assurance of Napoleon's invincibility, with -the consciousness that they had captured part of the battlefield and -had lost only a quarter of their men and still had their Guards -intact, twenty thousand strong, might easily have made that effort. -The French had attacked the Russian army in order to drive it from its -position ought to have made that effort, for as long as the Russians -continued to block the road to Moscow as before, the aim of the French -had not been attained and all their efforts and losses were in vain. -But the French did not make that effort. Some historians say that -Napoleon need only have used his Old Guards, who were intact, and -the battle would have been won. To speak of what would have happened -had Napoleon sent his Guards is like talking of what would happen if -autumn became spring. It could not be. Napoleon did not give his -Guards, not because he did not want to, but because it could not be -done. All the generals, officers, and soldiers of the French army knew -it could not be done, because the flagging spirit of the troops -would not permit it. - -It was not Napoleon alone who had experienced that nightmare feeling -of the mighty arm being stricken powerless, but all the generals and -soldiers of his army whether they had taken part in the battle or not, -after all their experience of previous battles--when after one tenth -of such efforts the enemy had fled--experienced a similar feeling of -terror before an enemy who, after losing HALF his men, stood as -threateningly at the end as at the beginning of the battle. The -moral force of the attacking French army was exhausted. Not that -sort of victory which is defined by the capture of pieces of -material fastened to sticks, called standards, and of the ground on -which the troops had stood and were standing, but a moral victory that -convinces the enemy of the moral superiority of his opponent and of -his own impotence was gained by the Russians at Borodino. The French -invaders, like an infuriated animal that has in its onslaught received -a mortal wound, felt that they were perishing, but could not stop, any -more than the Russian army, weaker by one half, could help swerving. -By impetus gained, the French army was still able to roll forward to -Moscow, but there, without further effort on the part of the Russians, -it had to perish, bleeding from the mortal wound it had received at -Borodino. The direct consequence of the battle of Borodino was -Napoleon's senseless flight from Moscow, his retreat along the old -Smolensk road, the destruction of the invading army of five hundred -thousand men, and the downfall of Napoleonic France, on which at -Borodino for the first time the hand of an opponent of stronger spirit -had been laid. - - - - - -BOOK ELEVEN: 1812 - - - - - -CHAPTER I - - -Absolute continuity of motion is not comprehensible to the human -mind. Laws of motion of any kind become comprehensible to man only -when he examines arbitrarily selected elements of that motion; but -at the same time, a large proportion of human error comes from the -arbitrary division of continuous motion into discontinuous elements. -There is a well known, so-called sophism of the ancients consisting in -this, that Achilles could never catch up with a tortoise he was -following, in spite of the fact that he traveled ten times as fast -as the tortoise. By the time Achilles has covered the distance that -separated him from the tortoise, the tortoise has covered one tenth of -that distance ahead of him: when Achilles has covered that tenth, -the tortoise has covered another one hundredth, and so on forever. -This problem seemed to the ancients insoluble. The absurd answer (that -Achilles could never overtake the tortoise) resulted from this: that -motion was arbitrarily divided into discontinuous elements, whereas -the motion both of Achilles and of the tortoise was continuous. - -By adopting smaller and smaller elements of motion we only -approach a solution of the problem, but never reach it. Only when we -have admitted the conception of the infinitely small, and the -resulting geometrical progression with a common ratio of one tenth, -and have found the sum of this progression to infinity, do we reach -a solution of the problem. - -A modern branch of mathematics having achieved the art of dealing -with the infinitely small can now yield solutions in other more -complex problems of motion which used to appear insoluble. - -This modern branch of mathematics, unknown to the ancients, when -dealing with problems of motion admits the conception of the -infinitely small, and so conforms to the chief condition of motion -(absolute continuity) and thereby corrects the inevitable error -which the human mind cannot avoid when it deals with separate elements -of motion instead of examining continuous motion. - -In seeking the laws of historical movement just the same thing -happens. The movement of humanity, arising as it does from innumerable -arbitrary human wills, is continuous. - -To understand the laws of this continuous movement is the aim of -history. But to arrive at these laws, resulting from the sum of all -those human wills, man's mind postulates arbitrary and disconnected -units. The first method of history is to take an arbitrarily -selected series of continuous events and examine it apart from others, -though there is and can be no beginning to any event, for one event -always flows uninterruptedly from another. - -The second method is to consider the actions of some one man--a king -or a commander--as equivalent to the sum of many individual wills; -whereas the sum of individual wills is never expressed by the activity -of a single historic personage. - -Historical science in its endeavor to draw nearer to truth -continually takes smaller and smaller units for examination. But -however small the units it takes, we feel that to take any unit -disconnected from others, or to assume a beginning of any -phenomenon, or to say that the will of many men is expressed by the -actions of any one historic personage, is in itself false. - -It needs no critical exertion to reduce utterly to dust any -deductions drawn from history. It is merely necessary to select some -larger or smaller unit as the subject of observation--as criticism has -every right to do, seeing that whatever unit history observes must -always be arbitrarily selected. - -Only by taking infinitesimally small units for observation (the -differential of history, that is, the individual tendencies of men) -and attaining to the art of integrating them (that is, finding the sum -of these infinitesimals) can we hope to arrive at the laws of history. - -The first fifteen years of the nineteenth century in Europe -present an extraordinary movement of millions of people. Men leave -their customary pursuits, hasten from one side of Europe to the other, -plunder and slaughter one another, triumph and are plunged in despair, -and for some years the whole course of life is altered and presents an -intensive movement which first increases and then slackens. What was -the cause of this movement, by what laws was it governed? asks the -mind of man. - -The historians, replying to this question, lay before us the sayings -and doings of a few dozen men in a building in the city of Paris, -calling these sayings and doings "the Revolution"; then they give a -detailed biography of Napoleon and of certain people favorable or -hostile to him; tell of the influence some of these people had on -others, and say: that is why this movement took place and those are -its laws. - -But the mind of man not only refuses to believe this explanation, -but plainly says that this method of explanation is fallacious, -because in it a weaker phenomenon is taken as the cause of a stronger. -The sum of human wills produced the Revolution and Napoleon, and -only the sum of those wills first tolerated and then destroyed them. - -"But every time there have been conquests there have been -conquerors; every time there has been a revolution in any state -there have been great men," says history. And, indeed, human reason -replies: every time conquerors appear there have been wars, but this -does not prove that the conquerors caused the wars and that it is -possible to find the laws of a war in the personal activity of a -single man. Whenever I look at my watch and its hands point to ten, -I hear the bells of the neighboring church; but because the bells -begin to ring when the hands of the clock reach ten, I have no right -to assume that the movement of the bells is caused by the position -of the hands of the watch. - -Whenever I see the movement of a locomotive I hear the whistle and -see the valves opening and wheels turning; but I have no right to -conclude that the whistling and the turning of wheels are the cause of -the movement of the engine. - -The peasants say that a cold wind blows in late spring because the -oaks are budding, and really every spring cold winds do blow when -the oak is budding. But though I do not know what causes the cold -winds to blow when the oak buds unfold, I cannot agree with the -peasants that the unfolding of the oak buds is the cause of the cold -wind, for the force of the wind is beyond the influence of the buds. I -see only a coincidence of occurrences such as happens with all the -phenomena of life, and I see that however much and however carefully I -observe the hands of the watch, and the valves and wheels of the -engine, and the oak, I shall not discover the cause of the bells -ringing, the engine moving, or of the winds of spring. To that I -must entirely change my point of view and study the laws of the -movement of steam, of the bells, and of the wind. History must do -the same. And attempts in this direction have already been made. - -To study the laws of history we must completely change the subject -of our observation, must leave aside kings, ministers, and generals, -and the common, infinitesimally small elements by which the masses are -moved. No one can say in how far it is possible for man to advance -in this way toward an understanding of the laws of history; but it -is evident that only along that path does the possibility of -discovering the laws of history lie, and that as yet not a millionth -part as much mental effort has been applied in this direction by -historians as has been devoted to describing the actions of various -kings, commanders, and ministers and propounding the historians' own -reflections concerning these actions. - - - - - -CHAPTER II - - -The forces of a dozen European nations burst into Russia. The -Russian army and people avoided a collision till Smolensk was reached, -and again from Smolensk to Borodino. The French army pushed on to -Moscow, its goal, its impetus ever increasing as it neared its aim, -just as the velocity of a falling body increases as it approaches -the earth. Behind it were seven hundred miles of hunger-stricken, -hostile country; ahead were a few dozen miles separating it from its -goal. Every soldier in Napoleon's army felt this and the invasion -moved on by its own momentum. - -The more the Russian army retreated the more fiercely a spirit of -hatred of the enemy flared up, and while it retreated the army -increased and consolidated. At Borodino a collision took place. -Neither army was broken up, but the Russian army retreated immediately -after the collision as inevitably as a ball recoils after colliding -with another having a greater momentum, and with equal inevitability -the ball of invasion that had advanced with such momentum rolled on -for some distance, though the collision had deprived it of all its -force. - -The Russians retreated eighty miles--to beyond Moscow--and the -French reached Moscow and there came to a standstill. For five weeks -after that there was not a single battle. The French did not move. -As a bleeding, mortally wounded animal licks its wounds, they remained -inert in Moscow for five weeks, and then suddenly, with no fresh -reason, fled back: they made a dash for the Kaluga road, and (after -a victory--for at Malo-Yaroslavets the field of conflict again -remained theirs) without undertaking a single serious battle, they -fled still more rapidly back to Smolensk, beyond Smolensk, beyond -the Berezina, beyond Vilna, and farther still. - -On the evening of the twenty-sixth of August, Kutuzov and the -whole Russian army were convinced that the battle of Borodino was a -victory. Kutuzov reported so to the Emperor. He gave orders to prepare -for a fresh conflict to finish the enemy and did this not to deceive -anyone, but because he knew that the enemy was beaten, as everyone who -had taken part in the battle knew it. - -But all that evening and next day reports came in one after -another of unheard-of losses, of the loss of half the army, and a -fresh battle proved physically impossible. - -It was impossible to give battle before information had been -collected, the wounded gathered in, the supplies of ammunition -replenished, the slain reckoned up, new officers appointed to -replace those who had been killed, and before the men had had food and -sleep. And meanwhile, the very next morning after the battle, the -French army advanced of itself upon the Russians, carried forward by -the force of its own momentum now seemingly increased in inverse -proportion to the square of the distance from its aim. Kutuzov's -wish was to attack next day, and the whole army desired to do so. -But to make an attack the wish to do so is not sufficient, there -must also be a possibility of doing it, and that possibility did not -exist. It was impossible not to retreat a day's march, and then in the -same way it was impossible not to retreat another and a third day's -march, and at last, on the first of September when the army drew -near Moscow--despite the strength of the feeling that had arisen in -all ranks--the force of circumstances compelled it to retire beyond -Moscow. And the troops retired one more, last, day's march, and -abandoned Moscow to the enemy. - -For people accustomed to think that plans of campaign and battles -are made by generals--as any one of us sitting over a map in his study -may imagine how he would have arranged things in this or that -battle--the questions present themselves: Why did Kutuzov during the -retreat not do this or that? Why did he not take up a position -before reaching Fili? Why did he not retire at once by the Kaluga -road, abandoning Moscow? and so on. People accustomed to think in that -way forget, or do not know, the inevitable conditions which always -limit the activities of any commander in chief. The activity of a -commander in chief does not all resemble the activity we imagine to -ourselves when we sit at case in our studies examining some campaign -on the map, with a certain number of troops on this and that side in a -certain known locality, and begin our plans from some given moment. -A commander in chief is never dealing with the beginning of any event- -the position from which we always contemplate it. The commander in -chief is always in the midst of a series of shifting events and so -he never can at any moment consider the whole import of an event -that is occurring. Moment by moment the event is imperceptibly shaping -itself, and at every moment of this continuous, uninterrupted -shaping of events the commander in chief is in the midst of a most -complex play of intrigues, worries, contingencies, authorities, -projects, counsels, threats, and deceptions and is continually obliged -to reply to innumerable questions addressed to him, which constantly -conflict with one another. - -Learned military authorities quite seriously tell us that Kutuzov -should have moved his army to the Kaluga road long before reaching -Fili, and that somebody actually submitted such a proposal to him. But -a commander in chief, especially at a difficult moment, has always -before him not one proposal but dozens simultaneously. And all these -proposals, based on strategics and tactics, contradict each other. - -A commander in chief's business, it would seem, is simply to -choose one of these projects. But even that he cannot do. Events and -time do not wait. For instance, on the twenty-eighth it is suggested -to him to cross to the Kaluga road, but just then an adjutant -gallops up from Miloradovich asking whether he is to engage the French -or retire. An order must be given him at once, that instant. And the -order to retreat carries us past the turn to the Kaluga road. And -after the adjutant comes the commissary general asking where the -stores are to be taken, and the chief of the hospitals asks where -the wounded are to go, and a courier from Petersburg brings a letter -from the sovereign which does not admit of the possibility of -abandoning Moscow, and the commander in chief's rival, the man who -is undermining him (and there are always not merely one but several -such), presents a new project diametrically opposed to that of turning -to the Kaluga road, and the commander in chief himself needs sleep and -refreshment to maintain his energy and a respectable general who has -been overlooked in the distribution of rewards comes to complain, -and the inhabitants of the district pray to be defended, and an -officer sent to inspect the locality comes in and gives a report quite -contrary to what was said by the officer previously sent; and a spy, a -prisoner, and a general who has been on reconnaissance, all describe -the position of the enemy's army differently. People accustomed to -misunderstand or to forget these inevitable conditions of a -commander in chief's actions describe to us, for instance, the -position of the army at Fili and assume that the commander in chief -could, on the first of September, quite freely decide whether to -abandon Moscow or defend it; whereas, with the Russian army less -than four miles from Moscow, no such question existed. When had that -question been settled? At Drissa and at Smolensk and most palpably -of all on the twenty-fourth of August at Shevardino and on the -twenty-sixth at Borodino, and each day and hour and minute of the -retreat from Borodino to Fili. - - - - - -CHAPTER III - - -When Ermolov, having been sent by Kutuzov to inspect the position, -told the field marshal that it was impossible to fight there before -Moscow and that they must retreat, Kutuzov looked at him in silence. - -"Give me your hand," said he and, turning it over so as to feel -the pulse, added: "You are not well, my dear fellow. Think what you -are saying!" - -Kutuzov could not yet admit the possibility of retreating beyond -Moscow without a battle. - -On the Poklonny Hill, four miles from the Dorogomilov gate of -Moscow, Kutuzov got out of his carriage and sat down on a bench by the -roadside. A great crowd of generals gathered round him, and Count -Rostopchin, who had come out from Moscow, joined them. This -brilliant company separated into several groups who all discussed -the advantages and disadvantages of the position, the state of the -army, the plans suggested, the situation of Moscow, and military -questions generally. Though they had not been summoned for the -purpose, and though it was not so called, they all felt that this -was really a council of war. The conversations all dealt with public -questions. If anyone gave or asked for personal news, it was done in a -whisper and they immediately reverted to general matters. No jokes, or -laughter, or smiles even, were seen among all these men. They -evidently all made an effort to hold themselves at the height the -situation demanded. And all these groups, while talking among -themselves, tried to keep near the commander in chief (whose bench -formed the center of the gathering) and to speak so that he might -overhear them. The commander in chief listened to what was being -said and sometimes asked them to repeat their remarks, but did not -himself take part in the conversations or express any opinion. After -hearing what was being said by one or other of these groups he -generally turned away with an air of disappointment, as though they -were not speaking of anything he wished to hear. Some discussed the -position that had been chosen, criticizing not the position itself -so much as the mental capacity of those who had chosen it. Others -argued that a mistake had been made earlier and that a battle should -have been fought two days before. Others again spoke of the battle -of Salamanca, which was described by Crosart, a newly arrived -Frenchman in a Spanish uniform. (This Frenchman and one of the -German princes serving with the Russian army were discussing the siege -of Saragossa and considering the possibility of defending Moscow in -a similar manner.) Count Rostopchin was telling a fourth group that he -was prepared to die with the city train bands under the walls of the -capital, but that he still could not help regretting having been -left in ignorance of what was happening, and that had he known it -sooner things would have been different.... A fifth group, -displaying the profundity of their strategic perceptions, discussed -the direction the troops would now have to take. A sixth group was -talking absolute nonsense. Kutuzov's expression grew more and more -preoccupied and gloomy. From all this talk he saw only one thing: that -to defend Moscow was a physical impossibility in the full meaning of -those words, that is to say, so utterly impossible that if any -senseless commander were to give orders to fight, confusion would -result but the battle would still not take place. It would not take -place because the commanders not merely all recognized the position to -be impossible, but in their conversations were only discussing what -would happen after its inevitable abandonment. How could the -commanders lead their troops to a field of battle they considered -impossible to hold? The lower-grade officers and even the soldiers -(who too reason) also considered the position impossible and therefore -could not go to fight, fully convinced as they were of defeat. If -Bennigsen insisted on the position being defended and others still -discussed it, the question was no longer important in itself but -only as a pretext for disputes and intrigue. This Kutuzov knew well. - -Bennigsen, who had chosen the position, warmly displayed his Russian -patriotism (Kutuzov could not listen to this without wincing) by -insisting that Moscow must be defended. His aim was as clear as -daylight to Kutuzov: if the defense failed, to throw the blame on -Kutuzov who had brought the army as far as the Sparrow Hills without -giving battle; if it succeeded, to claim the success as his own; or if -battle were not given, to clear himself of the crime of abandoning -Moscow. But this intrigue did not now occupy the old man's mind. One -terrible question absorbed him and to that question he heard no -reply from anyone. The question for him now was: "Have I really -allowed Napoleon to reach Moscow, and when did I do so? When was it -decided? Can it have been yesterday when I ordered Platov to -retreat, or was it the evening before, when I had a nap and told -Bennigsen to issue orders? Or was it earlier still?... When, when -was this terrible affair decided? Moscow must be abandoned. The army -must retreat and the order to do so must be given." To give that -terrible order seemed to him equivalent to resigning the command of -the army. And not only did he love power to which he was accustomed -(the honours awarded to Prince Prozorovski, under whom he had served -in Turkey, galled him), but he was convinced that he was destined to -save Russia and that that was why, against the Emperor's wish and by -the will of the people, he had been chosen commander in chief. He -was convinced that he alone could maintain command of the army in -these difficult circumstances, and that in all the world he alone -could encounter the invincible Napoleon without fear, and he was -horrified at the thought of the order he had to issue. But something -had to be decided, and these conversations around him which were -assuming too free a character must be stopped. - -He called the most important generals to him. - -"My head, be it good or bad, must depend on itself," said he, rising -from the bench, and he rode to Fili where his carriages were waiting. - - - - - -CHAPTER IV - - -The Council of War began to assemble at two in the afternoon in -the better and roomier part of Andrew Savostyanov's hut. The men, -women, and children of the large peasant family crowded into the -back room across the passage. Only Malasha, Andrew's six-year-old -granddaughter whom his Serene Highness had petted and to whom he had -given a lump of sugar while drinking his tea, remained on the top of -the brick oven in the larger room. Malasha looked down from the oven -with shy delight at the faces, uniforms, and decorations of the -generals, who one after another came into the room and sat down on the -broad benches in the corner under the icons. "Granddad" himself, as -Malasha in her own mind called Kutuzov, sat apart in a dark corner -behind the oven. He sat, sunk deep in a folding armchair, and -continually cleared his throat and pulled at the collar of his coat -which, though it was unbuttoned, still seemed to pinch his neck. Those -who entered went up one by one to the field marshal; he pressed the -hands of some and nodded to others. His adjutant Kaysarov was about to -draw back the curtain of the window facing Kutuzov, but the latter -moved his hand angrily and Kaysarov understood that his Serene -Highness did not wish his face to be seen. - -Round the peasant's deal table, on which lay maps, plans, pencils, -and papers, so many people gathered that the orderlies brought in -another bench and put it beside the table. Ermolov, Kaysarov, and -Toll, who had just arrived, sat down on this bench. In the foremost -place, immediately under the icons, sat Barclay de Tolly, his high -forehead merging into his bald crown. He had a St. George's Cross -round his neck and looked pale and ill. He had been feverish for two -days and was now shivering and in pain. Beside him sat Uvarov, who -with rapid gesticulations was giving him some information, speaking in -low tones as they all did. Chubby little Dokhturov was listening -attentively with eyebrows raised and arms folded on his stomach. On -the other side sat Count Ostermann-Tolstoy, seemingly absorbed in -his own thoughts. His broad head with its bold features and glittering -eyes was resting on his hand. Raevski, twitching forward the black -hair on his temples as was his habit, glanced now at Kutuzov and now -at the door with a look of impatience. Konovnitsyn's firm, handsome, -and kindly face was lit up by a tender, sly smile. His glance met -Malasha's, and the expression of his eyes caused the little girl to -smile. - -They were all waiting for Bennigsen, who on the pretext of -inspecting the position was finishing his savory dinner. They waited -for him from four till six o'clock and did not begin their -deliberations all that time talked in low tones of other matters. - -Only when Bennigsen had entered the hut did Kutuzov leave his corner -and draw toward the table, but not near enough for the candles that -had been placed there to light up his face. - -Bennigsen opened the council with the question: "Are we to abandon -Russia's ancient and sacred capital without a struggle, or are we to -defend it?" A prolonged and general silence followed. There was a -frown on every face and only Kutuzov's angry grunts and occasional -cough broke the silence. All eyes were gazing at him. Malasha too -looked at "Granddad." She was nearest to him and saw how his face -puckered; he seemed about to cry, but this did not last long. - -"Russia's ancient and sacred capital!" he suddenly said, repeating -Bennigsen's words in an angry voice and thereby drawing attention to -the false note in them. "Allow me to tell you, your excellency, that -that question has no meaning for a Russian." (He lurched his heavy -body forward.) "Such a question cannot be put; it is senseless! The -question I have asked these gentlemen to meet to discuss is a military -one. The question is that of saving Russia. Is it better to give up -Moscow without a battle, or by accepting battle to risk losing the -army as well as Moscow? That is the question on which I want your -opinion," and he sank back in his chair. - -The discussion began. Bennigsen did not yet consider his game -lost. Admitting the view of Barclay and others that a defensive battle -at Fili was impossible, but imbued with Russian patriotism and the -love of Moscow, he proposed to move troops from the right to the -left flank during the night and attack the French right flank the -following day. Opinions were divided, and arguments were advanced -for and against that project. Ermolov, Dokhturov, and Raevski agreed -with Bennigsen. Whether feeling it necessary to make a sacrifice -before abandoning the capital or guided by other, personal -considerations, these generals seemed not to understand that this -council could not alter the inevitable course of events and that -Moscow was in effect already abandoned. The other generals, however, -understood it and, leaving aside the question of Moscow, of the -direction the army should take in its retreat. Malasha, who kept her -eyes fixed on what was going on before her, understood the meaning -of the council differently. It seemed to her that it was only a -personal struggle between "Granddad" and "Long-coat" as she termed -Bennigsen. She saw that they grew spiteful when they spoke to one -another, and in her heart she sided with "Granddad." In the midst of -the conversation she noticed "Granddad" give Bennigsen a quick, subtle -glance, and then to her joys he saw that "Granddad" said something -to "Long-coat" which settled him. Bennigsen suddenly reddened and -paced angrily up and down the room. What so affected him was Kutuzov's -calm and quiet comment on the advantage or disadvantage of Bennigsen's -proposal to move troops by night from the right to the left flank to -attack the French right wing. - -"Gentlemen," said Kutuzov, "I cannot approve of the count's plan. -Moving troops in close proximity to an enemy is always dangerous, -and military history supports that view. For instance..." Kutuzov -seemed to reflect, searching for an example, then with a clear, -naive look at Bennigsen he added: "Oh yes; take the battle of -Friedland, which I think the count well remembers, and which was... -not fully successful, only because our troops were rearranged too near -the enemy..." - -There followed a momentary pause, which seemed very long to them -all. - -The discussion recommenced, but pauses frequently occurred and -they all felt that there was no more to be said. - -During one of these pauses Kutuzov heaved a deep sigh as if -preparing to speak. They all looked at him. - -"Well, gentlemen, I see that it is I who will have to pay for the -broken crockery," said he, and rising slowly he moved to the table. -"Gentlemen, I have heard your views. Some of you will not agree with -me. But I," he paused, "by the authority entrusted to me by my -Sovereign and country, order a retreat." - -After that the generals began to disperse with the solemnity and -circumspect silence of people who are leaving, after a funeral. - -Some of the generals, in low tones and in a strain very different -from the way they had spoken during the council, communicated -something to their commander in chief. - -Malasha, who had long been expected for supper, climbed carefully -backwards down from the oven, her bare little feet catching at its -projections, and slipping between the legs of the generals she -darted out of the room. - -When he had dismissed the generals Kutuzov sat a long time with -his elbows on the table, thinking always of the same terrible -question: "When, when did the abandonment of Moscow become inevitable? -When was that done which settled the matter? And who was to blame -for it?" - -"I did not expect this," said he to his adjutant Schneider when -the latter came in late that night. "I did not expect this! I did -not think this would happen." - -"You should take some rest, your Serene Highness," replied -Schneider. - -"But no! They shall eat horseflesh yet, like the Turks!" exclaimed -Kutuzov without replying, striking the table with his podgy fist. -"They shall too, if only..." - - - - - -CHAPTER V - - -At that very time, in circumstances even more important than -retreating without a battle, namely the evacuation and burning of -Moscow, Rostopchin, who is usually represented as being the instigator -of that event, acted in an altogether different manner from Kutuzov. - -After the battle of Borodino the abandonment and burning of Moscow -was as inevitable as the retreat of the army beyond Moscow without -fighting. - -Every Russian might have predicted it, not by reasoning but by the -feeling implanted in each of us and in our fathers. - -The same thing that took place in Moscow had happened in all the -towns and villages on Russian soil beginning with Smolensk, without -the participation of Count Rostopchin and his broadsheets. The -people awaited the enemy unconcernedly, did not riot or become excited -or tear anyone to pieces, but faced its fate, feeling within it the -strength to find what it should do at that most difficult moment. -And as soon as the enemy drew near the wealthy classes went away -abandoning their property, while the poorer remained and burned and -destroyed what was left. - -The consciousness that this would be so and would always be so was -and is present in the heart of every Russian. And a consciousness of -this, and a foreboding that Moscow would be taken, was present in -Russian Moscow society in 1812. Those who had quitted Moscow already -in July and at the beginning of August showed that they expected this. -Those who went away, taking what they could and abandoning their -houses and half their belongings, did so from the latent patriotism -which expresses itself not by phrases or by giving one's children to -save the fatherland and similar unnatural exploits, but unobtrusively, -simply, organically, and therefore in the way that always produces the -most powerful results. - -"It is disgraceful to run away from danger; only cowards are running -away from Moscow," they were told. In his broadsheets Rostopchin -impressed on them that to leave Moscow was shameful. They were ashamed -to be called cowards, ashamed to leave, but still they left, knowing -it had to be done. Why did they go? It is impossible to suppose that -Rostopchin had scared them by his accounts of horrors Napoleon had -committed in conquered countries. The first people to go away were the -rich educated people who knew quite well that Vienna and Berlin had -remained intact and that during Napoleon's occupation the -inhabitants had spent their time pleasantly in the company of the -charming Frenchmen whom the Russians, and especially the Russian -ladies, then liked so much. - -They went away because for Russians there could be no question as to -whether things would go well or ill under French rule in Moscow. It -was out of the question to be under French rule, it would be the worst -thing that could happen. They went away even before the battle of -Borodino and still more rapidly after it, despite Rostopchin's calls -to defend Moscow or the announcement of his intention to take the -wonder-working icon of the Iberian Mother of God and go to fight, or -of the balloons that were to destroy the French, and despite all the -nonsense Rostopchin wrote in his broadsheets. They knew that it was -for the army to fight, and that if it could not succeed it would not -do to take young ladies and house serfs to the Three Hills quarter -of Moscow to fight Napoleon, and that they must go away, sorry as they -were to abandon their property to destruction. They went away -without thinking of the tremendous significance of that immense and -wealthy city being given over to destruction, for a great city with -wooden buildings was certain when abandoned by its inhabitants to be -burned. They went away each on his own account, and yet it was only in -consequence of their going away that the momentous event was -accomplished that will always remain the greatest glory of the Russian -people. The lady who, afraid of being stopped by Count Rostopchin's -orders, had already in June moved with her Negroes and her women -jesters from Moscow to her Saratov estate, with a vague -consciousness that she was not Bonaparte's servant, was really, -simply, and truly carrying out the great work which saved Russia. -But Count Rostopchin, who now taunted those who left Moscow and now -had the government offices removed; now distributed quite useless -weapons to the drunken rabble; now had processions displaying the -icons, and now forbade Father Augustin to remove icons or the relics -of saints; now seized all the private carts in Moscow and on one -hundred and thirty-six of them removed the balloon that was being -constructed by Leppich; now hinted that he would burn Moscow and -related how he had set fire to his own house; now wrote a proclamation -to the French solemnly upbraiding them for having destroyed his -Orphanage; now claimed the glory of having hinted that he would burn -Moscow and now repudiated the deed; now ordered the people to catch -all spies and bring them to him, and now reproached them for doing so; -now expelled all the French residents from Moscow, and now allowed -Madame Aubert-Chalme (the center of the whole French colony in Moscow) -to remain, but ordered the venerable old postmaster Klyucharev to be -arrested and exiled for no particular offense; now assembled the -people at the Three Hills to fight the French and now, to get rid of -them, handed over to them a man to be killed and himself drove away by -a back gate; now declared that he would not survive the fall of -Moscow, and now wrote French verses in albums concerning his share -in the affair--this man did not understand the meaning of what was -happening but merely wanted to do something himself that would -astonish people, to perform some patriotically heroic feat; and like a -child he made sport of the momentous, and unavoidable event--the -abandonment and burning of Moscow--and tried with his puny hand now to -speed and now to stay the enormous, popular tide that bore him along -with it. - - - - - -CHAPTER VI - - -Helene, having returned with the court from Vilna to Petersburg, -found herself in a difficult position. - -In Petersburg she had enjoyed the special protection of a grandee -who occupied one of the highest posts in the Empire. In Vilna she -had formed an intimacy with a young foreign prince. When she -returned to Petersburg both the magnate and the prince were there, and -both claimed their rights. Helene was faced by a new problem--how to -preserve her intimacy with both without offending either. - -What would have seemed difficult or even impossible to another woman -did not cause the least embarrassment to Countess Bezukhova, who -evidently deserved her reputation of being a very clever woman. Had -she attempted concealment, or tried to extricate herself from her -awkward position by cunning, she would have spoiled her case by -acknowledging herself guilty. But Helene, like a really great man -who can do whatever he pleases, at once assumed her own position to be -correct, as she sincerely believed it to be, and that everyone else -was to blame. - -The first time the young foreigner allowed himself to reproach -her, she lifted her beautiful head and, half turning to him, said -firmly: "That's just like a man--selfish and cruel! I expected nothing -else. A woman sacrifices herself for you, she suffers, and this is her -reward! What right have you, monseigneur, to demand an account of my -attachments and friendships? He is a man who has been more than a -father to me!" The prince was about to say something, but Helene -interrupted him. - -"Well, yes," said she, "it may be that he has other sentiments for -me than those of a father, but that is not a reason for me to shut -my door on him. I am not a man, that I should repay kindness with -ingratitude! Know, monseigneur, that in all that relates to my -intimate feelings I render account only to God and to my -conscience," she concluded, laying her hand on her beautiful, fully -expanded bosom and looking up to heaven. - -"But for heaven's sake listen to me!" - -"Marry me, and I will be your slave!" - -"But that's impossible." - -"You won't deign to demean yourself by marrying me, you..." said -Helene, beginning to cry. - -The prince tried to comfort her, but Helene, as if quite distraught, -said through her tears that there was nothing to prevent her marrying, -that there were precedents (there were up to that time very few, but -she mentioned Napoleon and some other exalted personages), that she -had never been her husband's wife, and that she had been sacrificed. - -"But the law, religion..." said the prince, already yielding. - -"The law, religion... What have they been invented for if they can't -arrange that?" said Helene. - -The prince was surprised that so simple an idea had not occurred -to him, and he applied for advice to the holy brethren of the -Society of Jesus, with whom he was on intimate terms. - -A few days later at one of those enchanting fetes which Helene -gave at her country house on the Stone Island, the charming Monsieur -de Jobert, a man no longer young, with snow white hair and brilliant -black eyes, a Jesuit a robe courte* was presented to her, and in the -garden by the light of the illuminations and to the sound of music -talked to her for a long time of the love of God, of Christ, of the -Sacred Heart, and of the consolations the one true Catholic religion -affords in this world and the next. Helene was touched, and more -than once tears rose to her eyes and to those of Monsieur de Jobert -and their voices trembled. A dance, for which her partner came to seek -her, put an end to her discourse with her future directeur de -conscience, but the next evening Monsieur de Jobert came to see Helene -when she was alone, and after that often came again. - - -*Lay member of the Society of Jesus. - - -One day he took the countess to a Roman Catholic church, where she -knelt down before the altar to which she was led. The enchanting, -middle-aged Frenchman laid his hands on her head and, as she herself -afterward described it, she felt something like a fresh breeze -wafted into her soul. It was explained to her that this was la grace. - -After that a long-frocked abbe was brought to her. She confessed -to him, and he absolved her from her sins. Next day she received a box -containing the Sacred Host, which was left at her house for her to -partake of. A few days later Helene learned with pleasure that she had -now been admitted to the true Catholic Church and that in a few days -the Pope himself would hear of her and would send her a certain -document. - -All that was done around her and to her at this time, all the -attention devoted to her by so many clever men and expressed in such -pleasant, refined ways, and the state of dove-like purity she was -now in (she wore only white dresses and white ribbons all that time) -gave her pleasure, but her pleasure did not cause her for a moment -to forget her aim. And as it always happens in contests of cunning -that a stupid person gets the better of cleverer ones, Helene- -having realized that the main object of all these words and all this -trouble was, after converting her to Catholicism, to obtain money from -her for Jesuit institutions (as to which she received indications)- -before parting with her money insisted that the various operations -necessary to free her from her husband should be performed. In her -view the aim of every religion was merely to preserve certain -proprieties while affording satisfaction to human desires. And with -this aim, in one of her talks with her Father Confessor, she -insisted on an answer to the question, in how far was she bound by her -marriage? - -They were sitting in the twilight by a window in the drawing room. -The scent of flowers came in at the window. Helene was wearing a white -dress, transparent over her shoulders and bosom. The abbe, a -well-fed man with a plump, clean-shaven chin, a pleasant firm mouth, -and white hands meekly folded on his knees, sat close to Helene and, -with a subtle smile on his lips and a peaceful look of delight at -her beauty, occasionally glanced at her face as he explained his -opinion on the subject. Helene with an uneasy smile looked at his -curly hair and his plump, clean-shaven, blackish cheeks and every -moment expected the conversation to take a fresh turn. But the abbe, -though he evidently enjoyed the beauty of his companion, was -absorbed in his mastery of the matter. - -The course of the Father Confessor's arguments ran as follows: -"Ignorant of the import of what you were undertaking, you made a vow -of conjugal fidelity to a man who on his part, by entering the married -state without faith in the religious significance of marriage, -committed an act of sacrilege. That marriage lacked the dual -significance it should have had. Yet in spite of this your vow was -binding. You swerved from it. What did you commit by so acting? A -venial, or a mortal, sin? A venial sin, for you acted without evil -intention. If now you married again with the object of bearing -children, your sin might be forgiven. But the question is again a -twofold one: firstly..." - -But suddenly Helene, who was getting bored, said with one of her -bewitching smiles: "But I think that having espoused the true religion -I cannot be bound by what a false religion laid upon me." - -The director of her conscience was astounded at having the case -presented to him thus with the simplicity of Columbus' egg. He was -delighted at the unexpected rapidity of his pupil's progress, but -could not abandon the edifice of argument he had laboriously -constructed. - -"Let us understand one another, Countess," said he with a smile, and -began refuting his spiritual daughter's arguments. - - - - - -CHAPTER VII - - -Helene understood that the question was very simple and easy from -the ecclesiastical point of view, and that her directors were making -difficulties only because they were apprehensive as to how the -matter would be regarded by the secular authorities. - -So she decided that it was necessary to prepare the opinion of -society. She provoked the jealousy of the elderly magnate and told him -what she had told her other suitor; that is, she put the matter so -that the only way for him to obtain a right over her was to marry her. -The elderly magnate was at first as much taken aback by this -suggestion of marriage with a woman whose husband was alive, as the -younger man had been, but Helene's imperturbable conviction that it -was as simple and natural as marrying a maiden had its effect on him -too. Had Helene herself shown the least sign of hesitation, shame, -or secrecy, her cause would certainly have been lost; but not only did -she show no signs of secrecy or shame, on the contrary, with -good-natured naivete she told her intimate friends (and these were all -Petersburg) that both the prince and the magnate had proposed to her -and that she loved both and was afraid of grieving either. - -A rumor immediately spread in Petersburg, not that Helene wanted -to be divorced from her husband (had such a report spread many would -have opposed so illegal an intention) but simply that the -unfortunate and interesting Helene was in doubt which of the two men -she should marry. The question was no longer whether this was -possible, but only which was the better match and how the matter would -be regarded at court. There were, it is true, some rigid individuals -unable to rise to the height of such a question, who saw in the -project a desecration of the sacrament of marriage, but there were not -many such and they remained silent, while the majority were interested -in Helene's good fortune and in the question which match would be -the more advantageous. Whether it was right or wrong to remarry -while one had a husband living they did not discuss, for that question -had evidently been settled by people "wiser than you or me," as they -said, and to doubt the correctness of that decision would be to risk -exposing one's stupidity and incapacity to live in society. - -Only Marya Dmitrievna Akhrosimova, had come to Petersburg that -summer to see one of her sons, allowed herself plainly to express an -opinion contrary to the general one. Meeting Helene at a ball she -stopped her in the middle of the room and, amid general silence, -said in her gruff voice: "So wives of living men have started marrying -again! Perhaps you think you have invented a novelty? You have been -forestalled, my dear! It was thought of long ago. It is done in all -the brothels," and with these words Marya Dmitrievna, turning up her -wide sleeves with her usual threatening gesture and glancing sternly -round, moved across the room. - -Though people were afraid of Marya Dmitrievna she was regarded in -Petersburg as a buffoon, and so of what she had said they only -noticed, and repeated in a whisper, the one coarse word she had -used, supposing the whole sting of her remark to lie in that word. - -Prince Vasili, who of late very often forgot what he had said and -repeated one and the same thing a hundred times, remarked to his -daughter whenever he chanced to see her: - -"Helene, I have a word to say to you," and he would lead her -aside, drawing her hand downward. "I have heard of certain projects -concerning... you know. Well my dear child, you know how your father's -heart rejoices to know that you... You have suffered so much.... -But, my dear child, consult only your own heart. That is all I have to -say," and concealing his unvarying emotion he would press his cheek -against his daughter's and move away. - -Bilibin, who had not lost his reputation of an exceedingly clever -man, and who was one of the disinterested friends so -brilliant a woman as Helene always has--men friends who can never -change into lovers--once gave her his view of the matter at a small -and intimate gathering. - -"Listen, Bilibin," said Helene (she always called friends of that -sort by their surnames), and she touched his coat sleeve with her -white, beringed fingers. "Tell me, as you would a sister, what I ought -to do. Which of the two?" - -Bilibin wrinkled up the skin over his eyebrows and pondered, with -a smile on his lips. - -"You are not taking me unawares, you know," said he. "As a true -friend, I have thought and thought again about your affair. You see, -if you marry the prince"--he meant the younger man--and he crooked one -finger, "you forever lose the chance of marrying the other, and you -will displease the court besides. (You know there is some kind of -connection.) But if you marry the old count you will make his last -days happy, and as widow of the Grand... the prince would no longer be -making a mesalliance by marrying you," and Bilibin smoothed out his -forehead. - -"That's a true friend!" said Helene beaming, and again touching -Bilibin's sleeve. "But I love them, you know, and don't want to -distress either of them. I would give my life for the happiness of -them both." - -Bilibin shrugged his shoulders, as much as to say that not even he -could help in that difficulty. - -"Une maitresse-femme!* That's what is called putting things -squarely. She would like to be married to all three at the same time," -thought he. - - -*A masterly woman. - - -"But tell me, how will your husband look at the matter?" Bilibin -asked, his reputation being so well established that he did not fear -to ask so naive a question. "Will he agree?" - -"Oh, he loves me so!" said Helene, who for some reason imagined that -Pierre too loved her. "He will do anything for me." - -Bilibin puckered his skin in preparation for something witty. - -"Even divorce you?" said he. - -Helene laughed. - -Among those who ventured to doubt the justifiability of the proposed -marriage was Helene's mother, Princess Kuragina. She was continually -tormented by jealousy of her daughter, and now that jealousy concerned -a subject near to her own heart, she could not reconcile herself to -the idea. She consulted a Russian priest as to the possibility of -divorce and remarriage during a husband's lifetime, and the priest -told her that it was impossible, and to her delight showed her a -text in the Gospel which (as it seemed to him) plainly remarriage -while the husband is alive. - -Armed with these arguments, which appeared to her unanswerable, -she drove to her daughter's early one morning so as to find her alone. - -Having listened to her mother's objections, Helene smiled blandly -and ironically. - -"But it says plainly: 'Whosoever shall marry her that is -divorced...'" said the old princess. - -"Ah, Maman, ne dites pas de betises. Vous ne comprenez rein. Dans ma -position j'ai des devoirs,"* said Helene changing from Russian, in -which language she always felt that her case did not sound quite -clear, into French which suited it better. - - -*"Oh, Mamma, don't talk nonsense! You don't understand anything. -In my position I have obligations. - - -"But, my dear...." - -"Oh, Mamma, how is it you don't understand that the Holy Father, who -has the right to grant dispensations..." - -Just then the lady companion who lived with Helene came in to -announce that His Highness was in the ballroom and wished to see her. - -"Non, dites-lui que je ne veux pas le voir, que je suis furieuse -contre lui, parce qu'il m' a manque parole."* - - -*"No, tell him I don't wish to see him, I am furious with him for -not keeping his word to me." - - -"Comtesse, a tout peche misericorde,"* said a fair-haired young -man with a long face and nose, as he entered the room. - - -*"Countess, there is mercy for every sin." - - -The old princess rose respectfully and curtsied. The young man who -had entered took no notice of her. The princess nodded to her daughter -and sidled out of the room. - -"Yes, she is right," thought the old princess, all her convictions -dissipated by the appearance of His Highness. "She is right, but how -is it that we in our irrecoverable youth did not know it? Yet it is so -simple," she thought as she got into her carriage. - - -By the beginning of August Helene's affairs were clearly defined and -she wrote a letter to her husband--who, as she imagined, loved her -very much--informing him of her intention to marry N.N. and of her -having embraced the one true faith, and asking him to carry out all -the formalities necessary for a divorce, which would be explained to -him by the bearer of the letter. - - -And so I pray God to have you, my friend, in His holy and powerful -keeping--Your friend Helene. - - -This letter was brought to Pierre's house when he was on the field -of Borodino. - - - - - -CHAPTER VIII - - -Toward the end of the battle of Borodino, Pierre, having run down -from Raevski's battery a second time, made his way through a gully -to Knyazkovo with a crowd of soldiers, reached the dressing station, -and seeing blood and hearing cries and groans hurried on, still -entangled in the crowds of soldiers. - -The one thing he now desired with his whole soul was to get away -quickly from the terrible sensations amid which he had lived that -day and return to ordinary conditions of life and sleep quietly in a -room in his own bed. He felt that only in the ordinary conditions of -life would he be able to understand himself and all he had seen and -felt. But such ordinary conditions of life were nowhere to be found. - -Though shells and bullets did not whistle over the road along -which he was going, still on all sides there was what there had been -on the field of battle. There were still the same suffering, -exhausted, and sometimes strangely indifferent faces, the same -blood, the same soldiers' overcoats, the same sounds of firing -which, though distant now, still aroused terror, and besides this -there were the foul air and the dust. - -Having gone a couple of miles along the Mozhaysk road, Pierre sat -down by the roadside. - -Dusk had fallen, and the roar of guns died away. Pierre lay -leaning on his elbow for a long time, gazing at the shadows that moved -past him in the darkness. He was continually imagining that a cannon -ball was flying toward him with a terrific whizz, and then he -shuddered and sat up. He had no idea how long he had been there. In -the middle of the night three soldiers, having brought some -firewood, settled down near him and began lighting a fire. - -The soldiers, who threw sidelong glances at Pierre, got the fire -to burn and placed an iron pot on it into which they broke some -dried bread and put a little dripping. The pleasant odor of greasy -viands mingled with the smell of smoke. Pierre sat up and sighed. -The three soldiers were eating and talking among themselves, taking no -notice of him. - -"And who may you be?" one of them suddenly asked Pierre, evidently -meaning what Pierre himself had in mind, namely: "If you want to eat -we'll give you some food, only let us know whether you are an honest -man." - -"I, I..." said Pierre, feeling it necessary to minimize his social -position as much as possible so as to be nearer to the soldiers and -better understood by them. "By rights I am a militia officer, but my -men are not here. I came to the battle and have lost them." - -"There now!" said one of the soldiers. - -Another shook his head. - -"Would you like a little mash?" the first soldier asked, and -handed Pierre a wooden spoon after licking it clean. - -Pierre sat down by the fire and began eating the mash, as they -called the food in the cauldron, and he thought it more delicious than -any food he had ever tasted. As he sat bending greedily over it, -helping himself to large spoonfuls and chewing one after another, -his was lit up by the fire and the soldiers looked at him in silence. - -"Where have you to go to? Tell us!" said one of them. - -"To Mozhaysk." - -"You're a gentleman, aren't you?" - -"Yes." - -"And what's your name?" - -"Peter Kirilych." - -"Well then, Peter Kirilych, come along with us, we'll take you -there." - -In the total darkness the soldiers walked with Pierre to Mozhaysk. - -By the time they got near Mozhaysk and began ascending the steep -hill into the town, the cocks were already crowing. Pierre went on -with the soldiers, quite forgetting that his inn was at the bottom -of the hill and that he had already passed it. He would not soon -have remembered this, such was his state of forgetfulness, had he -not halfway up the hill stumbled upon his groom, who had been to -look for him in the town and was returning to the inn. The groom -recognized Pierre in the darkness by his white hat. - -"Your excellency!" he said. "Why, we were beginning to despair! -How is it you are on foot? And where are you going, please?" - -"Oh, yes!" said Pierre. - -The soldiers stopped. - -"So you've found your folk?" said one of them. "Well, good-by, Peter -Kirilych--isn't it?" - -"Good-by, Peter Kirilych!" Pierre heard the other voices repeat. - -"Good-by!" he said and turned with his groom toward the inn. - -"I ought to give them something!" he thought, and felt in his -pocket. "No, better not!" said another, inner voice. - -There was not a room to be had at the inn, they were all occupied. -Pierre went out into the yard and, covering himself up head and all, -lay down in his carriage. - - - - - -CHAPTER IX - - -Scarcely had Pierre laid his head on the pillow before he felt -himself falling asleep, but suddenly, almost with the distinctness -of reality, he heard the boom, boom, boom of firing, the thud of -projectiles, groans and cries, and smelled blood and powder, and a -feeling of horror and dread of death seized him. Filled with fright he -opened his eyes and lifted his head from under his cloak. All was -tranquil in the yard. Only someone's orderly passed through the -gateway, splashing through the mud, and talked to the innkeeper. Above -Pierre's head some pigeons, disturbed by the movement he had made in -sitting up, fluttered under the dark roof of the penthouse. The -whole courtyard was permeated by a strong peaceful smell of stable -yards, delightful to Pierre at that moment. He could see the clear -starry sky between the dark roofs of two penthouses. - -"Thank God, there is no more of that!" he thought, covering up his -head again. "Oh, what a terrible thing is fear, and how shamefully I -yielded to it! But they... they were steady and calm all the time, -to the end..." thought he. - -They, in Pierre's mind, were the soldiers, those who had been at the -battery, those who had given him food, and those who had prayed before -the icon. They, those strange men he had not previously known, stood -out clearly and sharply from everyone else. - -"To be a soldier, just a soldier!" thought Pierre as he fell asleep, -"to enter communal life completely, to be imbued by what makes them -what they are. But how cast off all the superfluous, devilish burden -of my outer man? There was a time when I could have done it. I could -have run away from my father, as I wanted to. Or I might have been -sent to serve as a soldier after the duel with Dolokhov." And the -memory of the dinner at the English Club when he had challenged -Dolokhov flashed through Pierre's mind, and then he remembered his -benefactor at Torzhok. And now a picture of a solemn meeting of the -lodge presented itself to his mind. It was taking place at the English -Club and someone near and dear to him sat at the end of the table. -"Yes, that is he! It is my benefactor. But he died!" thought Pierre. -"Yes, he died, and I did not know he was alive. How sorry I am that he -died, and how glad I am that he is alive again!" On one side of the -table sat Anatole, Dolokhov, Nesvitski, Denisov, and others like -them (in his dream the category to which these men belonged was as -clearly defined in his mind as the category of those he termed -they), and he heard those people, Anatole and Dolokhov, shouting and -singing loudly; yet through their shouting the voice of his benefactor -was heard speaking all the time and the sound of his words was as -weighty and uninterrupted as the booming on the battlefield, but -pleasant and comforting. Pierre did not understand what his benefactor -was saying, but he knew (the categories of thoughts were also quite -distinct in his dream) that he was talking of goodness and the -possibility of being what they were. And they with their simple, kind, -firm faces surrounded his benefactor on all sides. But though they -were kindly they did not look at Pierre and did not know him. -Wishing to speak and to attract their attention, he got up, but at -that moment his legs grew cold and bare. - -He felt ashamed, and with one arm covered his legs from which his -cloak had in fact slipped. For a moment as he was rearranging his -cloak Pierre opened his eyes and saw the same penthouse roofs, -posts, and yard, but now they were all bluish, lit up, and -glittering with frost or dew. - -"It is dawn," thought Pierre. "But that's not what I want. I want to -hear and understand my benefactor's words." Again he covered himself -up with his cloak, but now neither the lodge nor his benefactor was -there. There were only thoughts clearly expressed in words, thoughts -that someone was uttering or that he himself was formulating. - -Afterwards when he recalled those thoughts Pierre was convinced that -someone outside himself had spoken them, though the impressions of -that day had evoked them. He had never, it seemed to him, been able to -think and express his thoughts like that when awake. - -"To endure war is the most difficult subordination of man's -freedom to the law of God," the voice had said. "Simplicity is -submission to the will of God; you cannot escape from Him. And they -are simple. They do not talk, but act. The spoken word is silver but -the unspoken is golden. Man can be master of nothing while he fears -death, but he who does not fear it possesses all. If there were no -suffering, man would not know his limitations, would not know himself. -The hardest thing [Pierre went on thinking, or hearing, in his -dream] is to be able in your soul to unite the meaning of all. To -unite all?" he asked himself. "No, not to unite. Thoughts cannot be -united, but to harness all these thoughts together is what we need! -Yes, one must harness them, must harness them!" he repeated to himself -with inward rapture, feeling that these words and they alone expressed -what he wanted to say and solved the question that tormented him. - -"Yes, one must harness, it is time to harness." - -"Time to harness, time to harness, your excellency! Your -excellency!" some voice was repeating. "We must harness, it is time to -harness...." - -It was the voice of the groom, trying to wake him. The sun shone -straight into Pierre's face. He glanced at the dirty innyard in the -middle of which soldiers were watering their lean horses at the pump -while carts were passing out of the gate. Pierre turned away with -repugnance, and closing his eyes quickly fell back on the carriage -seat. "No, I don't want that, I don't want to see and understand that. -I want to understand what was revealing itself to me in my dream. -One second more and I should have understood it all! But what am I -to do? Harness, but how can I harness everything?" and Pierre felt -with horror that the meaning of all he had seen and thought in the -dream had been destroyed. - -The groom, the coachman, and the innkeeper told Pierre that an -officer had come with news that the French were already near -Mozhaysk and that our men were leaving it. - -Pierre got up and, having told them to harness and overtake him, -went on foot through the town. - -The troops were moving on, leaving about ten thousand wounded behind -them. There were wounded in the yards, at the windows of the houses, -and the streets were crowded with them. In the streets, around carts -that were to take some of the wounded away, shouts, curses, and -blows could be heard. Pierre offered the use of his carriage, which -had overtaken him, to a wounded general he knew, and drove with him -to Moscow. On the way Pierre was told of the death of his -brother-in-law Anatole and of that of Prince Andrew. - - - - - -CHAPTER X - - -On the thirteenth of August Pierre reached Moscow. Close to the -gates of the city he was met by Count Rostopchin's adjutant. - -"We have been looking for you everywhere," said the adjutant. "The -count wants to see you particularly. He asks you to come to him at -once on a very important matter." - -Without going home, Pierre took a cab and drove to see the Moscow -commander in chief. - -Count Rostopchin had only that morning returned to town from his -summer villa at Sokolniki. The anteroom and reception room of his -house were full of officials who had been summoned or had come for -orders. Vasilchikov and Platov had already seen the count and -explained to him that it was impossible to defend Moscow and that it -would have to be surrendered. Though this news was being concealed -from the inhabitants, the officials--the heads of the various -government departments--knew that Moscow would soon be in the -enemy's hands, just as Count Rostopchin himself knew it, and to escape -personal responsibility they had all come to the governor to ask how -they were to deal with their various departments. - -As Pierre was entering the reception room a courier from the army -came out of Rostopchin's private room. - -In answer to questions with which he was greeted, the courier made a -despairing gesture with his hand and passed through the room. - -While waiting in the reception room Pierre with weary eyes watched -the various officials, old and young, military and civilian, who -were there. They all seemed dissatisfied and uneasy. Pierre went up to -a group of men, one of whom he knew. After greeting Pierre they -continued their conversation. - -"If they're sent out and brought back again later on it will do no -harm, but as things are now one can't answer for anything." - -"But you see what he writes..." said another, pointing to a -printed sheet he held in his hand. - -"That's another matter. That's necessary for the people," said the -first. - -"What is it?" asked Pierre. - -"Oh, it's a fresh broadsheet." - -Pierre took it and began reading. - - -His Serene Highness has passed through Mozhaysk in order to join -up with the troops moving toward him and has taken up a strong -position where the enemy will not soon attack him. Forty eight guns -with ammunition have been sent him from here, and his Serene -Highness says he will defend Moscow to the last drop of blood and is -even ready to fight in the streets. Do not be upset, brothers, that -the law courts are closed; things have to be put in order, and we will -deal with villains in our own way! When the time comes I shall want -both town and peasant lads and will raise the cry a day or two -beforehand, but they are not wanted yet so I hold my peace. An ax will -be useful, a hunting spear not bad, but a three-pronged fork will be -best of all: a Frenchman is no heavier than a sheaf of rye. Tomorrow -after dinner I shall take the Iberian icon of the Mother of God to the -wounded in the Catherine Hospital where we will have some water -blessed. That will help them to get well quicker. I, too, am well now: -one of my eyes was sore but now I am on the lookout with both. - - -"But military men have told me that it is impossible to fight in the -town," said Pierre, "and that the position..." - -"Well, of course! That's what we were saying," replied the first -speaker. - -"And what does he mean by 'One of my eyes was sore but now I am on -the lookout with both'?" asked Pierre. - -"The count had a sty," replied the adjutant smiling, "and was very -much upset when I told him people had come to ask what was the -matter with him. By the by, Count," he added suddenly, addressing -Pierre with a smile, "we heard that you have family troubles and -that the countess, your wife..." - -"I have heard nothing," Pierre replied unconcernedly. "But what have -you heard?" - -"Oh, well, you know people often invent things. I only say what I -heard." - -"But what did you hear?" - -"Well, they say," continued the adjutant with the same smile, -"that the countess, your wife, is preparing to go abroad. I expect -it's nonsense...." - -"Possibly," remarked Pierre, looking about him absent-mindedly. "And -who is that?" he asked, indicating a short old man in a clean blue -peasant overcoat, with a big snow-white beard and eyebrows and a ruddy -face. - -"He? That's a tradesman, that is to say, he's the restaurant keeper, -Vereshchagin. Perhaps you have heard of that affair with the -proclamation." - -"Oh, so that is Vereshchagin!" said Pierre, looking at the firm, -calm face of the old man and seeking any indication of his being a -traitor. - -"That's not he himself, that's the father of the fellow who wrote -the proclamation," said the adjutant. "The young man is in prison -and I expect it will go hard with him." - -An old gentleman wearing a star and another official, a German -wearing a cross round his neck, approached the speaker. - -"It's a complicated story, you know," said the adjutant. "That -proclamation appeared about two months ago. The count was informed -of it. He gave orders to investigate the matter. Gabriel Ivanovich -here made the inquiries. The proclamation had passed through exactly -sixty-three hands. He asked one, 'From whom did you get it?' 'From -so-and-so.' He went to the next one. 'From whom did you get it?' and -so on till he reached Vereshchagin, a half educated tradesman, you -know, 'a pet of a trader,'" said the adjutant smiling. "They asked -him, 'Who gave it you?' And the point is that we knew whom he had it -from. He could only have had it from the Postmaster. But evidently -they had come to some understanding. He replied: 'From no one; I -made it up myself.' They threatened and questioned him, but he stuck -to that: 'I made it up myself.' And so it was reported to the count, -who sent for the man. 'From whom did you get the proclamation?' 'I -wrote it myself.' Well, you know the count," said the adjutant -cheerfully, with a smile of pride, "he flared up dreadfully--and -just think of the fellow's audacity, lying, and obstinacy!" - - "And the count wanted him to say it was from Klyucharev? I -understand!" said Pierre. - -"Not at all," rejoined the adjutant in dismay. "Klyucharev had his -own sins to answer for without that and that is why he has been -banished. But the point is that the count was much annoyed. 'How could -you have written it yourself?' said he, and he took up the Hamburg -Gazette that was lying on the table. 'Here it is! You did not write it -yourself but translated it, and translated it abominably, because -you don't even know French, you fool.' And what do you think? 'No,' -said he, 'I have not read any papers, I made it up myself.' 'If that's -so, you're a traitor and I'll have you tried, and you'll be hanged! -Say from whom you had it.' 'I have seen no papers, I made it up -myself.' And that was the end of it. The count had the father fetched, -but the fellow stuck to it. He was sent for trial and condemned to -hard labor, I believe. Now the father has come to intercede for him. -But he's a good-for-nothing lad! You know that sort of tradesman's -son, a dandy and lady-killer. He attended some lectures somewhere -and imagines that the devil is no match for him. That's the sort of -fellow he is. His father keeps a cookshop here by the Stone Bridge, -and you know there was a large icon of God Almighty painted with a -scepter in one hand and an orb in the other. Well, he took that icon -home with him for a few days and what did he do? He found some -scoundrel of a painter..." - - - - - -CHAPTER XI - - -In the middle of this fresh tale Pierre was summoned to the -commander in chief. - -When he entered the private room Count Rostopchin, puckering his -face, was rubbing his forehead and eyes with his hand. A short man was -saying something, but when Pierre entered he stopped speaking and went -out. - -"Ah, how do you do, great warrior?" said Rostopchin as soon as the -short man had left the room. "We have heard of your prowess. But -that's not the point. Between ourselves, mon cher, do you belong to -the Masons?" he went on severely, as though there were something wrong -about it which he nevertheless intended to pardon. Pierre remained -silent. "I am well informed, my friend, but I am aware that there -are Masons and I hope that you are not one of those who -on pretense of saving mankind wish to ruin Russia." - -"Yes, I am a Mason," Pierre replied. - -"There, you see, mon cher! I expect you know that Messrs. -Speranski and Magnitski have been deported to their proper place. -Mr. Klyucharev has been treated in the same way, and so have others -who on the plea of building up the temple of Solomon have tried to -destroy the temple of their fatherland. You can understand that -there are reasons for this and that I could not have exiled the -Postmaster had he not been a harmful person. It has now come to my -knowledge that you lent him your carriage for his removal from town, -and that you have even accepted papers from him for safe custody. I -like you and don't wish you any harm and--as you are only half my age- -I advise you, as a father would, to cease all communication with men -of that stamp and to leave here as soon as possible." - -"But what did Klyucharev do wrong, Count?" asked Pierre. - -"That is for me to know, but not for you to ask," shouted -Rostopchin. - -"If he is accused of circulating Napoleon's proclamation it is not -proved that he did so," said Pierre without looking at Rostopchin, -"and Vereshchagin..." - -"There we are!" Rostopchin shouted at Pierre louder than before, -frowning suddenly. "Vereshchagin is a renegade and a traitor who -will be punished as he deserves," said he with the vindictive heat -with which people speak when recalling an insult. "But I did not -summon you to discuss my actions, but to give you advice--or an -order if you prefer it. I beg you to leave the town and break off -all communication with such men as Klyucharev. And I will knock the -nonsense out of anybody"--but probably realizing that he was -shouting at Bezukhov who so far was not guilty of anything, he -added, taking Pierre's hand in a friendly manner, "We are on the eve -of a public disaster and I haven't time to be polite to everybody -who has business with me. My head is sometimes in a whirl. Well, mon -cher, what are you doing personally?" - -"Why, nothing," answered Pierre without raising his eyes or changing -the thoughtful expression of his face. - -The count frowned. - -"A word of friendly advice, mon cher. Be off as soon as you can, -that's all I have to tell you. Happy he who has ears to hear. Good-by, -my dear fellow. Oh, by the by!" he shouted through the doorway after -Pierre, "is it true that the countess has fallen into the clutches -of the holy fathers of the Society of Jesus?" - -Pierre did not answer and left Rostopchin's room more sullen and -angry than he had ever before shown himself. - -When he reached home it was already getting dark. Some eight -people had come to see him that evening: the secretary of a committee, -the colonel of his battalion, his steward, his major-domo, and various -petitioners. They all had business with Pierre and wanted decisions -from him. Pierre did not understand and was not interested in any of -these questions and only answered them in order to get rid of these -people. When left alone at last he opened and read his wife's letter. - -"They, the soldiers at the battery, Prince Andrew killed... that old -man... Simplicity is submission to God. Suffering is necessary... -the meaning of all... one must harness... my wife is getting -married... One must forget and understand..." And going to his bed -he threw himself on it without undressing and immediately fell asleep. - -When he awoke next morning the major-domo came to inform him that -a special messenger, a police officer, had come from Count -Rostopchin to know whether Count Bezukhov had left or was leaving -the town. - -A dozen persons who had business with Pierre were awaiting him in -the drawing room. Pierre dressed hurriedly and, instead of going to -see them, went to the back porch and out through the gate. - -From that time till the end of the destruction of Moscow no one of -Bezukhov's household, despite all the search they made, saw Pierre -again or knew where he was. - - - - - -CHAPTER XII - - -The Rostovs remained in Moscow till the first of September, that is, -till the eve of the enemy's entry into the city. - -After Petya had joined Obolenski's regiment of Cossacks and left for -Belaya Tserkov where that regiment was forming, the countess was -seized with terror. The thought that both her sons were at the war, -had both gone from under her wing, that today or tomorrow either or -both of them might be killed like the three sons of one of her -acquaintances, struck her that summer for the first time with cruel -clearness. She tried to get Nicholas back and wished to go herself -to join Petya, or to get him an appointment somewhere in Petersburg, -but neither of these proved possible. Petya could not return unless -his regiment did so or unless he was transferred to another regiment -on active service. Nicholas was somewhere with the army and had not -sent a word since his last letter, in which he had given a detailed -account of his meeting with Princess Mary. The countess did not -sleep at night, or when she did fall asleep dreamed that she saw her -sons lying dead. After many consultations and conversations, the count -at last devised means to tranquillize her. He got Petya transferred -from Obolenski's regiment to Bezukhov's, which was in training near -Moscow. Though Petya would remain in the service, this transfer -would give the countess the consolation of seeing at least one of -her sons under her wing, and she hoped to arrange matters for her -Petya so as not to let him go again, but always get him appointed to -places where he could not possibly take part in a battle. As long as -Nicholas alone was in danger the countess imagined that she loved -her first-born more than all her other children and even reproached -herself for it; but when her youngest: the scapegrace who had been bad -at lessons, was always breaking things in the house and making himself -a nuisance to everybody, that snub-nosed Petya with his merry black -eyes and fresh rosy cheeks where soft down was just beginning to show- -when he was thrown amid those big, dreadful, cruel men who were -fighting somewhere about something and apparently finding pleasure -in it--then his mother thought she loved him more, much more, than all -her other children. The nearer the time came for Petya to return, -the more uneasy grew the countess. She began to think she would -never live to see such happiness. The presence of Sonya, of her -beloved Natasha, or even of her husband irritated her. "What do I want -with them? I want no one but Petya," she thought. - -At the end of August the Rostovs received another letter from -Nicholas. He wrote from the province of Voronezh where he had been -sent to procure remounts, but that letter did not set the countess -at ease. Knowing that one son was out of danger she became the more -anxious about Petya. - -Though by the twentieth of August nearly all the Rostovs' -acquaintances had left Moscow, and though everybody tried to -persuade the countess to get away as quickly as possible, she would -not bear of leaving before her treasure, her adored Petya, returned. -On the twenty-eighth of August he arrived. The passionate tenderness -with which his mother received him did not please the sixteen-year-old -officer. Though she concealed from him her intention of keeping him -under her wing, Petya guessed her designs, and instinctively fearing -that he might give way to emotion when with her--might "become -womanish" as he termed it to himself--he treated her coldly, avoided -her, and during his stay in Moscow attached himself exclusively to -Natasha for whom he had always had a particularly brotherly -tenderness, almost lover-like. - -Owing to the count's customary carelessness nothing was ready for -their departure by the twenty-eighth of August and the carts that were -to come from their Ryazan and Moscow estates to remove their household -belongings did not arrive till the thirtieth. - -From the twenty-eighth till the thirty-first all Moscow was in a -bustle and commotion. Every day thousands of men wounded at Borodino -were brought in by the Dorogomilov gate and taken to various parts -of Moscow, and thousands of carts conveyed the inhabitants and their -possessions out by the other gates. In spite of Rostopchin's -broadsheets, or because of them or independently of them, the -strangest and most contradictory rumors were current in the town. Some -said that no one was to be allowed to leave the city, others on the -contrary said that all the icons had been taken out of the churches -and everybody was to be ordered to leave. Some said there had been -another battle after Borodino at which the French had been routed, -while others on the contrary reported that the Russian army bad been -destroyed. Some talked about the Moscow militia which, preceded by the -clergy, would go to the Three Hills; others whispered that Augustin -had been forbidden to leave, that traitors had been seized, that the -peasants were rioting and robbing people on their way from Moscow, and -so on. But all this was only talk; in reality (though the Council of -Fili, at which it was decided to abandon Moscow, had not yet been -held) both those who went away and those who remained behind felt, -though they did not show it, that Moscow would certainly be abandoned, -and that they ought to get away as quickly as possible and save -their belongings. It was felt that everything would suddenly break -up and change, but up to the first of September nothing had done so. -As a criminal who is being led to execution knows that he must die -immediately, but yet looks about him and straightens the cap that is -awry on his head, so Moscow involuntarily continued its wonted life, -though it knew that the time of its destruction was near when the -conditions of life to which its people were accustomed to submit would -be completely upset. - -During the three days preceding the occupation of Moscow the whole -Rostov family was absorbed in various activities. The head of the -family, Count Ilya Rostov, continually drove about the city collecting -the current rumors from all sides and gave superficial and hasty -orders at home about the preparations for their departure. - -The countess watched the things being packed, was dissatisfied -with everything, was constantly in pursuit of Petya who was always -running away from her, and was jealous of Natasha with whom he spent -all his time. Sonya alone directed the practical side of matters by -getting things packed. But of late Sonya had been particularly sad and -silent. Nicholas' letter in which he mentioned Princess Mary had -elicited, in her presence, joyous comments from the countess, who -saw an intervention of Providence in this meeting of the princess -and Nicholas. - -"I was never pleased at Bolkonski's engagement to Natasha," said the -countess, "but I always wanted Nicholas to marry the princess, and had -a presentiment that it would happen. What a good thing it would be!" - -Sonya felt that this was true: that the only possibility of -retrieving the Rostovs' affairs was by Nicholas marrying a rich woman, -and that the princess was a good match. It was very bitter for her. -But despite her grief, or perhaps just because of it, she took on -herself all the difficult work of directing the storing and packing of -their things and was busy for whole days. The count and countess -turned to her when they had any orders to give. Petya and Natasha on -the contrary, far from helping their parents, were generally a -nuisance and a hindrance to everyone. Almost all day long the house -resounded with their running feet, their cries, and their -spontaneous laughter. They laughed and were gay not because there -was any reason to laugh, but because gaiety and mirth were in their -hearts and so everything that happened was a cause for gaiety and -laughter to them. Petya was in high spirits because having left home a -boy he had returned (as everybody told him) a fine young man, -because he was at home, because he had left Belaya Tserkov where there -was no hope of soon taking part in a battle and had come to Moscow -where there was to be fighting in a few days, and chiefly because -Natasha, whose lead he always followed, was in high spirits. Natasha -was gay because she had been sad too long and now nothing reminded her -of the cause of her sadness, and because she was feeling well. She was -also happy because she had someone to adore her: the adoration of -others was a lubricant the wheels of her machine needed to make them -run freely--and Petya adored her. Above all, they were gay because -there was a war near Moscow, there would be fighting at the town -gates, arms were being given out, everybody was escaping--going away -somewhere, and in general something extraordinary was happening, and -that is always exciting, especially to the young. - - - - - -CHAPTER XIII - - -On Saturday, the thirty-first of August, everything in the -Rostovs' house seemed topsy-turvy. All the doors were open, all the -furniture was being carried out or moved about, and the mirrors and -pictures had been taken down. There were trunks in the rooms, and hay, -wrapping paper, and ropes were scattered about. The peasants and house -serfs carrying out the things were treading heavily on the parquet -floors. The yard was crowded with peasant carts, some loaded high -and already corded up, others still empty. - -The voices and footsteps of the many servants and of the peasants -who had come with the carts resounded as they shouted to one another -in the yard and in the house. The count bad been out since morning. -The countess had a headache brought on by all the noise and turmoil -and was lying down in the new sitting room with a vinegar compress -on her head. Petya was not at home, he had gone to visit a friend with -whom he meant to obtain a transfer from the militia to the active -army. Sonya was in the ballroom looking after the packing of the glass -and china. Natasha was sitting on the floor of her dismantled room -with dresses, ribbons, and scarves strewn all about her, gazing -fixedly at the floor and holding in her hands the old ball dress -(already out of fashion) which she had worn at her first Petersburg -ball. - -Natasha was ashamed of doing nothing when everyone else was so busy, -and several times that morning had tried to set to work, but her heart -was not in it, and she could not and did not know how to do anything -except with all her heart and all her might. For a while she had stood -beside Sonya while the china was being packed and tried to help, but -soon gave it up and went to her room to pack her own things. At -first she found it amusing to give away dresses and ribbons to the -maids, but when that was done and what was left had still to be -packed, she found it dull. - -"Dunyasha, you pack! You will, won't you, dear?" And when Dunyasha -willingly promised to do it all for her, Natasha sat down on the -floor, took her old ball dress, and fell into a reverie quite -unrelated to what ought to have occupied her thoughts now. She was -roused from her reverie by the talk of the maids in the next room -(which was theirs) and by the sound of their hurried footsteps going -to the back porch. Natasha got up and looked out of the window. An -enormously long row of carts full of wounded men had stopped in the -street. - -The housekeeper, the old nurse, the cooks, coachmen, maids, footmen, -postilions, and scullions stood at the gate, staring at the wounded. - -Natasha, throwing a clean pocket handkerchief over her hair and -holding an end of it in each hand, went out into the street. - -The former housekeeper, old Mavra Kuzminichna, had stepped out of -the crowd by the gate, gone up to a cart with a hood constructed of -bast mats, and was speaking to a pale young officer who lay inside. -Natasha moved a few steps forward and stopped shyly, still holding her -handkerchief, and listened to what the housekeeper was saying. - -"Then you have nobody in Moscow?" she was saying. "You would be more -comfortable somewhere in a house... in ours, for instance... the -family are leaving." - -"I don't know if it would be allowed," replied the officer in a weak -voice. "Here is our commanding officer... ask him," and he pointed -to a stout major who was walking back along the street past the row of -carts. - -Natasha glanced with frightened eyes at the face of the wounded -officer and at once went to meet the major. - -"May the wounded men stay in our house?" she asked. - -The major raised his hand to his cap with a smile. - -"Which one do you want, Ma'am'selle?" said he, screwing up his -eyes and smiling. - -Natasha quietly repeated her question, and her face and whole manner -were so serious, though she was still holding the ends of her -handkerchief, that the major ceased smiling and after some reflection- -as if considering in how far the thing was possible--replied in the -affirmative. - -"Oh yes, why not? They may," he said. - -With a slight inclination of her head, Natasha stepped back -quickly to Mavra Kuzminichna, who stood talking compassionately to the -officer. - -"They may. He says they may!" whispered Natasha. - -The cart in which the officer lay was turned into the Rostovs' yard, -and dozens of carts with wounded men began at the invitation of the -townsfolk to turn into the yards and to draw up at the entrances of -the houses in Povarskaya Street. Natasha was evidently pleased to be -dealing with new people outside the ordinary routine of her life. -She and Mavra Kuzminichna tried to get as many of the wounded as -possible into their yard. - -"Your Papa must be told, though," said Mavra Kuzminichna. - -"Never mind, never mind, what does it matter? For one day we can -move into the drawing room. They can have all our half of the house." - -"There now, young lady, you do take things into your head! Even if -we put them into the wing, the men's room, or the nurse's room, we -must ask permission." - -"Well, I'll ask." - -Natasha ran into the house and went on tiptoe through the -half-open door into the sitting room, where there was a smell of -vinegar and Hoffman's drops. - -"Are you asleep, Mamma?" - -"Oh, what sleep-?" said the countess, waking up just as she was -dropping into a doze. - -"Mamma darling!" said Natasha, kneeling by her mother and bringing -her face close to her mother's, "I am sorry, forgive me, I'll never do -it again; I woke you up! Mavra Kuzminichna has sent me: they have -brought some wounded here--officers. Will you let them come? They have -nowhere to go. I knew you'd let them come!" she said quickly all in -one breath. - -"What officers? Whom have they brought? I don't understand -anything about it," said the countess. - -Natasha laughed, and the countess too smiled slightly. - -"I knew you'd give permission... so I'll tell them," and, having -kissed her mother, Natasha got up and went to the door. - -In the hall she met her father, who had returned with bad news. - -"We've stayed too long!" said the count with involuntary vexation. -"The Club is closed and the police are leaving." - -"Papa, is it all right--I've invited some of the wounded into the -house?" said Natasha. - -"Of course it is," he answered absently. "That's not the point. I -beg you not to indulge in trifles now, but to help to pack, and -tomorrow we must go, go, go!...." - -And the count gave a similar order to the major-domo and the -servants. - -At dinner Petya having returned home told them the news he had -heard. He said the people had been getting arms in the Kremlin, and -that though Rostopchin's broadsheet had said that he would sound a -call two or three days in advance, the order had certainly already -been given for everyone to go armed to the Three Hills tomorrow, and -that there would be a big battle there. - -The countess looked with timid horror at her son's eager, excited -face as he said this. She realized that if she said a word about his -not going to the battle (she knew he enjoyed the thought of the -impending engagement) he would say something about men, honor, and the -fatherland--something senseless, masculine, and obstinate which -there would be no contradicting, and her plans would be spoiled; and -so, hoping to arrange to leave before then and take Petya with her -as their protector and defender, she did not answer him, but after -dinner called the count aside and implored him with tears to take -her away quickly, that very night if possible. With a woman's -involuntary loving cunning she, who till then had not shown any alarm, -said that she would die of fright if they did not leave that very -night. Without any pretense she was now afraid of everything. - - - - - -CHAPTER XIV - - -Madame Schoss, who had been out to visit her daughter, increased the -countess' fears still more by telling what she had seen at a spirit -dealer's in Myasnitski Street. When returning by that street she had -been unable to pass because of a drunken crowd rioting in front of the -shop. She had taken a cab and driven home by a side street and the -cabman had told her that the people were breaking open the barrels -at the drink store, having received orders to do so. - -After dinner the whole Rostov household set to work with -enthusiastic haste packing their belongings and preparing for their -departure. The old count, suddenly setting to work, kept passing -from the yard to the house and back again, shouting confused -instructions to the hurrying people, and flurrying them still more. -Petya directed things in the yard. Sonya, owing to the count's -contradictory orders, lost her head and did not know what to do. The -servants ran noisily about the house and yard, shouting and disputing. -Natasha, with the ardor characteristic of all she did suddenly set -to work too. At first her intervention in the business of packing -was received skeptically. Everybody expected some prank from her and -did not wish to obey her; but she resolutely and passionately demanded -obedience, grew angry and nearly cried because they did not heed -her, and at last succeeded in making them believe her. Her first -exploit, which cost her immense effort and established her -authority, was the packing of the carpets. The count had valuable -Gobelin tapestries and Persian carpets in the house. When Natasha -set to work two cases were standing open in the ballroom, one almost -full up with crockery, the other with carpets. There was also much -china standing on the tables, and still more was being brought in from -the storeroom. A third case was needed and servants had gone to -fetch it. - -"Sonya, wait a bit--we'll pack everything into these," said Natasha. - -"You can't, Miss, we have tried to," said the butler's assistant. - -"No, wait a minute, please." - -And Natasha began rapidly taking out of the case dishes and plates -wrapped in paper. - -"The dishes must go in here among the carpets," said she. - -"Why, it's a mercy if we can get the carpets alone into three -cases," said the butler's assistant. - -"Oh, wait, please!" And Natasha began rapidly and deftly sorting out -the things. "These aren't needed," said she, putting aside some plates -of Kiev ware. "These--yes, these must go among the carpets," she said, -referring to the Saxony china dishes. - -"Don't, Natasha! Leave it alone! We'll get it all packed," urged -Sonya reproachfully. - -"What a young lady she is!" remarked the major-domo. - -But Natasha would not give in. She turned everything out and began -quickly repacking, deciding that the inferior Russian carpets and -unnecessary crockery should not be taken at all. When everything had -been taken out of the cases, they recommenced packing, and it turned -out that when the cheaper things not worth taking had nearly all -been rejected, the valuable ones really did all go into the two cases. -Only the lid of the case containing the carpets would not shut down. A -few more things might have been taken out, but Natasha insisted on -having her own way. She packed, repacked, pressed, made the butler's -assistant and Petya--whom she had drawn into the business of -packing--press on the lid, and made desperate efforts herself. - -"That's enough, Natasha," said Sonya. "I see you were right, but -just take out the top one." - -"I won't!" cried Natasha, with one hand bolding back the hair that -hung over her perspiring face, while with the other she pressed down -the carpets. "Now press, Petya! Press, Vasilich, press hard!" she -cried. - -The carpets yielded and the lid closed; Natasha, clapping her hands, -screamed with delight and tears fell from her eyes. But this only -lasted a moment. She at once set to work afresh and they now trusted -her completely. The count was not angry even when they told him that -Natasha had countermanded an order of his, and the servants now came -to her to ask whether a cart was sufficiently loaded, and whether it -might be corded up. Thanks to Natasha's directions the work now went -on expeditiously, unnecessary things were left, and the most -valuable packed as compactly as possible. - -But hard as they all worked till quite late that night, they could -not get everything packed. The countess had fallen asleep and the -count, having put off their departure till next morning, went to bed. - -Sonya and Natasha slept in the sitting room without undressing. - -That night another wounded man was driven down the Povarskaya, and -Mavra Kuzminichna, who was standing at the gate, had him brought -into the Rostovs' yard. Mavra Kuzminichna concluded that he was a very -important man. He was being conveyed in a caleche with a raised -hood, and was quite covered by an apron. On the box beside the -driver sat a venerable old attendant. A doctor and two soldiers -followed the carriage in a cart. - -"Please come in here. The masters are going away and the whole house -will be empty," said the old woman to the old attendant. - -"Well, perhaps," said he with a sigh. "We don't expect to get him -home alive! We have a house of our own in Moscow, but it's a long -way from here, and there's nobody living in it." - -"Do us the honor to come in, there's plenty of everything in the -master's house. Come in," said Mavra Kuzminichna. "Is he very ill?" -she asked. - -The attendant made a hopeless gesture. - -"We don't expect to get him home! We must ask the doctor." - -And the old servant got down from the box and went up to the cart. - -"All right!" said the doctor. - -The old servant returned to the caleche, looked into it, shook his -head disconsolately, told the driver to turn into the yard, and -stopped beside Mavra Kuzminichna. - -"O, Lord Jesus Christ!" she murmured. - -She invited them to take the wounded man into the house. - -"The masters won't object..." she said. - -But they had to avoid carrying the man upstairs, and so they took -him into the wing and put him in the room that had been Madame -Schoss'. - -This wounded man was Prince Andrew Bolkonski. - - - - - -CHAPTER XV - - -Moscow's last day had come. It was a clear bright autumn day, a -Sunday. The church bells everywhere were ringing for service, just -as usual on Sundays. Nobody seemed yet to realize what awaited the -city. - -Only two things indicated the social condition of Moscow--the -rabble, that is the poor people, and the price of commodities. An -enormous crowd of factory hands, house serfs, and peasants, with -whom some officials, seminarists, and gentry were mingled, had gone -early that morning to the Three Hills. Having waited there for -Rostopchin who did not turn up, they became convinced that Moscow -would be surrendered, and then dispersed all about the town to the -public houses and cookshops. Prices too that day indicated the state -of affairs. The price of weapons, of gold, of carts and horses, kept -rising, but the value of paper money and city articles kept falling, -so that by midday there were instances of carters removing valuable -goods, such as cloth, and receiving in payment a half of what they -carted, while peasant horses were fetching five hundred rubles each, -and furniture, mirrors, and bronzes were being given away for nothing. - -In the Rostovs' staid old-fashioned house the dissolution of -former conditions of life was but little noticeable. As to the serfs -the only indication was that three out of their huge retinue -disappeared during the night, but nothing was stolen; and as to the -value of their possessions, the thirty peasant carts that had come -in from their estates and which many people envied proved to be -extremely valuable and they were offered enormous sums of money for -them. Not only were huge sums offered for the horses and carts, but on -the previous evening and early in the morning of the first of -September, orderlies and servants sent by wounded officers came to the -Rostovs' and wounded men dragged themselves there from the Rostovs' -and from neighboring houses where they were accommodated, entreating -the servants to try to get them a lift out of Moscow. The major-domo -to whom these entreaties were addressed, though he was sorry for the -wounded, resolutely refused, saying that he dare not even mention -the matter to the count. Pity these wounded men as one might, it was -evident that if they were given one cart there would be no reason to -refuse another, or all the carts and one's own carriages as well. -Thirty carts could not save all the wounded and in the general -catastrophe one could not disregard oneself and one's own family. So -thought the major-domo on his master's behalf. - -On waking up that morning Count Ilya Rostov left his bedroom softly, -so as not to wake the countess who had fallen asleep only toward -morning, and came out to the porch in his lilac silk dressing gown. In -the yard stood the carts ready corded. The carriages were at the front -porch. The major-domo stood at the porch talking to an elderly orderly -and to a pale young officer with a bandaged arm. On seeing the count -the major-domo made a significant and stern gesture to them both to go -away. - -"Well, Vasilich, is everything ready?" asked the count, and stroking -his bald head he looked good-naturedly at the officer and the -orderly and nodded to them. (He liked to see new faces.) - -"We can harness at once, your excellency." - -"Well, that's right. As soon as the countess wakes we'll be off, God -willing! What is it, gentlemen?" he added, turning to the officer. -"Are you staying in my house?" - -The officer came nearer and suddenly his face flushed crimson. - -"Count, be so good as to allow me... for God's sake, to get into -some corner of one of your carts! I have nothing here with me.... I -shall be all right on a loaded cart..." - -Before the officer had finished speaking the orderly made the same -request on behalf of his master. - -"Oh, yes, yes, yes!" said the count hastily. "I shall be very -pleased, very pleased. Vasilich, you'll see to it. Just unload one -or two carts. Well, what of it... do what's necessary..." said the -count, muttering some indefinite order. - -But at the same moment an expression of warm gratitude on the -officer's face had already sealed the order. The count looked around -him. In the yard, at the gates, at the window of the wings, wounded -officers and their orderlies were to be seen. They were all looking at -the count and moving toward the porch. - -"Please step into the gallery, your excellency," said the -major-domo. "What are your orders about the pictures?" - -The count went into the house with him, repeating his order not to -refuse the wounded who asked for a lift. - -"Well, never mind, some of the things can be unloaded," he added -in a soft, confidential voice, as though afraid of being overheard. - -At nine o'clock the countess woke up, and Matrena Timofeevna, who -had been her lady's maid before her marriage and now performed a -sort of chief gendarme's duty for her, came to say that Madame -Schoss was much offended and the young ladies' summer dresses could -not be left behind. On inquiry, the countess learned that Madame -Schoss was offended because her trunk had been taken down from its -cart, and all the loads were being uncorded and the luggage taken -out of the carts to make room for wounded men whom the count in the -simplicity of his heart had ordered that they should take with them. -The countess sent for her husband. - -"What is this, my dear? I hear that the luggage is being unloaded." - -"You know, love, I wanted to tell you... Countess dear... an officer -came to me to ask for a few carts for the wounded. After all, ours are -things that can be bought but think what being left behind means to -them!... Really now, in our own yard--we asked them in ourselves and -there are officers among them.... You know, I think, my dear... let -them be taken... where's the hurry?" - -The count spoke timidly, as he always did when talking of money -matters. The countess was accustomed to this tone as a precursor of -news of something detrimental to the children's interests, such as the -building of a new gallery or conservatory, the inauguration of a -private theater or an orchestra. She was accustomed always to oppose -anything announced in that timid tone and considered it her duty to do -so. - -She assumed her dolefully submissive manner and said to her husband: -"Listen to me, Count, you have managed matters so that we are -getting nothing for the house, and now you wish to throw away all our- -all the children's property! You said yourself that we have a -hundred thousand rubles' worth of things in the house. I don't -consent, my dear, I don't! Do as you please! It's the government's -business to look after the wounded; they know that. Look at the -Lopukhins opposite, they cleared out everything two days ago. That's -what other people do. It's only we who are such fools. If you have -no pity on me, have some for the children." - -Flourishing his arms in despair the count left the room without -replying. - -"Papa, what are you doing that for?" asked Natasha, who had followed -him into her mother's room. - -"Nothing! What business is it of yours?" muttered the count angrily. - -"But I heard," said Natasha. "Why does Mamma object?" - -"What business is it of yours?" cried the count. - -Natasha stepped up to the window and pondered. - -"Papa! Here's Berg coming to see us," said she, looking out of the -window. - - - - - -CHAPTER XVI - - -Berg, the Rostovs' son-in-law, was already a colonel wearing the -orders of Vladimir and Anna, and he still filled the quiet and -agreeable post of assistant to the head of the staff of the -assistant commander of the first division of the Second Army. - -On the first of September he had come to Moscow from the army. - -He had nothing to do in Moscow, but he had noticed that everyone -in the army was asking for leave to visit Moscow and had something -to do there. So he considered it necessary to ask for leave of absence -for family and domestic reasons. - -Berg drove up to his father-in-law's house in his spruce little trap -with a pair of sleek roans, exactly like those of a certain prince. He -looked attentively at the carts in the yard and while going up to -the porch took out a clean pocket handkerchief and tied a knot in it. - -From the anteroom Berg ran with smooth though impatient steps into -the drawing room, where he embraced the count, kissed the hands of -Natasha and Sonya, and hastened to inquire after "Mamma's" health. - -"Health, at a time like this?" said the count. "Come, tell us the -news! Is the army retreating or will there be another battle?" - -"God Almighty alone can decide the fate of our fatherland, Papa," -said Berg. "The army is burning with a spirit of heroism and the -leaders, so to say, have now assembled in council. No one knows what -is coming. But in general I can tell you, Papa, that such a heroic -spirit, the truly antique valor of the Russian army, which they--which -it" (he corrected himself) "has shown or displayed in the battle of -the twenty-sixth--there are no words worthy to do it justice! I tell -you, Papa" (he smote himself on the breast as a general he had heard -speaking had done, but Berg did it a trifle late for he should have -struck his breast at the words "Russian army"), "I tell you frankly -that we, the commanders, far from having to urge the men on or -anything of that kind, could hardly restrain those... those... yes, -those exploits of antique valor," he went on rapidly. "General Barclay -de Tolly risked his life everywhere at the head of the troops, I can -assure you. Our corps was stationed on a hillside. You can imagine!" - -And Berg related all that he remembered of the various tales he -had heard those days. Natasha watched him with an intent gaze that -confused him, as if she were trying to find in his face the answer -to some question. - -"Altogether such heroism as was displayed by the Russian warriors -cannot be imagined or adequately praised!" said Berg, glancing round -at Natasha, and as if anxious to conciliate her, replying to her -intent look with a smile. "'Russia is not in Moscow, she lives in -the hearts of her sons!' Isn't it so, Papa?" said he. - -Just then the countess came in from the sitting room with a weary -and dissatisfied expression. Berg hurriedly jumped up, kissed her -hand, asked about her health, and, swaying his head from side to -side to express sympathy, remained standing beside her. - -"Yes, Mamma, I tell you sincerely that these are hard and sad -times for every Russian. But why are you so anxious? You have still -time to get away...." - -"I can't think what the servants are about," said the countess, -turning to her husband. "I have just been told that nothing is ready -yet. Somebody after all must see to things. One misses Mitenka at such -times. There won't be any end to it." - -The count was about to say something, but evidently restrained -himself. He got up from his chair and went to the door. - -At that moment Berg drew out his handkerchief as if to blow his nose -and, seeing the knot in it, pondered, shaking his head sadly and -significantly. - -"And I have a great favor to ask of you, Papa," said he. - -"Hm..." said the count, and stopped. - -"I was driving past Yusupov's house just now," said Berg with a -laugh, "when the steward, a man I know, ran out and asked me whether I -wouldn't buy something. I went in out of curiosity, you know, and -there is a small chiffonier and a dressing table. You know how dear -Vera wanted a chiffonier like that and how we had a dispute about it." -(At the mention of the chiffonier and dressing table Berg -involuntarily changed his tone to one of pleasure at his admirable -domestic arrangements.) "And it's such a beauty! It pulls out and -has a secret English drawer, you know! And dear Vera has long wanted -one. I wish to give her a surprise, you see. I saw so many of those -peasant carts in your yard. Please let me have one, I will pay the man -well, and..." - -The count frowned and coughed. - -"Ask the countess, I don't give orders." - -"If it's inconvenient, please don't," said Berg. "Only I so wanted -it, for dear Vera's sake." - -"Oh, go to the devil, all of you! To the devil, the devil, the -devil..." cried the old count. "My head's in a whirl!" - -And he left the room. The countess began to cry. - -"Yes, Mamma! Yes, these are very hard times!" said Berg. - -Natasha left the room with her father and, as if finding it -difficult to reach some decision, first followed him and then ran -downstairs. - -Petya was in the porch, engaged in giving out weapons to the -servants who were to leave Moscow. The loaded carts were still -standing in the yard. Two of them had been uncorded and a wounded -officer was climbing into one of them helped by an orderly. - -"Do you know what it's about?" Petya asked Natasha. - -She understood that he meant what were their parents quarreling -about. She did not answer. - -"It's because Papa wanted to give up all the carts to the -wounded," said Petya. "Vasilich told me. I consider..." - -"I consider," Natasha suddenly almost shouted, turning her angry -face to Petya, "I consider it so horrid, so abominable, so... I -don't know what. Are we despicable Germans?" - -Her throat quivered with convulsive sobs and, afraid of weakening -and letting the force of her anger run to waste, she turned and rushed -headlong up the stairs. - -Berg was sitting beside the countess consoling her with the -respectful attention of a relative. The count, pipe in hand, was -pacing up and down the room, when Natasha, her face distorted by -anger, burst in like a tempest and approached her mother with rapid -steps. - -"It's horrid! It's abominable!" she screamed. "You can't possibly -have ordered it!" - -Berg and the countess looked at her, perplexed and frightened. The -count stood still at the window and listened. - -"Mamma, it's impossible: see what is going on in the yard!" she -cried. "They will be left!..." - -"What's the matter with you? Who are 'they'? What do you want?" - -"Why, the wounded! It's impossible, Mamma. It's monstrous!... No, -Mamma darling, it's not the thing. Please forgive me, darling.... -Mamma, what does it matter what we take away? Only look what is -going on in the yard... Mamma!... It's impossible!" - -The count stood by the window and listened without turning round. -Suddenly he sniffed and put his face closer to the window. - -The countess glanced at her daughter, saw her face full of shame for -her mother, saw her agitation, and understood why her husband did -not turn to look at her now, and she glanced round quite disconcerted. - -"Oh, do as you like! Am I hindering anyone?" she said, not -surrendering at once. - -"Mamma, darling, forgive me!" - -But the countess pushed her daughter away and went up to her -husband. - -"My dear, you order what is right.... You know I don't understand -about it," said she, dropping her eyes shamefacedly. - -"The eggs... the eggs are teaching the hen," muttered the count -through tears of joy, and he embraced his wife who was glad to hide -her look of shame on his breast. - -"Papa! Mamma! May I see to it? May I?..." asked Natasha. "We will -still take all the most necessary things." - -The count nodded affirmatively, and Natasha, at the rapid pace at -which she used to run when playing at tag, ran through the ballroom to -the anteroom and downstairs into the yard. - -The servants gathered round Natasha, but could not believe the -strange order she brought them until the count himself, in his -wife's name, confirmed the order to give up all the carts to the -wounded and take the trunks to the storerooms. When they understood -that order the servants set to work at this new task with pleasure and -zeal. It no longer seemed strange to them but on the contrary it -seemed the only thing that could be done, just as a quarter of an hour -before it had not seemed strange to anyone that the wounded should -be left behind and the goods carted away but that had seemed the -only thing to do. - -The whole household, as if to atone for not having done it sooner, -set eagerly to work at the new task of placing the wounded in the -carts. The wounded dragged themselves out of their rooms and stood -with pale but happy faces round the carts. The news that carts were to -be had spread to the neighboring houses, from which wounded men -began to come into the Rostovs' yard. Many of the wounded asked them -not to unload the carts but only to let them sit on the top of the -things. But the work of unloading, once started, could not be -arrested. It seemed not to matter whether all or only half the -things were left behind. Cases full of china, bronzes, pictures, and -mirrors that had been so carefully packed the night before now lay -about the yard, and still they went on searching for and finding -possibilities of unloading this or that and letting the wounded have -another and yet another cart. - -"We can take four more men," said the steward. "They can have my -trap, or else what is to become of them?" - -"Let them have my wardrobe cart," said the countess. "Dunyasha can -go with me in the carriage." - -They unloaded the wardrobe cart and sent it to take wounded men from -a house two doors off. The whole household, servants included, was -bright and animated. Natasha was in a state of rapturous excitement -such as she had not known for a long time. - -"What could we fasten this onto?" asked the servants, trying to -fix a trunk on the narrow footboard behind a carriage. "We must keep -at least one cart." - -"What's in it?" asked Natasha. - -"The count's books." - -"Leave it, Vasilich will put it away. It's not wanted." - -The phaeton was full of people and there was a doubt as to where -Count Peter could sit. - -"On the box. You'll sit on the box, won't you, Petya?" cried -Natasha. - -Sonya too was busy all this time, but the aim of her efforts was -quite different from Natasha's. She was putting away the things that -had to be left behind and making a list of them as the countess -wished, and she tried to get as much taken away with them as possible. - - - - - -CHAPTER XVII - - -Before two o'clock in the afternoon the Rostovs' four carriages, -packed full and with the horses harnessed, stood at the front door. -One by one the carts with the wounded had moved out of the yard. - -The caleche in which Prince Andrew was being taken attracted Sonya's -attention as it passed the front porch. With the help of a maid she -was arranging a seat for the countess in the huge high coach that -stood at the entrance. - -"Whose caleche is that?" she inquired, leaning out of the carriage -window. - -"Why, didn't you know, Miss?" replied the maid. "The wounded prince: -he spent the night in our house and is going with us." - -"But who is it? What's his name?" - -"It's our intended that was--Prince Bolkonski himself! They say he -is dying," replied the maid with a sigh. - -Sonya jumped out of the coach and ran to the countess. The countess, -tired out and already dressed in shawl and bonnet for her journey, was -pacing up and down the drawing room, waiting for the household to -assemble for the usual silent prayer with closed doors before -starting. Natasha was not in the room. - -"Mamma," said Sonya, "Prince Andrew is here, mortally wounded. He is -going with us." - -The countess opened her eyes in dismay and, seizing Sonya's arm, -glanced around. - -"Natasha?" she murmured. - -At that moment this news had only one significance for both of them. -They knew their Natasha, and alarm as to what would happen if she -heard this news stifled all sympathy for the man they both liked. - -"Natasha does not know yet, but he is going with us," said Sonya. - -"You say he is dying?" - -Sonya nodded. - -The countess put her arms around Sonya and began to cry. - -"The ways of God are past finding out!" she thought, feeling that -the Almighty Hand, hitherto unseen, was becoming manifest in all -that was now taking place. - -"Well, Mamma? Everything is ready. What's the matter?" asked -Natasha, as with animated face she ran into the room. - -"Nothing," answered the countess. "If everything is ready let us -start." - -And the countess bent over her reticule to hide her agitated face. -Sonya embraced Natasha and kissed her. - -Natasha looked at her inquiringly. - -"What is it? What has happened?" - -"Nothing... No..." - -"Is it something very bad for me? What is it?" persisted Natasha -with her quick intuition. - -Sonya sighed and made no reply. The count, Petya, Madame Schoss, -Mavra Kuzminichna, and Vasilich came into the drawing room and, having -closed the doors, they all sat down and remained for some moments -silently seated without looking at one another. - -The count was the first to rise, and with a loud sigh crossed -himself before the icon. All the others did the same. Then the count -embraced Mavra Kuzminichna and Vasilich, who were to remain in Moscow, -and while they caught at his hand and kissed his shoulder he patted -their backs lightly with some vaguely affectionate and comforting -words. The countess went into the oratory and there Sonya found her on -her knees before the icons that had been left here and there hanging -on the wall. (The most precious ones, with which some family tradition -was connected, were being taken with them.) - -In the porch and in the yard the men whom Petya had armed with -swords and daggers, with trousers tucked inside their high boots and -with belts and girdles tightened, were taking leave of those remaining -behind. - -As is always the case at a departure, much had been forgotten or put -in the wrong place, and for a long time two menservants stood one on -each side of the open door and the carriage steps waiting to help -the countess in, while maids rushed with cushions and bundles from the -house to the carriages, the caleche, the phaeton, and back again. - -"They always will forget everything!" said the countess. "Don't -you know I can't sit like that?" - -And Dunyasha, with clenched teeth, without replying but with an -aggrieved look on her face, hastily got into the coach to rearrange -the seat. - -"Oh, those servants!" said the count, swaying his head. - -Efim, the old coachman, who was the only one the countess trusted to -drive her, sat perched up high on the box and did not so much as -glance round at what was going on behind him. From thirty years' -experience he knew it would be some time yet before the order, "Be -off, in God's name!" would be given him: and he knew that even when it -was said he would be stopped once or twice more while they sent back -to fetch something that had been forgotten, and even after that he -would again be stopped and the countess herself would lean out of -the window and beg him for the love of heaven to drive carefully -down the hill. He knew all this and therefore waited calmly for what -would happen, with more patience than the horses, especially the -near one, the chestnut Falcon, who was pawing the ground and -champing his bit. At last all were seated, the carriage steps were -folded and pulled up, the door was shut, somebody was sent for a -traveling case, and the countess leaned out and said what she had to -say. Then Efim deliberately doffed his hat and began crossing himself. -The postilion and all the other servants did the same. "Off, in -God's name!" said Efim, putting on his hat. "Start!" The postilion -started the horses, the off pole horse tugged at his collar, the -high springs creaked, and the body of the coach swayed. The footman -sprang onto the box of the moving coach which jolted as it passed -out of the yard onto the uneven roadway; the other vehicles jolted -in their turn, and the procession of carriages moved up the street. In -the carriages, the caleche, and the phaeton, all crossed themselves as -they passed the church opposite the house. Those who were to remain in -Moscow walked on either side of the vehicles seeing the travelers off. - -Rarely had Natasha experienced so joyful a feeling as now, sitting -in the carriage beside the countess and gazing at the slowly -receding walls of forsaken, agitated Moscow. Occasionally she leaned -out of the carriage window and looked back and then forward at the -long train of wounded in front of them. Almost at the head of the line -she could see the raised hood of Prince Andrew's caleche. She did -not know who was in it, but each time she looked at the procession her -eyes sought that caleche. She knew it was right in front. - -In Kudrino, from the Nikitski, Presnya, and Podnovinsk Streets -came several other trains of vehicles similar to the Rostovs', and -as they passed along the Sadovaya Street the carriages and carts -formed two rows abreast. - -As they were going round the Sukharev water tower Natasha, who was -inquisitively and alertly scrutinizing the people driving or walking -past, suddenly cried out in joyful surprise: - -"Dear me! Mamma, Sonya, look, it's he!" - -"Who? Who?" - -"Look! Yes, on my word, it's Bezukhov!" said Natasha, putting her -head out of the carriage and staring at a tall, stout man in a -coachman's long coat, who from his manner of walking and moving was -evidently a gentleman in disguise, and who was passing under the -arch of the Sukharev tower accompanied by a small, sallow-faced, -beardless old man in a frieze coat. - -"Yes, it really is Bezukhov in a coachman's coat, with a -queer-looking old boy. Really," said Natasha, "look, look!" - -"No, it's not he. How can you talk such nonsense?" - -"Mamma," screamed Natasha, "I'll stake my head it's he! I assure -you! Stop, stop!" she cried to the coachman. - -But the coachman could not stop, for from the Meshchanski Street -came more carts and carriages, and the Rostovs were being shouted at -to move on and not block the way. - -In fact, however, though now much farther off than before, the -Rostovs all saw Pierre--or someone extraordinarily like him--in a -coachman's coat, going down the street with head bent and a serious -face beside a small, beardless old man who looked like a footman. That -old man noticed a face thrust out of the carriage window gazing at -them, and respectfully touching Pierre's elbow said something to him -and pointed to the carriage. Pierre, evidently engrossed in thought, -could not at first understand him. At length when he had understood -and looked in the direction the old man indicated, he recognized -Natasha, and following his first impulse stepped instantly and rapidly -toward the coach. But having taken a dozen steps he seemed to remember -something and stopped. - -Natasha's face, leaning out of the window, beamed with quizzical -kindliness. - -"Peter Kirilovich, come here! We have recognized you! This is -wonderful!" she cried, holding out her hand to him. "What are you -doing? Why are you like this?" - -Pierre took her outstretched hand and kissed it awkwardly as he -walked along beside her while the coach still moved on. - -"What is the matter, Count?" asked the countess in a surprised and -commiserating tone. - -"What? What? Why? Don't ask me," said Pierre, and looked round at -Natasha whose radiant, happy expression--of which he was conscious -without looking at her--filled him with enchantment. - -"Are you remaining in Moscow, then?" - -Pierre hesitated. - -"In Moscow?" he said in a questioning tone. "Yes, in Moscow. -Goodby!" - -"Ah, if only I were a man? I'd certainly stay with you. How -splendid!" said Natasha. "Mamma, if you'll let me, I'll stay!" - -Pierre glanced absently at Natasha and was about to say something, -but the countess interrupted him. - -"You were at the battle, we heard." - -"Yes, I was," Pierre answered. "There will be another battle -tomorrow..." he began, but Natasha interrupted him. - -"But what is the matter with you, Count? You are not like -yourself...." - -"Oh, don't ask me, don't ask me! I don't know myself. Tomorrow... -But no! Good-by, good-by!" he muttered. "It's an awful time!" and -dropping behind the carriage he stepped onto the pavement. - -Natasha continued to lean out of the window for a long time, beaming -at him with her kindly, slightly quizzical, happy smile. - - - - - -CHAPTER XVIII - - -For the last two days, ever since leaving home, Pierre had been -living in the empty house of his deceased benefactor, Bazdeev. This is -how it happened. - -When he woke up on the morning after his return to Moscow and his -interview with Count Rostopchin, he could not for some time make out -where he was and what was expected of him. When he was informed that -among others awaiting him in his reception room there was a -Frenchman who had brought a letter from his wife, the Countess Helene, -he felt suddenly overcome by that sense of confusion and -hopelessness to which he was apt to succumb. He felt that everything -was now at an end, all was in confusion and crumbling to pieces, -that nobody was right or wrong, the future held nothing, and there was -no escape from this position. Smiling unnaturally and muttering to -himself, he first sat down on the sofa in an attitude of despair, then -rose, went to the door of the reception room and peeped through the -crack, returned flourishing his arms, and took up a book. His -major-domo came in a second time to say that the Frenchman who had -brought the letter from the countess was very anxious to see him if -only for a minute, and that someone from Bazdeev's widow had called to -ask Pierre to take charge of her husband's books, as she herself was -leaving for the country. - -"Oh, yes, in a minute; wait... or no! No, of course... go and say -I will come directly," Pierre replied to the major-domo. - -But as soon as the man had left the room Pierre took up his hat -which was lying on the table and went out of his study by the other -door. There was no one in the passage. He went along the whole -length of this passage to the stairs and, frowning and rubbing his -forehead with both hands, went down as far as the first landing. The -hall porter was standing at the front door. From the landing where -Pierre stood there was a second staircase leading to the back -entrance. He went down that staircase and out into the yard. No one -had seen him. But there were some carriages waiting, and as soon as -Pierre stepped out of the gate the coachmen and the yard porter -noticed him and raised their caps to him. When he felt he was being -looked at he behaved like an ostrich which hides its head in a bush in -order not to be seen: he hung his head and quickening his pace went -down the street. - -Of all the affairs awaiting Pierre that day the sorting of Joseph -Bazdeev's books and papers appeared to him the most necessary. - - -He hired the first cab he met and told the driver to go to the -Patriarch's Ponds, where the widow Bazdeev's house was. - -Continually turning round to look at the rows of loaded carts that -were making their way from all sides out of Moscow, and balancing -his bulky body so as not to slip out of the ramshackle old vehicle, -Pierre, experiencing the joyful feeling of a boy escaping from school, -began to talk to his driver. - -The man told him that arms were being distributed today at the -Kremlin and that tomorrow everyone would be sent out beyond the -Three Hills gates and a great battle would be fought there. - -Having reached the Patriarch's Ponds Pierre found the Bazdeevs' -house, where he had not been for a long time past. He went up to the -gate. Gerasim, that sallow beardless old man Pierre had seen at -Torzhok five years before with Joseph Bazdeev, came out in answer to -his knock. - -"At home?" asked Pierre. - -"Owing to the present state of things Sophia Danilovna has gone to -the Torzhok estate with the children, your excellency." - -"I will come in all the same, I have to look through the books," -said Pierre. - -"Be so good as to step in. Makar Alexeevich, the brother of my -late master--may the kingdom of heaven be his--has remained here, -but he is in a weak state as you know," said the old servant. - -Pierre knew that Makar Alexeevich was Joseph Bazdeev's half-insane -brother and a hard drinker. - -"Yes, yes, I know. Let us go in..." said Pierre and entered the -house. - -A tall, bald-headed old man with a red nose, wearing a dressing gown -and with galoshes on his bare feet, stood in the anteroom. On seeing -Pierre he muttered something angrily and went away along the passage. - -"He was a very clever man but has now grown quite feeble, as your -honor sees," said Gerasim. "Will you step into the study?" Pierre -nodded. "As it was sealed up so it has remained, but Sophia -Danilovna gave orders that if anyone should come from you they were to -have the books." - -Pierre went into that gloomy study which he had entered with such -trepidation in his benefactor's lifetime. The room, dusty and -untouched since the death of Joseph Bazdeev was now even gloomier. - -Gerasim opened one of the shutters and left the room on tiptoe. -Pierre went round the study, approached the cupboard in which the -manuscripts were kept, and took out what had once been one of the most -important, the holy of holies of the order. This was the authentic -Scotch Acts with Bazdeev's notes and explanations. He sat down at -the dusty writing table, and, having laid the manuscripts before -him, opened them out, closed them, finally pushed them away, and -resting his head on his hand sank into meditation. - -Gerasim looked cautiously into the study several times and saw -Pierre always sitting in the same attitude. - -More than two hours passed and Gerasim took the liberty of making -a slight noise at the door to attract his attention, but Pierre did -not hear him. - -"Is the cabman to be discharged, your honor?" - -"Oh yes!" said Pierre, rousing himself and rising hurriedly. "Look -here," he added, taking Gerasim by a button of his coat and looking -down at the old man with moist, shining, and ecstatic eyes, "I say, do -you know that there is going to be a battle tomorrow?" - -"We heard so," replied the man. - -"I beg you not to tell anyone who I am, and to do what I ask you." - -"Yes, your excellency," replied Gerasim. "Will you have something to -eat?" - -"No, but I want something else. I want peasant clothes and a -pistol," said Pierre, unexpectedly blushing. - -"Yes, your excellency," said Gerasim after thinking for a moment. - -All the rest of that day Pierre spent alone in his benefactor's -study, and Gerasim heard him pacing restlessly from one corner to -another and talking to himself. And he spent the night on a bed made -up for him there. - -Gerasim, being a servant who in his time had seen many strange -things, accepted Pierre's taking up his residence in the house without -surprise, and seemed pleased to have someone to wait on. That same -evening--without even asking himself what they were wanted for--he -procured a coachman's coat and cap for Pierre, and promised to get him -the pistol next day. Makar Alexeevich came twice that evening -shuffling along in his galoshes as far as the door and stopped and -looked ingratiatingly at Pierre. But as soon as Pierre turned toward -him he wrapped his dressing gown around him with a shamefaced and -angry look and hurried away. It was when Pierre (wearing the -coachman's coat which Gerasim had procured for him and had disinfected -by steam) was on his way with the old man to buy the pistol at the -Sukharev market that he met the Rostovs. - - - - - -CHAPTER XIX - - -Kutuzov's order to retreat through Moscow to the Ryazan road was -issued at night on the first of September. - -The first troops started at once, and during the night they -marched slowly and steadily without hurry. At daybreak, however, those -nearing the town at the Dorogomilov bridge saw ahead of them masses of -soldiers crowding and hurrying across the bridge, ascending on the -opposite side and blocking the streets and alleys, while endless -masses of troops were bearing down on them from behind, and an -unreasoning hurry and alarm overcame them. They all rushed forward -to the bridge, onto it, and to the fords and the boats. Kutuzov -himself had driven round by side streets to the other side of Moscow. - -By ten o'clock in the morning of the second of September, only the -rear guard remained in the Dorogomilov suburb, where they had ample -room. The main army was on the other side of Moscow or beyond it. - -At that very time, at ten in the morning of the second of September, -Napoleon was standing among his troops on the Poklonny Hill looking at -the panorama spread out before him. From the twenty-sixth of August to -the second of September, that is from the battle of Borodino to the -entry of the French into Moscow, during the whole of that agitating, -memorable week, there had been the extraordinary autumn weather that -always comes as a surprise, when the sun hangs low and gives more heat -than in spring, when everything shines so brightly in the rare clear -atmosphere that the eyes smart, when the lungs are strengthened and -refreshed by inhaling the aromatic autumn air, when even the nights -are warm, and when in those dark warm nights, golden stars startle and -delight us continually by falling from the sky. - -At ten in the morning of the second of September this weather -still held. - -The brightness of the morning was magical. Moscow seen from the -Poklonny Hill lay spaciously spread out with her river, her gardens, -and her churches, and she seemed to be living her usual life, her -cupolas glittering like stars in the sunlight. - -The view of the strange city with its peculiar architecture, such as -he had never seen before, filled Napoleon with the rather envious -and uneasy curiosity men feel when they see an alien form of life that -has no knowledge of them. This city was evidently living with the full -force of its own life. By the indefinite signs which, even at a -distance, distinguish a living body from a dead one, Napoleon from the -Poklonny Hill perceived the throb of life in the town and felt, as -it were, the breathing of that great and beautiful body. - -Every Russian looking at Moscow feels her to be a mother; every -foreigner who sees her, even if ignorant of her significance as the -mother city, must feel her feminine character, and Napoleon felt it. - -"Cette ville asiatique aux innombrables eglises, Moscou la sainte. -La voila done enfin, cette fameuse ville! Il etait temps,"* said he, -and dismounting he ordered a plan of Moscow to be spread out before -him, and summoned Lelorgne d'Ideville, the interpreter. - - -*"That Asiatic city of the innumerable churches, holy Moscow! Here -it is then at last, that famous city. It was high time." - - -"A town captured by the enemy is like a maid who has lost her -honor," thought he (he had said so to Tuchkov at Smolensk). From -that point of view he gazed at the Oriental beauty he had not seen -before. It seemed strange to him that his long-felt wish, which had -seemed unattainable, had at last been realized. In the clear morning -light he gazed now at the city and now at the plan, considering its -details, and the assurance of possessing it agitated and awed him. - -"But could it be otherwise?" he thought. "Here is this capital at my -feet. Where is Alexander now, and of what is he thinking? A strange, -beautiful, and majestic city; and a strange and majestic moment! In -what light must I appear to them!" thought he, thinking of his troops. -"Here she is, the reward for all those fainthearted men," he -reflected, glancing at those near him and at the troops who were -approaching and forming up. "One word from me, one movement of my -hand, and that ancient capital of the Tsars would perish. But my -clemency is always ready to descend upon the vanquished. I must be -magnanimous and truly great. But no, it can't be true that I am in -Moscow," he suddenly thought. "Yet here she is lying at my feet, -with her golden domes and crosses scintillating and twinkling in the -sunshine. But I shall spare her. On the ancient monuments of barbarism -and despotism I will inscribe great words of justice and mercy.... -It is just this which Alexander will feel most painfully, I know him." -(It seemed to Napoleon that the chief import of what was taking -place lay in the personal struggle between himself and Alexander.) -"From the height of the Kremlin--yes, there is the Kremlin, yes--I -will give them just laws; I will teach them the meaning of true -civilization, I will make generations of boyars remember their -conqueror with love. I will tell the deputation that I did not, and do -not, desire war, that I have waged war only against the false policy -of their court; that I love and respect Alexander and that in Moscow I -will accept terms of peace worthy of myself and of my people. I do not -wish to utilize the fortunes of war to humiliate an honored monarch. -'Boyars,' I will say to them, 'I do not desire war, I desire the peace -and welfare of all my subjects.' However, I know their presence will -inspire me, and I shall speak to them as I always do: clearly, -impressively, and majestically. But can it be true that I am in -Moscow? Yes, there she lies." - -"Qu'on m'amene les boyars,"* said he to his suite. - - -*"Bring the boyars to me." - - -A general with a brilliant suite galloped off at once to fetch the -boyars. - -Two hours passed. Napoleon had lunched and was again standing in the -same place on the Poklonny Hill awaiting the deputation. His speech to -the boyars had already taken definite shape in his imagination. That -speech was full of dignity and greatness as Napoleon understood it. - -He was himself carried away by the tone of magnanimity he intended -to adopt toward Moscow. In his imagination he appointed days for -assemblies at the palace of the Tsars, at which Russian notables and -his own would mingle. He mentally appointed a governor, one who -would win the hearts of the people. Having learned that there were -many charitable institutions in Moscow he mentally decided that he -would shower favors on them all. He thought that, as in Africa he -had to put on a burnoose and sit in a mosque, so in Moscow he must -be beneficent like the Tsars. And in order finally to touch the hearts -of the Russians--and being like all Frenchmen unable to imagine -anything sentimental without a reference to ma chere, ma tendre, ma -pauvre mere* --he decided that he would place an inscription on all -these establishments in large letters: "This establishment is -dedicated to my dear mother." Or no, it should be simply: Maison de ma -Mere,*[2] he concluded. "But am I really in Moscow? Yes, here it -lies before me, but why is the deputation from the city so long in -appearing?" he wondered. - - -*"My dear, my tender, my poor mother." - -*[2] "House of my Mother." - - -Meanwhile an agitated consultation was being carried on in -whispers among his generals and marshals at the rear of his suite. -Those sent to fetch the deputation had returned with the news that -Moscow was empty, that everyone had left it. The faces of those who -were not conferring together were pale and perturbed. They were not -alarmed by the fact that Moscow had been abandoned by its -inhabitants (grave as that fact seemed), but by the question how to -tell the Emperor--without putting him in the terrible position of -appearing ridiculous--that he had been awaiting the boyars so long -in vain: that there were drunken mobs left in Moscow but no one -else. Some said that a deputation of some sort must be scraped -together, others disputed that opinion and maintained that the Emperor -should first be carefully and skillfully prepared, and then told the -truth. - -"He will have to be told, all the same," said some gentlemen of -the suite. "But, gentlemen..." - -The position was the more awkward because the Emperor, meditating -upon his magnanimous plans, was pacing patiently up and down before -the outspread map, occasionally glancing along the road to Moscow from -under his lifted hand with a bright and proud smile. - -"But it's impossible..." declared the gentlemen of the suite, -shrugging their shoulders but not venturing to utter the implied word- -le ridicule... - -At last the Emperor, tired of futile expectation, his actor's -instinct suggesting to him that the sublime moment having been too -long drawn out was beginning to lose its sublimity, gave a sign with -his hand. A single report of a signaling gun followed, and the troops, -who were already spread out on different sides of Moscow, moved into -the city through Tver, Kaluga, and Dorogomilov gates. Faster and -faster, vying with one another, they moved at the double or at a trot, -vanishing amid the clouds of dust they raised and making the air -ring with a deafening roar of mingling shouts. - -Drawn on by the movement of his troops Napoleon rode with them as -far as the Dorogomilov gate, but there again stopped and, -dismounting from his horse, paced for a long time by the -Kammer-Kollezski rampart, awaiting the deputation. - - - - - -CHAPTER XX - -Meanwhile Moscow was empty. There were still people in it, perhaps a -fiftieth part of its former inhabitants had remained, but it was -empty. It was empty in the sense that a dying queenless hive is empty. - -In a queenless hive no life is left though to a superficial glance -it seems as much alive as other hives. - -The bees circle round a queenless hive in the hot beams of the -midday sun as gaily as around the living hives; from a distance it -smells of honey like the others, and bees fly in and out in the same -way. But one has only to observe that hive to realize that there is no -longer any life in it. The bees do not fly in the same way, the -smell and the sound that meet the beekeeper are not the same. To the -beekeeper's tap on the wall of the sick hive, instead of the former -instant unanimous humming of tens of thousands of bees with their -abdomens threateningly compressed, and producing by the rapid -vibration of their wings an aerial living sound, the only reply is a -disconnected buzzing from different parts of the deserted hive. From -the alighting board, instead of the former spirituous fragrant smell -of honey and venom, and the warm whiffs of crowded life, comes an odor -of emptiness and decay mingling with the smell of honey. There are -no longer sentinels sounding the alarm with their abdomens raised, and -ready to die in defense of the hive. There is no longer the measured -quiet sound of throbbing activity, like the sound of boiling water, -but diverse discordant sounds of disorder. In and out of the hive long -black robber bees smeared with honey fly timidly and shiftily. They do -not sting, but crawl away from danger. Formerly only bees laden with -honey flew into the hive, and they flew out empty; now they fly out -laden. The beekeeper opens the lower part of the hive and peers in. -Instead of black, glossy bees--tamed by toil, clinging to one -another's legs and drawing out the wax, with a ceaseless hum of labor- -that used to hang in long clusters down to the floor of the hive, -drowsy shriveled bees crawl about separately in various directions -on the floor and walls of the hive. Instead of a neatly glued floor, -swept by the bees with the fanning of their wings, there is a floor -littered with bits of wax, excrement, dying bees scarcely moving their -legs, and dead ones that have not been cleared away. - -The beekeeper opens the upper part of the hive and examines the -super. Instead of serried rows of bees sealing up every gap in the -combs and keeping the brood warm, he sees the skillful complex -structures of the combs, but no longer in their former state of -purity. All is neglected and foul. Black robber bees are swiftly and -stealthily prowling about the combs, and the short home bees, -shriveled and listless as if they were old, creep slowly about without -trying to hinder the robbers, having lost all motive and all sense -of life. Drones, bumblebees, wasps, and butterflies knock awkwardly -against the walls of the hive in their flight. Here and there among -the cells containing dead brood and honey an angry buzzing can -sometimes be heard. Here and there a couple of bees, by force of habit -and custom cleaning out the brood cells, with efforts beyond their -strength laboriously drag away a dead bee or bumblebee without knowing -why they do it. In another corner two old bees are languidly fighting, -or cleaning themselves, or feeding one another, without themselves -knowing whether they do it with friendly or hostile intent. In a third -place a crowd of bees, crushing one another, attack some victim and -fight and smother it, and the victim, enfeebled or killed, drops -from above slowly and lightly as a feather, among the heap of corpses. -The keeper opens the two center partitions to examine the brood cells. -In place of the former close dark circles formed by thousands of -bees sitting back to back and guarding the high mystery of generation, -he sees hundreds of dull, listless, and sleepy shells of bees. They -have almost all died unawares, sitting in the sanctuary they had -guarded and which is now no more. They reek of decay and death. Only a -few of them still move, rise, and feebly fly to settle on the -enemy's hand, lacking the spirit to die stinging him; the rest are -dead and fall as lightly as fish scales. The beekeeper closes the -hive, chalks a mark on it, and when he has time tears out its contents -and burns it clean. - -So in the same way Moscow was empty when Napoleon, weary, uneasy, -and morose, paced up and down in front of the Kammer-Kollezski -rampart, awaiting what to his mind was a necessary, if but formal, -observance of the proprieties--a deputation. - -In various corners of Moscow there still remained a few people -aimlessly moving about, following their old habits and hardly aware of -what they were doing. - -When with due circumspection Napoleon was informed that Moscow was -empty, he looked angrily at his informant, turned away, and silently -continued to walk to and fro. - -"My carriage!" he said. - -He took his seat beside the aide-de-camp on duty and drove into -the suburb. "Moscow deserted!" he said to himself. "What an incredible -event!" - -He did not drive into the town, but put up at an inn in the -Dorogomilov suburb. - -The coup de theatre had not come off. - - - - - -CHAPTER XXI - - -The Russian troops were passing through Moscow from two o'clock at -night till two in the afternoon and bore away with them the wounded -and the last of the inhabitants who were leaving. - -The greatest crush during the movement of the troops took place at -the Stone, Moskva, and Yauza bridges. - -While the troops, dividing into two parts when passing around the -Kremlin, were thronging the Moskva and the Stone bridges, a great many -soldiers, taking advantage of the stoppage and congestion, turned back -from the bridges and slipped stealthily and silently past the church -of Vasili the Beatified and under the Borovitski gate, back up the -hill to the Red Square where some instinct told them they could easily -take things not belonging to them. Crowds of the kind seen at cheap -sales filled all the passages and alleys of the Bazaar. But there were -no dealers with voices of ingratiating affability inviting customers -to enter; there were no hawkers, nor the usual motley crowd of -female purchasers--but only soldiers, in uniforms and overcoats though -without muskets, entering the Bazaar empty-handed and silently -making their way out through its passages with bundles. Tradesmen -and their assistants (of whom there were but few) moved about among -the soldiers quite bewildered. They unlocked their shops and locked -them up again, and themselves carried goods away with the help their -assistants. On the square in front of the Bazaar were drummers beating -the muster call. But the roll of the drums did not make the looting -soldiers run in the direction of the drum as formerly, but made -them, on the contrary, run farther away. Among the soldiers in the -shops and passages some men were to be seen in gray coats, with -closely shaven heads. Two officers, one with a scarf over his -uniform and mounted on a lean, dark-gray horse, the other in an -overcoat and on foot, stood at the corner of Ilyinka Street, -talking. A third officer galloped up to them. - -"The general orders them all to be driven out at once, without fail. -This is outrageous! Half the men have dispersed." - -"Where are you off to?... Where?..." he shouted to three infantrymen -without muskets who, holding up the skirts of their overcoats, were -slipping past him into the Bazaar passage. "Stop, you rascals!" - -"But how are you going to stop them?" replied another officer. -"There is no getting them together. The army should push on before the -rest bolt, that's all!" - -"How can one push on? They are stuck there, wedged on the bridge, -and don't move. Shouldn't we put a cordon round to prevent the rest -from running away?" - -"Come, go in there and drive them out!" shouted the senior officer. - -The officer in the scarf dismounted, called up a drummer, and went -with him into the arcade. Some soldiers started running away in a -group. A shopkeeper with red pimples on his cheeks near the nose, -and a calm, persistent, calculating expression on his plump face, -hurriedly and ostentatiously approached the officer, swinging his -arms. - -"Your honor!" said he. "Be so good as to protect us! We won't grudge -trifles, you are welcome to anything--we shall be delighted! -Pray!... I'll fetch a piece of cloth at once for such an honorable -gentleman, or even two pieces with pleasure. For we feel how it is; -but what's all this--sheer robbery! If you please, could not guards be -placed if only to let us close the shop...." - -Several shopkeepers crowded round the officer. - -"Eh, what twaddle!" said one of them, a thin, stern-looking man. -"When one's head is gone one doesn't weep for one's hair! Take what -any of you like!" And flourishing his arm energetically he turned -sideways to the officer. - -"It's all very well for you, Ivan Sidorych, to talk," said the first -tradesman angrily. "Please step inside, your honor!" - -"Talk indeed!" cried the thin one. "In my three shops here I have -a hundred thousand rubles' worth of goods. Can they be saved when -the army has gone? Eh, what people! 'Against God's might our hands -can't fight.'" - -"Come inside, your honor!" repeated the tradesman, bowing. - -The officer stood perplexed and his face showed indecision. - -"It's not my business!" he exclaimed, and strode on quickly down one -of the passages. - -From one open shop came the sound of blows and vituperation, and -just as the officer came up to it a man in a gray coat with a shaven -head was flung out violently. - -This man, bent double, rushed past the tradesman and the officer. -The officer pounced on the soldiers who were in the shops, but at that -moment fearful screams reached them from the huge crowd on the -Moskva bridge and the officer ran out into the square. - -"What is it? What is it?" he asked, but his comrade was already -galloping off past Vasili the Beatified in the direction from which -the screams came. - -The officer mounted his horse and rode after him. When he reached -the bridge he saw two unlimbered guns, the infantry crossing the -bridge, several overturned carts, and frightened and laughing faces -among the troops. Beside the cannon a cart was standing to which two -horses were harnessed. Four borzois with collars were pressing close -to the wheels. The cart was loaded high, and at the very top, beside a -child's chair with its legs in the air, sat a peasant woman uttering -piercing and desperate shrieks. He was told by his fellow officers -that the screams of the crowd and the shrieks of the woman were due to -the fact that General Ermolov, coming up to the crowd and learning -that soldiers were dispersing among the shops while crowds of -civilians blocked the bridge, had ordered two guns to be unlimbered -and made a show of firing at the bridge. The crowd, crushing one -another, upsetting carts, and shouting and squeezing desperately, -had cleared off the bridge and the troops were now moving forward. - - - - - -CHAPTER XXII - - -Meanwhile, the city itself was deserted. There was hardly anyone -in the streets. The gates and shops were all closed, only here and -there round the taverns solitary shouts or drunken songs could be -heard. Nobody drove through the streets and footsteps were rarely -heard. The Povarskaya was quite still and deserted. The huge courtyard -of the Rostovs' house was littered with wisps of hay and with dung -from the horses, and not a soul was to be seen there. In the great -drawing room of the house, which had been left with all it -contained, were two people. They were the yard porter Ignat, and the -page boy Mishka, Vasilich's grandson who had stayed in Moscow with his -grandfather. Mishka had opened the clavichord and was strumming on -it with one finger. The yard porter, his arms akimbo, stood smiling -with satisfaction before the large mirror. - -"Isn't it fine, eh, Uncle Ignat?" said the boy, suddenly beginning -to strike the keyboard with both hands. - -"Only fancy!" answered Ignat, surprised at the broadening grin on -his face in the mirror. - -"Impudence! Impudence!" they heard behind them the voice of Mavra -Kuzminichna who had entered silently. "How he's grinning, the fat mug! -Is that what you're here for? Nothing's cleared away down there and -Vasilich is worn out. Just you wait a bit!" - -Ignat left off smiling, adjusted his belt, and went out of the -room with meekly downcast eyes. - -"Aunt, I did it gently," said the boy. - -"I'll give you something gently, you monkey you!" cried Mavra -Kuzminichna, raising her arm threateningly. "Go and get the samovar to -boil for your grandfather." - -Mavra Kuzminichna flicked the dust off the clavichord and closed it, -and with a deep sigh left the drawing room and locked its main door. - -Going out into the yard she paused to consider where she should go -next--to drink tea in the servants' wing with Vasilich, or into the -storeroom to put away what still lay about. - -She heard the sound of quick footsteps in the quiet street. -Someone stopped at the gate, and the latch rattled as someone tried to -open it. Mavra Kuzminichna went to the gate. - -"Who do you want?" - -"The count--Count Ilya Andreevich Rostov." - -"And who are you?" - -"An officer, I have to see him," came the reply in a pleasant, -well-bred Russian voice. - -Mavra Kuzminichna opened the gate and an officer of eighteen, with -the round face of a Rostov, entered the yard. - -"They have gone away, sir. Went away yesterday at vespertime," -said Mavra Kuzminichna cordially. - -The young officer standing in the gateway, as if hesitating -whether to enter or not, clicked his tongue. - -"Ah, how annoying!" he muttered. "I should have come yesterday.... -Ah, what a pity." - -Meanwhile, Mavra Kuzminichna was attentively and sympathetically -examining the familiar Rostov features of the young man's face, his -tattered coat and trodden-down boots. - -"What did you want to see the count for?" she asked. - -"Oh well... it can't be helped!" said he in a tone of vexation and -placed his hand on the gate as if to leave. - -He again paused in indecision. - -"You see," he suddenly said, "I am a kinsman of the count's and he -has been very kind to me. As you see" (he glanced with an amused air -and good-natured smile at his coat and boots) "my things are worn -out and I have no money, so I was going to ask the count..." - -Mavra Kuzminichna did not let him finish. - -"Just wait a minute, sir. One little moment," said she. - -And as soon as the officer let go of the gate handle she turned and, -hurrying away on her old legs, went through the back yard to the -servants' quarters. - -While Mavra Kuzminichna was running to her room the officer walked -about the yard gazing at his worn-out boots with lowered head and a -faint smile on his lips. "What a pity I've missed Uncle! What a nice -old woman! Where has she run off to? And how am I to find the -nearest way to overtake my regiment, which must by now be getting near -the Rogozhski gate?" thought he. Just then Mavra Kuzminichna -appeared from behind the corner of the house with a frightened yet -resolute look, carrying a rolled-up check kerchief in her hand. -While still a few steps from the officer she unfolded the kerchief and -took out of it a white twenty-five-ruble assignat and hastily handed -it to him. - -"If his excellency had been at home, as a kinsman he would of -course... but as it is..." - -Mavra Kuzminichna grew abashed and confused. The officer did not -decline, but took the note quietly and thanked her. - -"If the count had been at home..." Mavra Kuzminichna went on -apologetically. "Christ be with you, sir! May God preserve you!" -said she, bowing as she saw him out. - -Swaying his head and smiling as if amused at himself, the officer -ran almost at a trot through the deserted streets toward the Yauza -bridge to overtake his regiment. - -But Mavra Kuzminichna stood at the closed gate for some time with -moist eyes, pensively swaying her head and feeling an unexpected -flow of motherly tenderness and pity for the unknown young officer. - - - - - -CHAPTER XXIII - - -From an unfinished house on the Varvarka, the ground floor of -which was a dramshop, came drunken shouts and songs. On benches -round the tables in a dirty little room sat some ten factory hands. -Tipsy and perspiring, with dim eyes and wide-open mouths, they were -all laboriously singing some song or other. They were singing -discordantly, arduously, and with great effort, evidently not -because they wished to sing, but because they wanted to show they were -drunk and on a spree. One, a tall, fair-haired lad in a clean blue -coat, was standing over the others. His face with its fine straight -nose would have been handsome had it not been for his thin, -compressed, twitching lips and dull, gloomy, fixed eyes. Evidently -possessed by some idea, he stood over those who were singing, and -solemnly and jerkily flourished above their heads his white arm with -the sleeve turned up to the elbow, trying unnaturally to spread out -his dirty fingers. The sleeve of his coat kept slipping down and he -always carefully rolled it up again with his left hand, as if it -were most important that the sinewy white arm he was flourishing -should be bare. In the midst of the song cries were heard, and -fighting and blows in the passage and porch. The tall lad waved his -arm. - -"Stop it!" he exclaimed peremptorily. "There's a fight, lads!" -And, still rolling up his sleeve, he went out to the porch. - -The factory hands followed him. These men, who under the -leadership of the tall lad were drinking in the dramshop that morning, -had brought the publican some skins from the factory and for this -had had drink served them. The blacksmiths from a neighboring -smithy, hearing the sounds of revelry in the tavern and supposing it -to have been broken into, wished to force their way in too and a fight -in the porch had resulted. - -The publican was fighting one of the smiths at the door, and when -the workmen came out the smith, wrenching himself free from the tavern -keeper, fell face downward on the pavement. - -Another smith tried to enter the doorway, pressing against the -publican with his chest. - -The lad with the turned-up sleeve gave the smith a blow in the -face and cried wildly: "They're fighting us, lads!" - -At that moment the first smith got up and, scratching his bruised -face to make it bleed, shouted in a tearful voice: "Police! Murder!... -They've killed a man, lads!" - -"Oh, gracious me, a man beaten to death--killed!..." screamed a -woman coming out of a gate close by. - -A crowd gathered round the bloodstained smith. - -"Haven't you robbed people enough--taking their last shirts?" said a -voice addressing the publican. "What have you killed a man for, you -thief?" - -The tall lad, standing in the porch, turned his bleared eyes from -the publican to the smith and back again as if considering whom he -ought to fight now. - -"Murderer!" he shouted suddenly to the publican. "Bind him, lads!" - -"I daresay you would like to bind me!" shouted the publican, pushing -away the men advancing on him, and snatching his cap from his head -he flung it on the ground. - -As if this action had some mysterious and menacing significance, the -workmen surrounding the publican paused in indecision. - -"I know the law very well, mates! I'll take the matter to the -captain of police. You think I won't get to him? Robbery is not -permitted to anybody now a days!" shouted the publican, picking up his -cap. - -"Come along then! Come along then!" the publican and the tall -young fellow repeated one after the other, and they moved up the -street together. - -The bloodstained smith went beside them. The factory hands and -others followed behind, talking and shouting. - -At the corner of the Moroseyka, opposite a large house with closed -shutters and bearing a bootmaker's signboard, stood a score of thin, -worn-out, gloomy-faced bootmakers, wearing overalls and long -tattered coats. - -"He should pay folks off properly," a thin workingman, with frowning -brows and a straggly beard, was saying. - -"But he's sucked our blood and now he thinks he's quit of us. He's -been misleading us all the week and now that he's brought us to this -pass he's made off." - -On seeing the crowd and the bloodstained man the workman ceased -speaking, and with eager curiosity all the bootmakers joined the -moving crowd. - -"Where are all the folks going?" - -"Why, to the police, of course!" - -"I say, is it true that we have been beaten?" "And what did you -think? Look what folks are saying." - -Questions and answers were heard. The publican, taking advantage -of the increased crowd, dropped behind and returned to his tavern. - -The tall youth, not noticing the disappearance of his foe, waved his -bare arm and went on talking incessantly, attracting general attention -to himself. It was around him that the people chiefly crowded, -expecting answers from him to the questions that occupied all their -minds. - -"He must keep order, keep the law, that's what the government is -there for. Am I not right, good Christians?" said the tall youth, with -a scarcely perceptible smile. "He thinks there's no government! How -can one do without government? Or else there would be plenty who'd rob -us." - -"Why talk nonsense?" rejoined voices in the crowd. "Will they give -up Moscow like this? They told you that for fun, and you believed -it! Aren't there plenty of troops on the march? Let him in, indeed! -That's what the government is for. You'd better listen to what -people are saying," said some of the mob pointing to the tall youth. - -By the wall of China-Town a smaller group of people were gathered -round a man in a frieze coat who held a paper in his hand. - -"An ukase, they are reading an ukase! Reading an ukase!" cried -voices in the crowd, and the people rushed toward the reader. - -The man in the frieze coat was reading the broadsheet of August 31 -When the crowd collected round him he seemed confused, but at the -demand of the tall lad who had pushed his way up to him, he began in a -rather tremulous voice to read the sheet from the beginning. - -"Early tomorrow I shall go to his Serene Highness," he read -("Sirin Highness," said the tall fellow with a triumphant smile on his -lips and a frown on his brow), "to consult with him to act, and to aid -the army to exterminate these scoundrels. We too will take part..." -the reader went on, and then paused ("Do you see," shouted the youth -victoriously, "he's going to clear up the whole affair for -you...."), "in destroying them, and will send these visitors to the -devil. I will come back to dinner, and we'll set to work. We will -do, completely do, and undo these scoundrels." - -The last words were read out in the midst of complete silence. The -tall lad hung his head gloomily. It was evident that no one had -understood the last part. In particular, the words "I will come back -to dinner," evidently displeased both reader and audience. The -people's minds were tuned to a high pitch and this was too simple -and needlessly comprehensible--it was what any one of them might -have said and therefore was what an ukase emanating from the highest -authority should not say. - -They all stood despondent and silent. The tall youth moved his -lips and swayed from side to side. - -"We should ask him... that's he himself?"... "Yes, ask him -indeed!... Why not? He'll explain"... voices in the rear of the -crowd were suddenly heard saying, and the general attention turned -to the police superintendent's trap which drove into the square -attended by two mounted dragoons. - -The superintendent of police, who had that morning by Count -Rostopchin's orders to burn the barges and had in connection with that -matter acquired a large sum of money which was at that moment in his -pocket, on seeing a crowd bearing down upon him told his coachman to -stop. - -"What people are these?" he shouted to the men, who were moving -singly and timidly in the direction of his trap. - -"What people are these?" he shouted again, receiving no answer. - -"Your honor..." replied the shopman in the frieze coat, "your honor, -in accord with the proclamation of his highest excellency the count, -they desire to serve, not sparing their lives, and it is not any -kind of riot, but as his highest excellence said..." - -"The count has not left, he is here, and an order will be issued -concerning you," said the superintendent of police. "Go on!" he -ordered his coachman. - -The crowd halted, pressing around those who had heard what the -superintendent had said, and looking at the departing trap. - -The superintendent of police turned round at that moment with a -scared look, said something to his coachman, and his horses -increased their speed. - -"It's a fraud, lads! Lead the way to him, himself!" shouted the tall -youth. "Don't let him go, lads! Let him answer us! Keep him!" -shouted different people and the people dashed in pursuit of the trap. - -Following the superintendent of police and talking loudly the -crowd went in the direction of the Lubyanka Street. - -"There now, the gentry and merchants have gone away and left us to -perish. Do they think we're dogs?" voices in the crowd were heard -saying more and more frequently. - - - - - -CHAPTER XXIV - - -On the evening of the first of September, after his interview with -Kutuzov, Count Rostopchin had returned to Moscow mortified and -offended because he had not been invited to attend the council of war, -and because Kutuzov had paid no attention to his offer to take part in -the defense of the city; amazed also at the novel outlook revealed -to him at the camp, which treated the tranquillity of the capital -and its patriotic fervor as not merely secondary but quite -irrelevant and unimportant matters. Distressed, offended, and -surprised by all this, Rostopchin had returned to Moscow. After supper -he lay down on a sofa without undressing, and was awakened soon -after midnight by a courier bringing him a letter from Kutuzov. This -letter requested the count to send police officers to guide the troops -through the town, as the army was retreating to the Ryazan road beyond -Moscow. This was not news to Rostopchin. He had known that Moscow -would be abandoned not merely since his interview the previous day -with Kutuzov on the Poklonny Hill but ever since the battle of -Borodino, for all the generals who came to Moscow after that battle -had said unanimously that it was impossible to fight another battle, -and since then the government property had been removed every night, -and half the inhabitants had left the city with Rostopchin's own -permission. Yet all the same this information astonished and irritated -the count, coming as it did in the form of a simple note with an order -from Kutuzov, and received at night, breaking in on his beauty sleep. - -When later on in his memoirs Count Rostopchin explained his -actions at this time, he repeatedly says that he was then actuated -by two important considerations: to maintain tranquillity in Moscow -and expedite the departure of the inhabitants. If one accepts this -twofold aim all Rostopchin's actions appear irreproachable. "Why -were the holy relics, the arms, ammunition, gunpowder, and stores of -corn not removed? Why were thousands of inhabitants deceived into -believing that Moscow would not be given up--and thereby ruined?" -"To presence the tranquillity of the city," explains Count Rostopchin. -"Why were bundles of useless papers from the government offices, and -Leppich's balloon and other articles removed?" "To leave the town -empty," explains Count Rostopchin. One need only admit that public -tranquillity is in danger and any action finds a justification. - -All the horrors of the reign of terror were based only on solicitude -for public tranquillity. - -On what, then, was Count Rostopchin's fear for the tranquillity of -Moscow based in 1812? What reason was there for assuming any -probability of an uprising in the city? The inhabitants were leaving -it and the retreating troops were filling it. Why should that cause -the masses to riot? - -Neither in Moscow nor anywhere in Russia did anything resembling -an insurrection ever occur when the enemy entered a town. More than -ten thousand people were still in Moscow on the first and second of -September, and except for a mob in the governor's courtyard, assembled -there at his bidding, nothing happened. It is obvious that there would -have been even less reason to expect a disturbance among the people if -after the battle of Borodino, when the surrender of Moscow became -certain or at least probable, Rostopchin instead of exciting the -people by distributing arms and broadsheets had taken steps to -remove all the holy relics, the gunpowder, munitions, and money, and -had told the population plainly that the town would be abandoned. - -Rostopchin, though he had patriotic sentiments, was a sanguine and -impulsive man who had always moved in the highest administrative -circles and had no understanding at all of the people he supposed -himself to be guiding. Ever since the enemy's entry into Smolensk he -had in imagination been playing the role of director of the popular -feeling of "the heart of Russia." Not only did it seem to him (as to -all administrators) that he controlled the external actions of -Moscow's inhabitants, but he also thought he controlled their mental -attitude by means of his broadsheets and posters, written in a -coarse tone which the people despise in their own class and do not -understand from those in authority. Rostopchin was so pleased with the -fine role of leader of popular feeling, and had grown so used to it, -that the necessity of relinquishing that role and abandoning Moscow -without any heroic display took him unawares and he suddenly felt -the ground slip away from under his feet, so that he positively did -not know what to do. Though he knew it was coming, he did not till the -last moment wholeheartedly believe that Moscow would be abandoned, and -did not prepare for it. The inhabitants left against his wishes. If -the government offices were removed, this was only done on the -demand of officials to whom the count yielded reluctantly. He was -absorbed in the role he had created for himself. As is often the -case with those gifted with an ardent imagination, though he had -long known that Moscow would be abandoned he knew it only with his -intellect, he did not believe it in his heart and did not adapt -himself mentally to this new position of affairs. - -All his painstaking and energetic activity (in how far it was useful -and had any effect on the people is another question) had been -simply directed toward arousing in the masses his own feeling of -patriotic hatred of the French. - -But when events assumed their true historical character, when -expressing hatred for the French in words proved insufficient, when it -was not even possible to express that hatred by fighting a battle, -when self-confidence was of no avail in relation to the one question -before Moscow, when the whole population streamed out of Moscow as one -man, abandoning their belongings and proving by that negative action -all the depth of their national feeling, then the role chosen by -Rostopchin suddenly appeared senseless. He unexpectedly felt himself -ridiculous, weak, and alone, with no ground to stand on. - -When, awakened from his sleep, he received that cold, peremptory -note from Kutuzov, he felt the more irritated the more he felt himself -to blame. All that he had been specially put in charge of, the state -property which he should have removed, was still in Moscow and it -was no longer possible to take the whole of it away. - -"Who is to blame for it? Who has let things come to such a pass?" he -ruminated. "Not I, of course. I had everything ready. I had Moscow -firmly in hand. And this is what they have let it come to! Villains! -Traitors!" he thought, without clearly defining who the villains and -traitors were, but feeling it necessary to hate those traitors whoever -they might be who were to blame for the false and ridiculous -position in which he found himself. - -All that night Count Rostopchin issued orders, for which people came -to him from all parts of Moscow. Those about him had never seen the -count so morose and irritable. - -"Your excellency, the Director of the Registrar's Department has -sent for instructions... From the Consistory, from the Senate, from -the University, from the Foundling Hospital, the Suffragan has sent... -asking for information.... What are your orders about the Fire -Brigade? From the governor of the prison... from the superintendent of -the lunatic asylum..." All night long such announcements were -continually being received by the count. - -To all these inquiries he gave brief and angry replies indicating -that orders from him were not now needed, that the whole affair, -carefully prepared by him, had now been ruined by somebody, and that -that somebody would have to bear the whole responsibility for all that -might happen. - -"Oh, tell that blockhead," he said in reply to the question from the -Registrar's Department, "that he should remain to guard his documents. -Now why are you asking silly questions about the Fire Brigade? They -have horses, let them be off to Vladimir, and not leave them to the -French." - -"Your excellency, the superintendent of the lunatic asylum has come: -what are your commands?" - -"My commands? Let them go away, that's all.... And let the -lunatics out into the town. When lunatics command our armies God -evidently means these other madmen to be free." - -In reply to an inquiry about the convicts in the prison, Count -Rostopchin shouted angrily at the governor: - -"Do you expect me to give you two battalions--which we have not got- -for a convoy? Release them, that's all about it!" - -"Your excellency, there are some political prisoners, Meshkov, -Vereshchagin..." - -"Vereshchagin! Hasn't he been hanged yet?" shouted Rostopchin. -"Bring him to me!" - - - - - -CHAPTER XXV - - -Toward nine o'clock in the morning, when the troops were already -moving through Moscow, nobody came to the count any more for -instructions. Those who were able to get away were going of their -own accord, those who remained behind decided for themselves what they -must do. - -The count ordered his carriage that he might drive to Sokolniki, and -sat in his study with folded hands, morose, sallow, and taciturn. - -In quiet and untroubled times it seems to every administrator that -it is only by his efforts that the whole population under his rule -is kept going, and in this consciousness of being indispensable -every administrator finds the chief reward of his labor and efforts. -While the sea of history remains calm the ruler-administrator in his -frail bark, holding on with a boat hook to the ship of the people -and himself moving, naturally imagines that his efforts move the -ship he is holding on to. But as soon as a storm arises and the sea -begins to heave and the ship to move, such a delusion is no longer -possible. The ship moves independently with its own enormous motion, -the boat hook no longer reaches the moving vessel, and suddenly the -administrator, instead of appearing a ruler and a source of power, -becomes an insignificant, useless, feeble man. - -Rostopchin felt this, and it was this which exasperated him. - -The superintendent of police, whom the crowd had stopped, went in to -see him at the same time as an adjutant who informed the count that -the horses were harnessed. They were both pale, and the superintendent -of police, after reporting that he had executed the instructions he -had received, informed the count that an immense crowd had collected -in the courtyard and wished to see him. - -Without saying a word Rostopchin rose and walked hastily to his -light, luxurious drawing room, went to the balcony door, took hold -of the handle, let it go again, and went to the window from which he -had a better view of the whole crowd. The tall lad was standing in -front, flourishing his arm and saying something with a stern look. The -blood stained smith stood beside him with a gloomy face. A drone of -voices was audible through the closed window. - -"Is my carriage ready?" asked Rostopchin, stepping back from the -window. - -"It is, your excellency," replied the adjutant. - -Rostopchin went again to the balcony door. - -"But what do they want?" he asked the superintendent of police. - -"Your excellency, they say they have got ready, according to your -orders, to go against the French, and they shouted something about -treachery. But it is a turbulent crowd, your excellency--I hardly -managed to get away from it. Your excellency, I venture to suggest..." - -"You may go. I don't need you to tell me what to do!" exclaimed -Rostopchin angrily. - -He stood by the balcony door looking at the crowd. - -"This is what they have done with Russia! This is what they have -done with me!" thought he, full of an irrepressible fury that welled -up within him against the someone to whom what was happening might -be attributed. As often happens with passionate people, he was -mastered by anger but was still seeking an object on which to vent it. -"Here is that mob, the dregs of the people," he thought as he gazed at -the crowd: "this rabble they have roused by their folly! They want a -victim," he thought as he looked at the tall lad flourishing his -arm. And this thought occurred to him just because he himself -desired a victim, something on which to vent his rage. - -"Is the carriage ready?" he asked again. - -"Yes, your excellency. What are your orders about Vereshchagin? He -is waiting at the porch," said the adjutant. - -"Ah!" exclaimed Rostopchin, as if struck by an unexpected -recollection. - -And rapidly opening the door he went resolutely out onto the -balcony. The talking instantly ceased, hats and caps were doffed, -and all eyes were raised to the count. - -"Good morning, lads!" said the count briskly and loudly. "Thank -you for coming. I'll come out to you in a moment, but we must first -settle with the villain. We must punish the villain who has caused the -ruin of Moscow. Wait for me!" - -And the count stepped as briskly back into the room and slammed -the door behind him. - -A murmur of approbation and satisfaction ran through the crowd. -"He'll settle with all the villains, you'll see! And you said the -French... He'll show you what law is!" the mob were saying as if -reproving one another for their lack of confidence. - -A few minutes later an officer came hurriedly out of the front door, -gave an order, and the dragoons formed up in line. The crowd moved -eagerly from the balcony toward the porch. Rostopchin, coming out -there with quick angry steps, looked hastily around as if seeking -someone. - -"Where is he?" he inquired. And as he spoke he saw a young man -coming round the corner of the house between two dragoons. He had a -long thin neck, and his head, that had been half shaved, was again -covered by short hair. This young man was dressed in a threadbare blue -cloth coat lined with fox fur, that had once been smart, and dirty -hempen convict trousers, over which were pulled his thin, dirty, -trodden-down boots. On his thin, weak legs were heavy chains which -hampered his irresolute movements. - -"Ah!" said Rostopchin, hurriedly turning away his eyes from the -young man in the fur-lined coat and pointing to the bottom step of the -porch. "Put him there." - -The young man in his clattering chains stepped clumsily to the -spot indicated, holding away with one finger the coat collar which -chafed his neck, turned his long neck twice this way and that, sighed, -and submissively folded before him his thin hands, unused to work. - -For several seconds while the young man was taking his place on -the step the silence continued. Only among the back rows of the -people, who were all pressing toward the one spot, could sighs, -groans, and the shuffling of feet be heard. - -While waiting for the young man to take his place on the step -Rostopchin stood frowning and rubbing his face with his hand. - -"Lads!" said he, with a metallic ring in his voice. "This man, -Vereshchagin, is the scoundrel by whose doing Moscow is perishing." - -The young man in the fur-lined coat, stooping a little, stood in a -submissive attitude, his fingers clasped before him. His emaciated -young face, disfigured by the half-shaven head, hung down -hopelessly. At the count's first words he raised it slowly and -looked up at him as if wishing to say something or at least to meet -his eye. But Rostopchin did not look at him. A vein in the young man's -long thin neck swelled like a cord and went blue behind the ear, and -suddenly his face flushed. - -All eyes were fixed on him. He looked at the crowd, and rendered -more hopeful by the expression he read on the faces there, he smiled -sadly and timidly, and lowering his head shifted his feet on the step. - -"He has betrayed his Tsar and his country, he had gone over to -Bonaparte. He alone of all the Russians has disgraced the Russian -name, he has caused Moscow to perish," said Rostopchin in a sharp, -even voice, but suddenly he glanced down at Vereshchagin who continued -to stand in the same submissive attitude. As if inflamed by the sight, -he raised his arm and addressed the people, almost shouting: - -"Deal with him as you think fit! I hand him over to you." - -The crowd remained silent and only pressed closer and closer to -one another. To keep one another back, to breathe in that stifling -atmosphere, to be unable to stir, and to await something unknown, -uncomprehended, and terrible, was becoming unbearable. Those -standing in front, who had seen and heard what had taken place -before them, all stood with wide open eyes and mouths, straining -with all their strength, and held back the crowd that was pushing -behind them. - -"Beat him!... Let the traitor perish and not disgrace the Russian -name!" shouted Rostopchin. "Cut him down. I command it." - -Hearing not so much the words as the angry tone of Rostopchin's -voice, the crowd moaned and heaved forward, but again paused. - -"Count!" exclaimed the timid yet theatrical voice of Vereshchagin in -the midst of the momentary silence that ensued, "Count! One God is -above us both...." He lifted his head and again the thick vein in -his thin neck filled with blood and the color rapidly came and went in -his face. - -He did not finish what he wished to say. - -"Cut him down! I command it..." shouted Rostopchin, suddenly growing -pale like Vereshchagin. - -"Draw sabers!" cried the dragoon officer, drawing his own. - -Another still stronger wave flowed through the crowd and reaching -the front ranks carried it swaying to the very steps of the porch. The -tall youth, with a stony look on his face, and rigid and uplifted arm, -stood beside Vereshchagin. - -"Saber him!" the dragoon officer almost whispered. - -And one of the soldiers, his face all at once distorted with fury, -struck Vereshchagin on the head with the blunt side of his saber. - -"Ah!" cried Vereshchagin in meek surprise, looking round with a -frightened glance as if not understanding why this was done to him. -A similar moan of surprise and horror ran through the crowd. "O Lord!" -exclaimed a sorrowful voice. - -But after the exclamation of surprise that had escaped from -Vereshchagin he uttered a plaintive cry of pain, and that cry was -fatal. The barrier of human feeling, strained to the utmost, that -had held the crowd in check suddenly broke. The crime had begun and -must now be completed. The plaintive moan of reproach was drowned by -the threatening and angry roar of the crowd. Like the seventh and last -wave that shatters a ship, that last irresistible wave burst from -the rear and reached the front ranks, carrying them off their feet and -engulfing them all. The dragoon was about to repeat his blow. -Vereshchagin with a cry of horror, covering his head with his hands, -rushed toward the crowd. The tall youth, against whom he stumbled, -seized his thin neck with his hands and, yelling wildly, fell with him -under the feet of the pressing, struggling crowd. - -Some beat and tore at Vereshchagin, others at the tall youth. And -the screams of those that were being trampled on and of those who -tried to rescue the tall lad only increased the fury of the crowd. -It was a long time before the dragoons could extricate the bleeding -youth, beaten almost to death. And for a long time, despite the -feverish haste with which the mob tried to end the work that had -been begun, those who were hitting, throttling, and tearing at -Vereshchagin were unable to kill him, for the crowd pressed from all -sides, swaying as one mass with them in the center and rendering it -impossible for them either to kill him or let him go. - -"Hit him with an ax, eh!... Crushed?... Traitor, he sold -Christ.... Still alive... tenacious... serves him right! Torture -serves a thief right. Use the hatchet!... What--still alive?" - -Only when the victim ceased to struggle and his cries changed to a -long-drawn, measured death rattle did the crowd around his -prostrate, bleeding corpse begin rapidly to change places. Each one -came up, glanced at what had been done, and with horror, reproach, and -astonishment pushed back again. - -"O Lord! The people are like wild beasts! How could he be alive?" -voices in the crowd could be heard saying. "Quite a young fellow -too... must have been a merchant's son. What men!... and they say he's -not the right one.... How not the right one?... O Lord! And there's -another has been beaten too--they say he's nearly done for.... Oh, the -people... Aren't they afraid of sinning?..." said the same mob now, -looking with pained distress at the dead body with its long, thin, -half-severed neck and its livid face stained with blood and dust. - -A painstaking police officer, considering the presence of a corpse -in his excellency's courtyard unseemly, told the dragoons to take it -away. Two dragoons took it by its distorted legs and dragged it -along the ground. The gory, dust-stained, half-shaven head with its -long neck trailed twisting along the ground. The crowd shrank back -from it. - -At the moment when Vereshchagin fell and the crowd closed in with -savage yells and swayed about him, Rostopchin suddenly turned pale -and, instead of going to the back entrance where his carriage -awaited him, went with hurried steps and bent head, not knowing -where and why, along the passage leading to the rooms on the ground -floor. The count's face was white and he could not control the -feverish twitching of his lower jaw. - - -"This way, your excellency... Where are you going?... This way, -please..." said a trembling, frightened voice behind him. - -Count Rostopchin was unable to reply and, turning obediently, went -in the direction indicated. At the back entrance stood his caleche. -The distant roar of the yelling crowd was audible even there. He -hastily took his seat and told the coachman to drive him to his -country house in Sokolniki. - -When they reached the Myasnitski Street and could no longer hear the -shouts of the mob, the count began to repent. He remembered with -dissatisfaction the agitation and fear he had betrayed before his -subordinates. "The mob is terrible--disgusting," he said to himself in -French. "They are like wolves whom nothing but flesh can appease." -"Count! One God is above us both!"--Vereshchagin's words suddenly -recurred to him, and a disagreeable shiver ran down his back. But this -was only a momentary feeling and Count Rostopchin smiled -disdainfully at himself. "I had other duties," thought he. "The people -had to be appeased. Many other victims have perished and are perishing -for the public good"--and he began thinking of his social duties to -his family and to the city entrusted to him, and of himself--not -himself as Theodore Vasilyevich Rostopchin (he fancied that Theodore -Vasilyevich Rostopchin was sacrificing himself for the public good) -but himself as governor, the representative of authority and of the -Tsar. "Had I been simply Theodore Vasilyevich my course of action -would have been quite different, but it was my duty to safeguard my -life and dignity as commander in chief." - -Lightly swaying on the flexible springs of his carriage and no -longer hearing the terrible sounds of the crowd, Rostopchin grew -physically calm and, as always happens, as soon as he became -physically tranquil his mind devised reasons why he should be mentally -tranquil too. The thought which tranquillized Rostopchin was not a new -one. Since the world began and men have killed one another no one -has ever committed such a crime against his fellow man without -comforting himself with this same idea. This idea is le bien public, -the hypothetical welfare of other people. - -To a man not swayed by passion that welfare is never certain, but he -who commits such a crime always knows just where that welfare lies. -And Rostopchin now knew it. - -Not only did his reason not reproach him for what he had done, but -he even found cause for self-satisfaction in having so successfully -contrived to avail himself of a convenient opportunity to punish a -criminal and at the same time pacify the mob. - -"Vereshchagin was tried and condemned to death," thought -Rostopchin (though the Senate had only condemned Vereshchagin to -hard labor), "he was a traitor and a spy. I could not let him go -unpunished and so I have killed two birds with one stone: to appease -the mob I gave them a victim and at the same time punished a -miscreant." - -Having reached his country house and begun to give orders about -domestic arrangements, the count grew quite tranquil. - -Half an hour later he was driving with his fast horses across the -Sokolniki field, no longer thinking of what had occurred but -considering what was to come. He was driving to the Yauza bridge where -he had heard that Kutuzov was. Count Rostopchin was mentally preparing -the angry and stinging reproaches he meant to address to Kutuzov for -his deception. He would make that foxy old courtier feel that the -responsibility for all the calamities that would follow the -abandonment of the city and the ruin of Russia (as Rostopchin regarded -it) would fall upon his doting old head. Planning beforehand what he -would say to Kutuzov, Rostopchin turned angrily in his caleche and -gazed sternly from side to side. - -The Sokolniki field was deserted. Only at the end of it, in front of -the almshouse and the lunatic asylum, could be seen some people in -white and others like them walking singly across the field shouting -and gesticulating. - -One of these was running to cross the path of Count Rostopchin's -carriage, and the count himself, his coachman, and his dragoons looked -with vague horror and curiosity at these released lunatics and -especially at the one running toward them. - -Swaying from side to side on his long, thin legs in his fluttering -dressing gown, this lunatic was running impetuously, his gaze fixed on -Rostopchin, shouting something in a hoarse voice and making signs to -him to stop. The lunatic's solemn, gloomy face was thin and yellow, -with its beard growing in uneven tufts. His black, agate pupils with -saffron-yellow whites moved restlessly near the lower eyelids. - -"Stop! Pull up, I tell you!" he cried in a piercing voice, and again -shouted something breathlessly with emphatic intonations and gestures. - -Coming abreast of the caleche he ran beside it. - -"Thrice have they slain me, thrice have I risen from the dead. -They stoned me, crucified me... I shall rise... shall rise... shall -rise. They have torn my body. The kingdom of God will be overthrown... -Thrice will I overthrow it and thrice re-establish it!" he cried, -raising his voice higher and higher. - -Count Rostopchin suddenly grew pale as he had done when the crowd -closed in on Vereshchagin. He turned away. "Go fas... faster!" he -cried in a trembling voice to his coachman. The caleche flew over -the ground as fast as the horses could draw it, but for a long time -Count Rostopchin still heard the insane despairing screams growing -fainter in the distance, while his eyes saw nothing but the -astonished, frightened, bloodstained face of "the traitor" in the -fur-lined coat. - -Recent as that mental picture was, Rostopchin already felt that it -had cut deep into his heart and drawn blood. Even now he felt -clearly that the gory trace of that recollection would not pass with -time, but that the terrible memory would, on the contrary, dwell in -his heart ever more cruelly and painfully to the end of his life. He -seemed still to hear the sound of his own words: "Cut him down! I -command it...." - -"Why did I utter those words? It was by some accident I said -them.... I need not have said them," he thought. "And then nothing -would have happened." He saw the frightened and then infuriated face -of the dragoon who dealt the blow, the look of silent, timid -reproach that boy in the fur-lined coat had turned upon him. "But I -did not do it for my own sake. I was bound to act that way.... The -mob, the traitor... the public welfare," thought he. - -Troops were still crowding at the Yauza bridge. It was hot. Kutuzov, -dejected and frowning, sat on a bench by the bridge toying with his -whip in the sand when a caleche dashed up noisily. A man in a -general's uniform with plumes in his hat went up to Kutuzov and said -something in French. It was Count Rostopchin. He told Kutuzov that -he had come because Moscow, the capital, was no more and only the army -remained. - -"Things would have been different if your Serene Highness had not -told me that you would not abandon Moscow without another battle; -all this would not have happened," he said. - -Kutuzov looked at Rostopchin as if, not grasping what was said to -him, he was trying to read something peculiar written at that moment -on the face of the man addressing him. Rostopchin grew confused and -became silent. Kutuzov slightly shook his head and not taking his -penetrating gaze from Rostopchin's face muttered softly: - -"No! I shall not give up Moscow without a battle!" - -Whether Kutuzov was thinking of something entirely different when he -spoke those words, or uttered them purposely, knowing them to be -meaningless, at any rate Rostopchin made no reply and hastily left -him. And strange to say, the Governor of Moscow, the proud Count -Rostopchin, took up a Cossack whip and went to the bridge where he -began with shouts to drive on the carts that blocked the way. - - - - - -CHAPTER XXVI - - -Toward four o'clock in the afternoon Murat's troops were entering -Moscow. In front rode a detachment of Wurttemberg hussars and behind -them rode the King of Naples himself accompanied by a numerous suite. - -About the middle of the Arbat Street, near the Church of the -Miraculous Icon of St. Nicholas, Murat halted to await news from the -advanced detachment as to the condition in which they had found the -citadel, le Kremlin. - -Around Murat gathered a group of those who had remained in Moscow. -They all stared in timid bewilderment at the strange, long-haired -commander dressed up in feathers and gold. - -"Is that their Tsar himself? He's not bad!" low voices could be -heard saying. - -An interpreter rode up to the group. - -"Take off your cap... your caps!" These words went from one to -another in the crowd. The interpreter addressed an old porter and -asked if it was far to the Kremlin. The porter, listening in -perplexity to the unfamiliar Polish accent and not realizing that -the interpreter was speaking Russian, did not understand what was -being said to him and slipped behind the others. - -Murat approached the interpreter and told him to ask where the -Russian army was. One of the Russians understood what was asked and -several voices at once began answering the interpreter. A French -officer, returning from the advanced detachment, rode up to Murat -and reported that the gates of the citadel had been barricaded and -that there was probably an ambuscade there. - -"Good!" said Murat and, turning to one of the gentlemen in his -suite, ordered four light guns to be moved forward to fire at the -gates. - -The guns emerged at a trot from the column following Murat and -advanced up the Arbat. When they reached the end of the Vozdvizhenka -Street they halted and drew in the Square. Several French officers -superintended the placing of the guns and looked at the Kremlin -through field glasses. - -The bells in the Kremlin were ringing for vespers, and this sound -troubled the French. They imagined it to be a call to arms. A few -infantrymen ran to the Kutafyev Gate. Beams and wooden screens had -been put there, and two musket shots rang out from under the gate as -soon as an officer and men began to run toward it. A general who was -standing by the guns shouted some words of command to the officer, and -the latter ran back again with his men. - -The sound of three more shots came from the gate. - -One shot struck a French soldier's foot, and from behind the screens -came the strange sound of a few voices shouting. Instantly as at a -word of command the expression of cheerful serenity on the faces of -the French general, officers, and men changed to one of determined -concentrated readiness for strife and suffering. To all of them from -the marshal to the least soldier, that place was not the Vozdvizhenka, -Mokhavaya, or Kutafyev Street, nor the Troitsa Gate (places familiar -in Moscow), but a new battlefield which would probably prove -sanguinary. And all made ready for that battle. The cries from the -gates ceased. The guns were advanced, the artillerymen blew the ash -off their linstocks, and an officer gave the word "Fire!" This was -followed by two whistling sounds of canister shot, one after -another. The shot rattled against the stone of the gate and upon the -wooden beams and screens, and two wavering clouds of smoke rose over -the Square. - -A few instants after the echo of the reports resounding over the -stone-built Kremlin had died away the French heard a strange sound -above their head. Thousands of crows rose above the walls and -circled in the air, cawing and noisily flapping their wings. -Together with that sound came a solitary human cry from the gateway -and amid the smoke appeared the figure of a bareheaded man in a -peasant's coat. He grasped a musket and took aim at the French. -"Fire!" repeated the officer once more, and the reports of a musket -and of two cannon shots were heard simultaneously. The gate again -hidden by smoke. - -Nothing more stirred behind the screens and the French infantry -soldiers and officers advanced to the gate. In the gateway lay three -wounded and four dead. Two men in peasant coats ran away at the foot -of the wall, toward the Znamenka. - -"Clear that away!" said the officer, pointing to the beams and the -corpses, and the French soldiers, after dispatching the wounded, threw -the corpses over the parapet. - -Who these men were nobody knew. "Clear that away!" was all that -was said of them, and they were thrown over the parapet and removed -later on that they might not stink. Thiers alone dedicates a few -eloquent lines to their memory: "These wretches had occupied the -sacred citadel, having supplied themselves with guns from the arsenal, -and fired" (the wretches) "at the French. Some of them were sabered -and the Kremlin was purged of their presence." - -Murat was informed that the way had been cleared. The French entered -the gates and began pitching their camp in the Senate Square. Out of -the windows of the Senate House the soldiers threw chairs into the -Square for fuel and kindled fires there. - -Other detachments passed through the Kremlin and encamped along -the Moroseyka, the Lubyanka, and Pokrovka Streets. Others quartered -themselves along the Vozdvizhenka, the Nikolski, and the Tverskoy -Streets. No masters of the houses being found anywhere, the French -were not billeted on the inhabitants as is usual in towns but lived in -it as in a camp. - -Though tattered, hungry, worn out, and reduced to a third of their -original number, the French entered Moscow in good marching order. -It was a weary and famished, but still a fighting and menacing army. -But it remained an army only until its soldiers had dispersed into -their different lodgings. As soon as the men of the various -regiments began to disperse among the wealthy and deserted houses, the -army was lost forever and there came into being something nondescript, -neither citizens nor soldiers but what are known as marauders. When -five weeks later these same men left Moscow, they no longer formed -an army. They were a mob of marauders, each carrying a quantity of -articles which seemed to him valuable or useful. The aim of each man -when he left Moscow was no longer, as it had been, to conquer, but -merely to keep what he had acquired. Like a monkey which puts its -paw into the narrow neck of a jug, and having seized a handful of nuts -will not open its fist for fear of losing what it holds, and therefore -perishes, the French when they left Moscow had inevitably to perish -because they carried their loot with them, yet to abandon what they -had stolen was as impossible for them as it is for the monkey to -open its paw and let go of its nuts. Ten minutes after each regiment -had entered a Moscow district, not a soldier or officer was left. -Men in military uniforms and Hessian boots could be seen through the -windows, laughing and walking through the rooms. In cellars and -storerooms similar men were busy among the provisions, and in the -yards unlocking or breaking open coach house and stable doors, -lighting fires in kitchens and kneading and baking bread with -rolled-up sleeves, and cooking; or frightening, amusing, or -caressing women and children. There were many such men both in the -shops and houses--but there was no army. - -Order after order was issued by the French commanders that day -forbidding the men to disperse about the town, sternly forbidding -any violence to the inhabitants or any looting, and announcing a -roll call for that very evening. But despite all these measures the -men, who had till then constituted an army, flowed all over the -wealthy, deserted city with its comforts and plentiful supplies. As -a hungry herd of cattle keeps well together when crossing a barren -field, but gets out of hand and at once disperses uncontrollably as -soon as it reaches rich pastures, so did the army disperse all over -the wealthy city. - -No residents were left in Moscow, and the soldiers--like water -percolating through sand--spread irresistibly through the city in -all directions from the Kremlin into which they had first marched. The -cavalry, on entering a merchant's house that had been abandoned and -finding there stabling more than sufficient for their horses, went on, -all the same, to the next house which seemed to them better. Many of -them appropriated several houses, chalked their names on them, and -quarreled and even fought with other companies for them. Before they -had had time to secure quarters the soldiers ran out into the -streets to see the city and, hearing that everything had been -abandoned, rushed to places where valuables were to be had for the -taking. The officers followed to check the soldiers and were -involuntarily drawn into doing the same. In Carriage Row carriages had -been left in the shops, and generals flocked there to select -caleches and coaches for themselves. The few inhabitants who had -remained invited commanding officers to their houses, hoping thereby -to secure themselves from being plundered. There were masses of wealth -and there seemed no end to it. All around the quarters occupied by the -French were other regions still unexplored and unoccupied where, -they thought, yet greater riches might be found. And Moscow engulfed -the army ever deeper and deeper. When water is spilled on dry ground -both the dry ground and the water disappear and mud results; and in -the same way the entry of the famished army into the rich and deserted -city resulted in fires and looting and the destruction of both the -army and the wealthy city. - - -The French attributed the Fire of Moscow au patriotisme feroce de -Rostopchine,* the Russians to the barbarity of the French. In reality, -however, it was not, and could not be, possible to explain the burning -of Moscow by making any individual, or any group of people, -responsible for it. Moscow was burned because it found itself in a -position in which any town built of wood was bound to burn, quite -apart from whether it had, or had not, a hundred and thirty inferior -fire engines. Deserted Moscow had to burn as inevitably as a heap of -shavings has to burn on which sparks continually fall for several -days. A town built of wood, where scarcely a day passes without -conflagrations when the house owners are in residence and a police -force is present, cannot help burning when its inhabitants have left -it and it is occupied by soldiers who smoke pipes, make campfires of -the Senate chairs in the Senate Square, and cook themselves meals -twice a day. In peacetime it is only necessary to billet troops in the -villages of any district and the number of fires in that district -immediately increases. How much then must the probability of fire be -increased in an abandoned, wooden town where foreign troops are -quartered. "Le patriotisme feroce de Rostopchine" and the barbarity of -the French were not to blame in the matter. Moscow was set on fire -by the soldiers' pipes, kitchens, and campfires, and by the -carelessness of enemy soldiers occupying houses they did not own. Even -if there was any arson (which is very doubtful, for no one had any -reason to burn the houses--in any case a troublesome and dangerous -thing to do), arson cannot be regarded as the cause, for the same -thing would have happened without any incendiarism. - - -*To Rostopchin's ferocious patriotism. - - -However tempting it might be for the French to blame Rostopchin's -ferocity and for Russians to blame the scoundrel Bonaparte, or later -on to place an heroic torch in the hands of their own people, it is -impossible not to see that there could be no such direct cause of -the fire, for Moscow had to burn as every village, factory, or house -must burn which is left by its owners and in which strangers are -allowed to live and cook their porridge. Moscow was burned by its -inhabitants, it is true, but by those who had abandoned it and not -by those who remained in it. Moscow when occupied by the enemy did not -remain intact like Berlin, Vienna, and other towns, simply because its -inhabitants abandoned it and did not welcome the French with bread and -salt, nor bring them the keys of the city. - - - - - -CHAPTER XXVII - - -The absorption of the French by Moscow, radiating starwise as it -did, only reached the quarter where Pierre was staying by the -evening of the second of September. - -After the last two days spent in solitude and unusual circumstances, -Pierre was in a state bordering on insanity. He was completely -obsessed by one persistent thought. He did not know how or when this -thought had taken such possession of him, but he remembered nothing of -the past, understood nothing of the present, and all he saw and -heard appeared to him like a dream. - -He had left home only to escape the intricate tangle of life's -demands that enmeshed him, and which in his present condition he was -unable to unravel. He had gone to Joseph Alexeevich's house, on the -plea of sorting the deceased's books and papers, only in search of -rest from life's turmoil, for in his mind the memory of Joseph -Alexeevich was connected with a world of eternal, solemn, and calm -thoughts, quite contrary to the restless confusion into which he -felt himself being drawn. He sought a quiet refuge, and in Joseph -Alexeevich's study he really found it. When he sat with his elbows -on the dusty writing table in the deathlike stillness of the study, -calm and significant memories of the last few days rose one after -another in his imagination, particularly of the battle of Borodino and -of that vague sense of his own insignificance and insincerity compared -with the truth, simplicity, and strength of the class of men he -mentally classed as they. When Gerasim roused him from his reverie the -idea occurred to him of taking part in the popular defense of Moscow -which he knew was projected. And with that object he had asked Gerasim -to get him a peasant's coat and a pistol, confiding to him his -intentions of remaining in Joseph Alexeevich's house and keeping his -name secret. Then during the first day spent in inaction and -solitude (he tried several times to fix his attention on the Masonic -manuscripts, but was unable to do so) the idea that had previously -occurred to him of the cabalistic significance of his name in -connection with Bonaparte's more than once vaguely presented itself. -But the idea that he, L'russe Besuhof, was destined to set a limit -to the power of the Beast was as yet only one of the fancies that -often passed through his mind and left no trace behind. - -When, having bought the coat merely with the object of taking part -among the people in the defense of Moscow, Pierre had met the -Rostovs and Natasha had said to him: "Are you remaining in -Moscow?... How splendid!" the thought flashed into his mind that it -really would be a good thing, even if Moscow were taken, for him to -remain there and do what he was predestined to do. - -Next day, with the sole idea of not sparing himself and not -lagging in any way behind them, Pierre went to the Three Hills gate. -But when he returned to the house convinced that Moscow would not be -defended, he suddenly felt that what before had seemed to him merely a -possibility had now become absolutely necessary and inevitable. He -must remain in Moscow, concealing his name, and must meet Napoleon and -kill him, and either perish or put an end to the misery of all Europe- -which it seemed to him was solely due to Napoleon. - -Pierre knew all the details of the attempt on Bonaparte's life in -1809 by a German student in Vienna, and knew that the student had been -shot. And the risk to which he would expose his life by carrying out -his design excited him still more. - -Two equally strong feelings drew Pierre irresistibly to this -purpose. The first was a feeling of the necessity of sacrifice and -suffering in view of the common calamity, the same feeling that had -caused him to go to Mozhaysk on the twenty-fifth and to make his way -to the very thick of the battle and had now caused him to run away -from his home and, in place of the luxury and comfort to which he -was accustomed, to sleep on a hard sofa without undressing and eat the -same food as Gerasim. The other was that vague and quite Russian -feeling of contempt for everything conventional, artificial, and -human--for everything the majority of men regard as the greatest -good in the world. Pierre had first experienced this strange and -fascinating feeling at the Sloboda Palace, when he had suddenly felt -that wealth, power, and life--all that men so painstakingly acquire -and guard--if it has any worth has so only by reason the joy with -which it can all be renounced. - -It was the feeling that induces a volunteer recruit to spend his -last penny on drink, and a drunken man to smash mirrors or glasses for -no apparent reason and knowing that it will cost him all the money -he possesses: the feeling which causes a man to perform actions -which from an ordinary point of view are insane, to test, as it -were, his personal power and strength, affirming the existence of a -higher, nonhuman criterion of life. - -From the very day Pierre had experienced this feeling for the -first time at the Sloboda Palace he had been continuously under its -influence, but only now found full satisfaction for it. Moreover, at -this moment Pierre was supported in his design and prevented from -renouncing it by what he had already done in that direction. If he -were now to leave Moscow like everyone else, his flight from home, the -peasant coat, the pistol, and his announcement to the Rostovs that -he would remain in Moscow would all become not merely meaningless -but contemptible and ridiculous, and to this Pierre was very -sensitive. - -Pierre's physical condition, as is always the case, corresponded -to his mental state. The unaccustomed coarse food, the vodka he -drank during those days, the absence of wine and cigars, his dirty -unchanged linen, two almost sleepless nights passed on a short sofa -without bedding--all this kept him in a state of excitement -bordering on insanity. - -It was two o'clock in the afternoon. The French had already -entered Moscow. Pierre knew this, but instead of acting he only -thought about his undertaking, going over its minutest details in -his mind. In his fancy he did not clearly picture to himself either -the striking of the blow or the death of Napoleon, but with -extraordinary vividness and melancholy enjoyment imagined his own -destruction and heroic endurance. - -"Yes, alone, for the sake of all, I must do it or perish!" he -thought. "Yes, I will approach... and then suddenly... with pistol -or dagger? But that is all the same! 'It is not I but the hand of -Providence that punishes thee,' I shall say," thought he, imagining -what he would say when killing Napoleon. "Well then, take me and -execute me!" he went on, speaking to himself and bowing his head -with a sad but firm expression. - -While Pierre, standing in the middle of the room, was talking to -himself in this way, the study door opened and on the threshold -appeared the figure of Makar Alexeevich, always so timid before but -now quite transformed. - -His dressing gown was unfastened, his face red and distorted. He was -obviously drunk. On seeing Pierre he grew confused at first, but -noticing embarrassment on Pierre's face immediately grew bold and, -staggering on his thin legs, advanced into the middle of the room. - -"They're frightened," he said confidentially in a hoarse voice. "I -say I won't surrender, I say... Am I not right, sir?" - -He paused and then suddenly seeing the pistol on the table seized it -with unexpected rapidity and ran out into the corridor. - -Gerasim and the porter, who had followed Makar Alexeevich, stopped -him in the vestibule and tried to take the pistol from him. Pierre, -coming out into the corridor, looked with pity and repulsion at the -half-crazy old man. Makar Alexeevich, frowning with exertion, held -on to the pistol and screamed hoarsely, evidently with some heroic -fancy in his head. - -"To arms! Board them! No, you shan't get it," he yelled. - -"That will do, please, that will do. Have the goodness--please, sir, -to let go! Please, sir..." pleaded Gerasim, trying carefully to -steer Makar Alexeevich by the elbows back to the door. - -"Who are you? Bonaparte!..." shouted Makar Alexeevich. - -"That's not right, sir. Come to your room, please, and rest. Allow -me to have the pistol." - -"Be off, thou base slave! Touch me not! See this?" shouted Makar -Alexeevich, brandishing the pistol. "Board them!" - -"Catch hold!" whispered Gerasim to the porter. - -They seized Makar Alexeevich by the arms and dragged him to the -door. - -The vestibule was filled with the discordant sounds of a struggle -and of a tipsy, hoarse voice. - -Suddenly a fresh sound, a piercing feminine scream, reverberated -from the porch and the cook came running into the vestibule. - -"It's them! Gracious heavens! O Lord, four of them, horsemen!" she -cried. - -Gerasim and the porter let Makar Alexeevich go, and in the now -silent corridor the sound of several hands knocking at the front -door could be heard. - - - - - -CHAPTER XXVIII - - -Pierre, having decided that until he had carried out his design he -would disclose neither his identity nor his knowledge of French, stood -at the half-open door of the corridor, intending to conceal himself as -soon as the French entered. But the French entered and still Pierre -did not retire--an irresistible curiosity kept him there. - -There were two of them. One was an officer--a tall, soldierly, -handsome man--the other evidently a private or an orderly, -sunburned, short, and thin, with sunken cheeks and a dull -expression. The officer walked in front, leaning on a stick and -slightly limping. When he had advanced a few steps he stopped, -having apparently decided that these were good quarters, turned -round to the soldiers standing at the entrance, and in a loud voice of -command ordered them to put up the horses. Having done that, the -officer, lifting his elbow with a smart gesture, stroked his -mustache and lightly touched his hat. - -"Bonjour, la compagnie!"* said he gaily, smiling and looking about -him. - - -*"Good day, everybody!" - - -No one gave any reply. - -"Vous etes le bourgeois?"* the officer asked Gerasim. - - -*"Are you the master here?" - - -Gerasim gazed at the officer with an alarmed and inquiring look. - -"Quartier, quartier, logement!" said the officer, looking down at -the little man with a condescending and good-natured smile. "Les -francais sont de bons enfants. Que diable! Voyons! Ne nous fachons -pas, mon vieux!"* added he, clapping the scared and silent Gerasim -on the shoulder. "Well, does no one speak French in this -establishment?" he asked again in French, looking around and meeting -Pierre's eyes. Pierre moved away from the door. - - -*"Quarters, quarters, lodgings! The French are good fellows. What -the devil! There, don't let us be cross, old fellow!" - - -Again the officer turned to Gerasim and asked him to show him the -rooms in the house. - -"Master, not here--don't understand... me, you..." said Gerasim, -trying to render his words more comprehensible by contorting them. - -Still smiling, the French officer spread out his hands before -Gerasim's nose, intimating that he did not understand him either, -and moved, limping, to the door at which Pierre was standing. Pierre -wished to go away and conceal himself, but at that moment he saw Makar -Alexeevich appearing at the open kitchen door with the pistol in his -hand. With a madman's cunning, Makar Alexeevich eyed the Frenchman, -raised his pistol, and took aim. - -"Board them!" yelled the tipsy man, trying to press the trigger. -Hearing the yell the officer turned round, and at the same moment -Pierre threw himself on the drunkard. Just when Pierre snatched at and -struck up the pistol Makar Alexeevich at last got his fingers on the -trigger, there was a deafening report, and all were enveloped in a -cloud of smoke. The Frenchman turned pale and rushed to the door. - -Forgetting his intention of concealing his knowledge of French, -Pierre, snatching away the pistol and throwing it down, ran up to -the officer and addressed him in French. - -"You are not wounded?" he asked. - -"I think not," answered the Frenchman, feeling himself over. "But -I have had a lucky escape this time," he added, pointing to the -damaged plaster of the wall. "Who is that man?" said he, looking -sternly at Pierre. - -"Oh, I am really in despair at what has occurred," said Pierre -rapidly, quite forgetting the part he had intended to play. "He is -an unfortunate madman who did not know what he was doing." - -The officer went up to Makar Alexeevich and took him by the collar. - -Makar Alexeevich was standing with parted lips, swaying, as if about -to fall asleep, as he leaned against the wall. - -"Brigand! You shall pay for this," said the Frenchman, letting go of -him. "We French are merciful after victory, but we do not pardon -traitors," he added, with a look of gloomy dignity and a fine -energetic gesture. - -Pierre continued, in French, to persuade the officer not to hold -that drunken imbecile to account. The Frenchman listened in silence -with the same gloomy expression, but suddenly turned to Pierre with -a smile. For a few seconds he looked at him in silence. His handsome -face assumed a melodramatically gentle expression and he held out -his hand. - -"You have saved my life. You are French," said he. - -For a Frenchman that deduction was indubitable. Only a Frenchman -could perform a great deed, and to save his life--the life of M. -Ramballe, captain of the 13th Light Regiment--was undoubtedly a very -great deed. - -But however indubitable that conclusion and the officer's conviction -based upon it, Pierre felt it necessary to disillusion him. - -"I am Russian," he said quickly. - -"Tut, tut, tut! Tell that to others," said the officer, waving his -finger before his nose and smiling. "You shall tell me all about -that presently. I am delighted to meet a compatriot. Well, and what -are we to do with this man?" he added, addressing himself to Pierre as -to a brother. - -Even if Pierre were not a Frenchman, having once received that -loftiest of human appellations he could not renounce it, said the -officer's look and tone. In reply to his last question Pierre again -explained who Makar Alexeevich was and how just before their arrival -that drunken imbecile had seized the loaded pistol which they had -not had time to recover from him, and begged the officer to let the -deed go unpunished. - -The Frenchman expanded his chest and made a majestic gesture with -his arm. - -"You have saved my life! You are French. You ask his pardon? I grant -it you. Lead that man away!" said he quickly and energetically, and -taking the arm of Pierre whom he had promoted to be a Frenchman for -saving his life, he went with him into the room. - -The soldiers in the yard, hearing the shot, came into the passage -asking what had happened, and expressed their readiness to punish -the culprits, but the officer sternly checked them. - -"You will be called in when you are wanted," he said. - -The soldiers went out again, and the orderly, who had meanwhile -had time to visit the kitchen, came up to his officer. - -"Captain, there is soup and a leg of mutton in the kitchen," said -he. "Shall I serve them up?" - -"Yes, and some wine," answered the captain. - - - - - -CHAPTER XXIX - - -When the French officer went into the room with Pierre the latter -again thought it his duty to assure him that he was not French and -wished to go away, but the officer would not hear of it. He was so -very polite, amiable, good-natured, and genuinely grateful to Pierre -for saving his life that Pierre had not the heart to refuse, and sat -down with him in the parlor--the first room they entered. To -Pierre's assurances that he was not a Frenchman, the captain, -evidently not understanding how anyone could decline so flattering -an appellation, shrugged his shoulders and said that if Pierre -absolutely insisted on passing for a Russian let it be so, but for all -that he would be forever bound to Pierre by gratitude for saving his -life. - -Had this man been endowed with the slightest capacity for perceiving -the feelings of others, and had he at all understood what Pierre's -feelings were, the latter would probably have left him, but the -man's animated obtuseness to everything other than himself disarmed -Pierre. - -"A Frenchman or a Russian prince incognito," said the officer, -looking at Pierre's fine though dirty linen and at the ring on his -finger. "I owe my life to you and offer you my friendship. A Frenchman -never forgets either an insult or a service. I offer you my -friendship. That is all I can say." - -There was so much good nature and nobility (in the French sense of -the word) in the officer's voice, in the expression of his face and in -his gestures, that Pierre, unconsciously smiling in response to the -Frenchman's smile, pressed the hand held out to him. - -"Captain Ramballe, of the 13th Light Regiment, Chevalier of the -Legion of Honor for the affair on the seventh of September," he -introduced himself, a self-satisfied irrepressible smile puckering his -lips under his mustache. "Will you now be so good as to tell me with -whom I have the honor of conversing so pleasantly, instead of being in -the ambulance with that maniac's bullet in my body?" - -Pierre replied that he could not tell him his name and, blushing, -began to try to invent a name and to say something about his reason -for concealing it, but the Frenchman hastily interrupted him. - -"Oh, please!" said he. "I understand your reasons. You are an -officer... a superior officer perhaps. You have borne arms against us. -That's not my business. I owe you my life. That is enough for me. I am -quite at your service. You belong to the gentry?" he concluded with -a shade of inquiry in his tone. Pierre bent his head. "Your -baptismal name, if you please. That is all I ask. Monsieur Pierre, you -say.... That's all I want to know." - -When the mutton and an omelet had been served and a samovar and -vodka brought, with some wine which the French had taken from a -Russian cellar and brought with them, Ramballe invited Pierre to share -his dinner, and himself began to eat greedily and quickly like a -healthy and hungry man, munching his food rapidly with his strong -teeth, continually smacking his lips, and repeating--"Excellent! -Delicious!" His face grew red and was covered with perspiration. -Pierre was hungry and shared the dinner with pleasure. Morel, the -orderly, brought some hot water in a saucepan and placed a bottle of -claret in it. He also brought a bottle of kvass, taken from the -kitchen for them to try. That beverage was already known to the French -and had been given a special name. They called it limonade de cochon -(pig's lemonade), and Morel spoke well of the limonade de cochon he -had found in the kitchen. But as the captain had the wine they had -taken while passing through Moscow, he left the kvass to Morel and -applied himself to the bottle of Bordeaux. He wrapped the bottle up to -its neck in a table napkin and poured out wine for himself and for -Pierre. The satisfaction of his hunger and the wine rendered the -captain still more lively and he chatted incessantly all through -dinner. - -"Yes, my dear Monsieur Pierre, I owe you a fine votive candle for -saving me from that maniac.... You see, I have bullets enough in my -body already. Here is one I got at Wagram" (he touched his side) -"and a second at Smolensk"--he showed a scar on his cheek--"and this -leg which as you see does not want to march, I got that on the seventh -at the great battle of la Moskowa. Sacre Dieu! It was splendid! That -deluge of fire was worth seeing. It was a tough job you set us -there, my word! You may be proud of it! And on my honor, in spite of -the cough I caught there, I should be ready to begin again. I pity -those who did not see it." - -"I was there," said Pierre. - -"Bah, really? So much the better! You are certainly brave foes. -The great redoubt held out well, by my pipe!" continued the Frenchman. -"And you made us pay dear for it. I was at it three times--sure as I -sit here. Three times we reached the guns and three times we were -thrown back like cardboard figures. Oh, it was beautiful, Monsieur -Pierre! Your grenadiers were splendid, by heaven! I saw them close -up their ranks six times in succession and march as if on parade. Fine -fellows! Our King of Naples, who knows what's what, cried 'Bravo!' Ha, -ha! So you are one of us soldiers!" he added, smiling, after a -momentary pause. "So much the better, so much the better, Monsieur -Pierre! Terrible in battle... gallant... with the fair" (he winked and -smiled), "that's what the French are, Monsieur Pierre, aren't they?" - -The captain was so naively and good-humoredly gay, so real, and so -pleased with himself that Pierre almost winked back as he looked -merrily at him. Probably the word "gallant" turned the captain's -thoughts to the state of Moscow. - -"Apropos, tell me please, is it true that the women have all left -Moscow? What a queer idea! What had they to be afraid of?" - -"Would not the French ladies leave Paris if the Russians entered -it?" asked Pierre. - -"Ha, ha, ha!" The Frenchman emitted a merry, sanguine chuckle, -patting Pierre on the shoulder. "What a thing to say!" he exclaimed. -"Paris?... But Paris, Paris..." - -"Paris--the capital of the world," Pierre finished his remark for -him. - -The captain looked at Pierre. He had a habit of stopping short in -the middle of his talk and gazing intently with his laughing, kindly -eyes. - -"Well, if you hadn't told me you were Russian, I should have wagered -that you were Parisian! You have that... I don't know what, that..." -and having uttered this compliment, he again gazed at him in silence. - -"I have been in Paris. I spent years there," said Pierre. - -"Oh yes, one sees that plainly. Paris!... A man who doesn't know -Paris is a savage. You can tell a Parisian two leagues off. Paris is -Talma, la Duchenois, Potier, the Sorbonne, the boulevards," and -noticing that his conclusion was weaker than what had gone before, -he added quickly: "There is only one Paris in the world. You have been -to Paris and have remained Russian. Well, I don't esteem you the -less for it." - -Under the influence of the wine he had drunk, and after the days -he had spent alone with his depressing thoughts, Pierre -involuntarily enjoyed talking with this cheerful and good-natured man. - -"To return to your ladies--I hear they are lovely. What a wretched -idea to go and bury themselves in the steppes when the French army -is in Moscow. What a chance those girls have missed! Your peasants, -now--that's another thing; but you civilized people, you ought to know -us better than that. We took Vienna, Berlin, Madrid, Naples, Rome, -Warsaw, all the world's capitals.... We are feared, but we are -loved. We are nice to know. And then the Emperor..." he began, but -Pierre interrupted him. - -"The Emperor," Pierre repeated, and his face suddenly became sad and -embarrassed, "is the Emperor...?" - -"The Emperor? He is generosity, mercy, justice, order, genius- -that's what the Emperor is! It is I, Ramballe, who tell you so.... I -assure you I was his enemy eight years ago. My father was an -emigrant count.... But that man has vanquished me. He has taken hold -of me. I could not resist the sight of the grandeur and glory with -which he has covered France. When I understood what he wanted--when -I saw that he was preparing a bed of laurels for us, you know, I -said to myself: 'That is a monarch,' and I devoted myself to him! So -there! Oh yes, mon cher, he is the greatest man of the ages past or -future." - -"Is he in Moscow?" Pierre stammered with a guilty look. - -The Frenchman looked at his guilty face and smiled. - -"No, he will make his entry tomorrow," he replied, and continued his -talk. - -Their conversation was interrupted by the cries of several voices at -the gate and by Morel, who came to say that some Wurttemberg hussars -had come and wanted to put up their horses in the yard where the -captain's horses were. This difficulty had arisen chiefly because -the hussars did not understand what was said to them in French. - -The captain had their senior sergeant called in, and in a stern -voice asked him to what regiment he belonged, who was his commanding -officer, and by what right he allowed himself to claim quarters that -were already occupied. The German who knew little French, answered the -two first questions by giving the names of his regiment and of his -commanding officer, but in reply to the third question which he did -not understand said, introducing broken French into his own German, -that he was the quartermaster of the regiment and his commander had -ordered him to occupy all the houses one after another. Pierre, who -knew German, translated what the German said to the captain and gave -the captain's reply to the Wurttemberg hussar in German. When he had -understood what was said to him, the German submitted and took his men -elsewhere. The captain went out into the porch and gave some orders in -a loud voice. - -When he returned to the room Pierre was sitting in the same place as -before, with his head in his hands. His face expressed suffering. He -really was suffering at that moment. When the captain went out and -he was left alone, suddenly he came to himself and realized the -position he was in. It was not that Moscow had been taken or that -the happy conquerors were masters in it and were patronizing him. -Painful as that was it was not that which tormented Pierre at the -moment. He was tormented by the consciousness of his own weakness. The -few glasses of wine he had drunk and the conversation with this -good-natured man had destroyed the mood of concentrated gloom in which -he had spent the last few days and which was essential for the -execution of his design. The pistol, dagger, and peasant coat were -ready. Napoleon was to enter the town next day. Pierre still -considered that it would be a useful and worthy action to slay the -evildoer, but now he felt that he would not do it. He did not know -why, but he felt a foreboding that he would not carry out his -intention. He struggled against the confession of his weakness but -dimly felt that he could not overcome it and that his former gloomy -frame of mind, concerning vengeance, killing, and self-sacrifice, -had been dispersed like dust by contact with the first man he met. - -The captain returned to the room, limping slightly and whistling a -tune. - -The Frenchman's chatter which had previously amused Pierre now -repelled him. The tune he was whistling, his gait, and the gesture -with which he twirled his mustache, all now seemed offensive. "I -will go away immediately. I won't say another word to him," thought -Pierre. He thought this, but still sat in the same place. A strange -feeling of weakness tied him to the spot; he wished to get up and go -away, but could not do so. - -The captain, on the other hand, seemed very cheerful. He paced up -and down the room twice. His eyes shone and his mustache twitched as -if he were smiling to himself at some amusing thought. - -"The colonel of those Wurttembergers is delightful," he suddenly -said. "He's a German, but a nice fellow all the same.... But he's a -German." He sat down facing Pierre. "By the way, you know German, -then?" - -Pierre looked at him in silence. - -"What is the German for 'shelter'?" - -"Shelter?" Pierre repeated. "The German for shelter is Unterkunft." - -"How do you say it?" the captain asked quickly and doubtfully. - -"Unterkunft," Pierre repeated. - -"Onterkoff," said the captain and looked at Pierre for some -seconds with laughing eyes. "These Germans are first-rate fools, don't -you think so, Monsieur Pierre?" he concluded. - -"Well, let's have another bottle of this Moscow Bordeaux, shall -we? Morel will warm us up another little bottle. Morel!" he called out -gaily. - -Morel brought candles and a bottle of wine. The captain looked at -Pierre by the candlelight and was evidently struck by the troubled -expression on his companion's face. Ramballe, with genuine distress -and sympathy in his face, went up to Pierre and bent over him. - -"There now, we're sad," said he, touching Pierre's hand. "Have I -upset you? No, really, have you anything against me?" he asked Pierre. -"Perhaps it's the state of affairs?" - -Pierre did not answer, but looked cordially into the Frenchman's -eyes whose expression of sympathy was pleasing to him. - -"Honestly, without speaking of what I owe you, I feel friendship for -you. Can I do anything for you? Dispose of me. It is for life and -death. I say it with my hand on my heart!" said he, striking his -chest. - -"Thank you," said Pierre. - -The captain gazed intently at him as he had done when he learned -that "shelter" was Unterkunft in German, and his face suddenly -brightened. - -"Well, in that case, I drink to our friendship!" he cried gaily, -filling two glasses with wine. - -Pierre took one of the glasses and emptied it. Ramballe emptied -his too, again pressed Pierre's hand, and leaned his elbows on the -table in a pensive attitude. - -"Yes, my dear friend," he began, "such is fortune's caprice. Who -would have said that I should be a soldier and a captain of dragoons -in the service of Bonaparte, as we used to call him? Yet here I am -in Moscow with him. I must tell you, mon cher," he continued in the -sad and measured tones of a man who intends to tell a long story, -"that our name is one of the most ancient in France." - -And with a Frenchman's easy and naive frankness the captain told -Pierre the story of his ancestors, his childhood, youth, and -manhood, and all about his relations and his financial and family -affairs, "ma pauvre mere" playing of course an important part in the -story. - -"But all that is only life's setting, the real thing is love- -love! Am I not right, Monsieur Pierre?" said he, growing animated. -"Another glass?" - -Pierre again emptied his glass and poured himself out a third. - -"Oh, women, women!" and the captain, looking with glistening eyes at -Pierre, began talking of love and of his love affairs. - -There were very many of these, as one could easily believe, -looking at the officer's handsome, self-satisfied face, and noting the -eager enthusiasm with which he spoke of women. Though all Ramballe's -love stories had the sensual character which Frenchmen regard as the -special charm and poetry of love, yet he told his story with such -sincere conviction that he alone had experienced and known all the -charm of love and he described women so alluringly that Pierre -listened to him with curiosity. - -It was plain that l'amour which the Frenchman was so fond of was not -that low and simple kind that Pierre had once felt for his wife, nor -was it the romantic love stimulated by himself that he experienced for -Natasha. (Ramballe despised both these kinds of love equally: the -one he considered the "love of clodhoppers" and the other the "love of -simpletons.") L'amour which the Frenchman worshiped consisted -principally in the unnaturalness of his relation to the woman and in a -combination of incongruities giving the chief charm to the feeling. - -Thus the captain touchingly recounted the story of his love for a -fascinating marquise of thirty-five and at the same time for a -charming, innocent child of seventeen, daughter of the bewitching -marquise. The conflict of magnanimity between the mother and the -daughter, ending in the mother's sacrificing herself and offering -her daughter in marriage to her lover, even now agitated the -captain, though it was the memory of a distant past. Then he recounted -an episode in which the husband played the part of the lover, and -he--the lover--assumed the role of the husband, as well as several -droll incidents from his recollections of Germany, where "shelter" -is called Unterkunft and where the husbands eat sauerkraut and the -young girls are "too blonde." - -Finally, the latest episode in Poland still fresh in the captain's -memory, and which he narrated with rapid gestures and glowing face, -was of how he had saved the life of a Pole (in general, the saving -of life continually occurred in the captain's stories) and the Pole -had entrusted to him his enchanting wife (parisienne de coeur) while -himself entering the French service. The captain was happy, the -enchanting Polish lady wished to elope with him, but, prompted by -magnanimity, the captain restored the wife to the husband, saying as -he did so: "I have saved your life, and I save your honor!" Having -repeated these words the captain wiped his eyes and gave himself a -shake, as if driving away the weakness which assailed him at this -touching recollection. - -Listening to the captain's tales, Pierre--as often happens late in -the evening and under the influence of wine--followed all that was -told him, understood it all, and at the same time followed a train -of personal memories which, he knew not why, suddenly arose in his -mind. While listening to these love stories his own love for Natasha -unexpectedly rose to his mind, and going over the pictures of that -love in his imagination he mentally compared them with Ramballe's -tales. Listening to the story of the struggle between love and duty, -Pierre saw before his eyes every minutest detail of his last meeting -with the object of his love at the Sukharev water tower. At the time -of that meeting it had not produced an effect upon him--he had not -even once recalled it. But now it seemed to him that that meeting -had had in it something very important and poetic. - -"Peter Kirilovich, come here! We have recognized you," he now seemed -to hear the words she had uttered and to see before him her eyes, -her smile, her traveling hood, and a stray lock of her hair... and -there seemed to him something pathetic and touching in all this. - -Having finished his tale about the enchanting Polish lady, the -captain asked Pierre if he had ever experienced a similar impulse to -sacrifice himself for love and a feeling of envy of the legitimate -husband. - -Challenged by this question Pierre raised his head and felt a need -to express the thoughts that filled his mind. He began to explain that -he understood love for a women somewhat differently. He said that in -all his life he had loved and still loved only one woman, and that she -could never be his. - -"Tiens!" said the captain. - -Pierre then explained that he had loved this woman from his earliest -years, but that he had not dared to think of her because she was too -young, and because he had been an illegitimate son without a name. -Afterwards when he had received a name and wealth he dared not think -of her because he loved her too well, placing her far above everything -in the world, and especially therefore above himself. - -When he had reached this point, Pierre asked the captain whether -he understood that. - -The captain made a gesture signifying that even if he did not -understand it he begged Pierre to continue. - -"Platonic love, clouds..." he muttered. - -Whether it was the wine he had drunk, or an impulse of frankness, or -the thought that this man did not, and never would, know any of -those who played a part in his story, or whether it was all these -things together, something loosened Pierre's tongue. Speaking -thickly and with a faraway look in his shining eyes, he told the whole -story of his life: his marriage, Natasha's love for his best friend, -her betrayal of him, and all his own simple relations with her. -Urged on by Ramballe's questions he also told what he had at first -concealed--his own position and even his name. - -More than anything else in Pierre's story the captain was -impressed by the fact that Pierre was very rich, had two mansions in -Moscow, and that he had abandoned everything and not left the city, -but remained there concealing his name and station. - -When it was late at night they went out together into the street. -The night was warm and light. To the left of the house on the Pokrovka -a fire glowed--the first of those that were beginning in Moscow. To -the right and high up in the sky was the sickle of the waning moon and -opposite to it hung that bright comet which was connected in -Pierre's heart with his love. At the gate stood Gerasim, the cook, and -two Frenchmen. Their laughter and their mutually incomprehensible -remarks in two languages could be heard. They were looking at the glow -seen in the town. - -There was nothing terrible in the one small, distant fire in the -immense city. - -Gazing at the high starry sky, at the moon, at the comet, and at the -glow from the fire, Pierre experienced a joyful emotion. "There now, -how good it is, what more does one need?" thought he. And suddenly -remembering his intention he grew dizzy and felt so faint that he -leaned against the fence to save himself from falling. - -Without taking leave of his new friend, Pierre left the gate with -unsteady steps and returning to his room lay down on the sofa and -immediately fell asleep. - - - - - -CHAPTER XXX - - -The glow of the first fire that began on the second of September was -watched from the various roads by the fugitive Muscovites and by the -retreating troops, with many different feelings. - -The Rostov party spent the night at Mytishchi, fourteen miles from -Moscow. They had started so late on the first of September, the road -had been so blocked by vehicles and troops, so many things had been -forgotten for which servants were sent back, that they had decided -to spend that night at a place three miles out of Moscow. The next -morning they woke late and were again delayed so often that they -only got as far as Great Mytishchi. At ten o'clock that evening the -Rostov family and the wounded traveling with them were all distributed -in the yards and huts of that large village. The Rostovs' servants and -coachmen and the orderlies of the wounded officers, after attending to -their masters, had supper, fed the horses, and came out into the -porches. - -In a neighboring hut lay Raevski's adjutant with a fractured -wrist. The awful pain he suffered made him moan incessantly and -piteously, and his moaning sounded terrible in the darkness of the -autumn night. He had spent the first night in the same yard as the -Rostovs. The countess said she had been unable to close her eyes on -account of his moaning, and at Mytishchi she moved into a worse hut -simply to be farther away from the wounded man. - -In the darkness of the night one of the servants noticed, above -the high body of a coach standing before the porch, the small glow -of another fire. One glow had long been visible and everybody knew -that it was Little Mytishchi burning--set on fire by Mamonov's -Cossacks. - -"But look here, brothers, there's another fire!" remarked an -orderly. - -All turned their attention to the glow. - -"But they told us Little Mytishchi had been set on fire by Mamonov's -Cossacks." - -"But that's not Mytishchi, it's farther away." - -"Look, it must be in Moscow!" - -Two of the gazers went round to the other side of the coach and -sat down on its steps. - -"It's more to the left, why, Little Mytishchi is over there, and -this is right on the other side." - -Several men joined the first two. - -"See how it's flaring," said one. "That's a fire in Moscow: either -in the Sushchevski or the Rogozhski quarter." - -No one replied to this remark and for some time they all gazed -silently at the spreading flames of the second fire in the distance. - -Old Daniel Terentich, the count's valet (as he was called), came -up to the group and shouted at Mishka. - -"What are you staring at, you good-for-nothing?... The count will be -calling and there's nobody there; go and gather the clothes together." - -"I only ran out to get some water," said Mishka. - -"But what do you think, Daniel Terentich? Doesn't it look as if that -glow were in Moscow?" remarked one of the footmen. - -Daniel Terentich made no reply, and again for a long time they -were all silent. The glow spread, rising and failing, farther and -farther still. - -"God have mercy.... It's windy and dry..." said another voice. - -"Just look! See what it's doing now. O Lord! You can even see the -crows flying. Lord have mercy on us sinners!" - -"They'll put it out, no fear!" - -"Who's to put it out?" Daniel Terentich, who had hitherto been -silent, was heard to say. His voice was calm and deliberate. "Moscow -it is, brothers," said he. "Mother Moscow, the white..." his voice -faltered, and he gave way to an old man's sob. - -And it was as if they had all only waited for this to realize the -significance for them of the glow they were watching. Sighs were -heard, words of prayer, and the sobbing of the count's old valet. - - - - - -CHAPTER XXXI - - -The valet, returning to the cottage, informed the count that -Moscow was burning. The count donned his dressing gown and went out to -look. Sonya and Madame Schoss, who had not yet undressed, went out -with him. Only Natasha and the countess remained in the room. Petya -was no longer with the family, he had gone on with his regiment -which was making for Troitsa. - -The countess, on hearing that Moscow was on fire, began to cry. -Natasha, pale, with a fixed look, was sitting on the bench under the -icons just where she had sat down on arriving and paid no attention to -her father's words. She was listening to the ceaseless moaning of -the adjutant, three houses off. - -"Oh, how terrible," said Sonya returning from the yard chilled and -frightened. "I believe the whole of Moscow will burn, there's an awful -glow! Natasha, do look! You can see it from the window," she said to -her cousin, evidently wishing to distract her mind. - -But Natasha looked at her as if not understanding what was said to -her and again fixed her eyes on the corner of the stove. She had -been in this condition of stupor since the morning, when Sonya, to the -surprise and annoyance of the countess, had for some unaccountable -reason found it necessary to tell Natasha of Prince Andrew's wound and -of his being with their party. The countess had seldom been so angry -with anyone as she was with Sonya. Sonya had cried and begged to be -forgiven and now, as if trying to atone for her fault, paid -unceasing attention to her cousin. - -"Look, Natasha, how dreadfully it is burning!" said she. - -"What's burning?" asked Natasha. "Oh, yes, Moscow." - -And as if in order not to offend Sonya and to get rid of her, she -turned her face to the window, looked out in such a way that it was -evident that she could not see anything, and again settled down in her -former attitude. - -"But you didn't see it!" - -"Yes, really I did," Natasha replied in a voice that pleaded to be -left in peace. - -Both the countess and Sonya understood that, naturally, neither -Moscow nor the burning of Moscow nor anything else could seem of -importance to Natasha. - -The count returned and lay down behind the partition. The countess -went up to her daughter and touched her head with the back of her hand -as she was wont to do when Natasha was ill, then touched her -forehead with her lips as if to feel whether she was feverish, and -finally kissed her. - -"You are cold. You are trembling all over. You'd better lie down," -said the countess. - -"Lie down? All right, I will. I'll lie down at once," said Natasha. - -When Natasha had been told that morning that Prince Andrew was -seriously wounded and was traveling with their party, she had at first -asked many questions: Where was he going? How was he wounded? Was it -serious? And could she see him? But after she had been told that she -could not see him, that he was seriously wounded but that his life was -not in danger, she ceased to ask questions or to speak at all, -evidently disbelieving what they told her, and convinced that say what -she might she would still be told the same. All the way she had sat -motionless in a corner of the coach with wide open eyes, and the -expression in them which the countess knew so well and feared so much, -and now she sat in the same way on the bench where she had seated -herself on arriving. She was planning something and either deciding or -had already decided something in her mind. The countess knew this, but -what it might be she did not know, and this alarmed and tormented her. - -"Natasha, undress, darling; lie down on my bed." - -A bed had been made on a bedstead for the countess only. Madame -Schoss and the two girls were to sleep on some hay on the floor. - -"No, Mamma, I will lie down here on the floor," Natasha replied -irritably and she went to the window and opened it. Through the open -window the moans of the adjutant could be heard more distinctly. She -put her head out into the damp night air, and the countess saw her -slim neck shaking with sobs and throbbing against the window frame. -Natasha knew it was not Prince Andrew who was moaning. She knew Prince -Andrew was in the same yard as themselves and in a part of the hut -across the passage; but this dreadful incessant moaning made her -sob. The countess exchanged a look with Sonya. - -"Lie down, darling; lie down, my pet," said the countess, softly -touching Natasha's shoulders. "Come, lie down." - -"Oh, yes... I'll lie down at once," said Natasha, and began -hurriedly undressing, tugging at the tapes of her petticoat. - -When she had thrown off her dress and put on a dressing jacket, -she sat down with her foot under her on the bed that had been made -up on the floor, jerked her thin and rather short plait of hair to the -front, and began replaiting it. Her long, thin, practiced fingers -rapidly unplaited, replaited, and tied up her plait. Her head moved -from side to side from habit, but her eyes, feverishly wide, looked -fixedly before her. When her toilet for the night was finished she -sank gently onto the sheet spread over the hay on the side nearest the -door. - -"Natasha, you'd better lie in the middle," said Sonya. - -"I'll stay here," muttered Natasha. "Do lie down," she added -crossly, and buried her face in the pillow. - -The countess, Madame Schoss, and Sonya undressed hastily and lay -down. The small lamp in front of the icons was the only light left -in the room. But in the yard there was a light from the fire at Little -Mytishchi a mile and a half away, and through the night came the noise -of people shouting at a tavern Mamonov's Cossacks had set up across -the street, and the adjutant's unceasing moans could still be heard. - -For a long time Natasha listened attentively to the sounds that -reached her from inside and outside the room and did not move. First -she heard her mother praying and sighing and the creaking of her bed -under her, then Madame Schoss' familiar whistling snore and Sonya's -gentle breathing. Then the countess called to Natasha. Natasha did not -answer. - -"I think she's asleep, Mamma," said Sonya softly. - -After short silence the countess spoke again but this time no one -replied. - -Soon after that Natasha heard her mother's even breathing. Natasha -did not move, though her little bare foot, thrust out from under the -quilt, was growing cold on the bare floor. - -As if to celebrate a victory over everybody, a cricket chirped in -a crack in the wall. A cock crowed far off and another replied near -by. The shouting in the tavern had died down; only the moaning of -the adjutant was heard. Natasha sat up. - -"Sonya, are you asleep? Mamma?" she whispered. - -No one replied. Natasha rose slowly and carefully, crossed -herself, and stepped cautiously on the cold and dirty floor with her -slim, supple, bare feet. The boards of the floor creaked. Stepping -cautiously from one foot to the other she ran like a kitten the few -steps to the door and grasped the cold door handle. - -It seemed to her that something heavy was beating rhythmically -against all the walls of the room: it was her own heart, sinking -with alarm and terror and overflowing with love. - -She opened the door and stepped across the threshold and onto the -cold, damp earthen floor of the passage. The cold she felt refreshed -her. With her bare feet she touched a sleeping man, stepped over -him, and opened the door into the part of the hut where Prince -Andrew lay. It was dark in there. In the farthest corner, on a bench -beside a bed on which something was lying, stood a tallow candle -with a long, thick, and smoldering wick. - -From the moment she had been told that of Prince Andrew's wound -and his presence there, Natasha had resolved to see him. She did not -know why she had to, she knew the meeting would be painful, but felt -the more convinced that it was necessary. - -All day she had lived only in hope of seeing him that night. But now -that the moment had come she was filled with dread of what she might -see. How was he maimed? What was left of him? Was he like that -incessant moaning of the adjutant's? Yes, he was altogether like that. -In her imagination he was that terrible moaning personified. When -she saw an indistinct shape in the corner, and mistook his knees -raised under the quilt for his shoulders, she imagined a horrible body -there, and stood still in terror. But an irresistible impulse drew her -forward. She cautiously took one step and then another, and found -herself in the middle of a small room containing baggage. Another man- -Timokhin--was lying in a corner on the benches beneath the icons, -and two others--the doctor and a valet--lay on the floor. - -The valet sat up and whispered something. Timokhin, kept awake by -the pain in his wounded leg, gazed with wide-open eyes at this strange -apparition of a girl in a white chemise, dressing jacket, and -nightcap. The valet's sleepy, frightened exclamation, "What do you -want? What's the matter?" made Natasha approach more swiftly to what -was lying in the corner. Horribly unlike a man as that body looked, -she must see him. She passed the valet, the snuff fell from the candle -wick, and she saw Prince Andrew clearly with his arms outside the -quilt, and such as she had always seen him. - -He was the same as ever, but the feverish color of his face, his -glittering eyes rapturously turned toward her, and especially his -neck, delicate as a child's, revealed by the turn-down collar of his -shirt, gave him a peculiarly innocent, childlike look, such as she had -never seen on him before. She went up to him and with a swift, -flexible, youthful movement dropped on her knees. - -He smiled and held out his hand to her. - - - - - -CHAPTER XXXII - - -Seven days had passed since Prince Andrew found himself in the -ambulance station on the field of Borodino. His feverish state and the -inflammation of his bowels, which were injured, were in the doctor's - -opinion sure to carry him off. But on the seventh day he ate with -pleasure a piece of bread with some tea, and the doctor noticed that -his temperature was lower. He had regained consciousness that morning. -The first night after they left Moscow had been fairly warm and he had -remained in the caleche, but at Mytishchi the wounded man himself -asked to be taken out and given some tea. The pain caused by his -removal into the hut had made him groan aloud and again lose -consciousness. When he had been placed on his camp bed he lay for a -long time motionless with closed eyes. Then he opened them and -whispered softly: "And the tea?" His remembering such a small detail -of everyday life astonished the doctor. He felt Prince Andrew's pulse, -and to his surprise and dissatisfaction found it had improved. He -was dissatisfied because he knew by experience that if his patient did -not die now, he would do so a little later with greater suffering. -Timokhin, the red-nosed major of Prince Andrew's regiment, had -joined him in Moscow and was being taken along with him, having been -wounded in the leg at the battle of Borodino. They were accompanied by -a doctor, Prince Andrew's valet, his coachman, and two orderlies. - -They gave Prince Andrew some tea. He drank it eagerly, looking -with feverish eyes at the door in front of him as if trying to -understand and remember something. - -"I don't want any more. Is Timokhin here?" he asked. - -Timokhin crept along the bench to him. - -"I am here, your excellency." - -"How's your wound?" - -"Mine, sir? All right. But how about you?" - -Prince Andrew again pondered as if trying to remember something. - -"Couldn't one get a book?" he asked. - -"What book?" - -"The Gospels. I haven't one." - -The doctor promised to procure it for him and began to ask how he -was feeling. Prince Andrew answered all his questions reluctantly -but reasonably, and then said he wanted a bolster placed under him -as he was uncomfortable and in great pain. The doctor and valet lifted -the cloak with which he was covered and, making wry faces at the -noisome smell of mortifying flesh that came from the wound, began -examining that dreadful place. The doctor was very much displeased -about something and made a change in the dressings, turning the -wounded man over so that he groaned again and grew unconscious and -delirious from the agony. He kept asking them to get him the book -and put it under him. - -"What trouble would it be to you?" he said. "I have not got one. -Please get it for me and put it under for a moment," he pleaded in a -piteous voice. - -The doctor went into the passage to wash his hands. - -"You fellows have no conscience," said he to the valet who was -pouring water over his hands. "For just one moment I didn't look after -you... It's such pain, you know, that I wonder how he can bear it." - -"By the Lord Jesus Christ, I thought we had put something under -him!" said the valet. - -The first time Prince Andrew understood where he was and what was -the matter with him and remembered being wounded and how was when he -asked to be carried into the hut after his caleche had stopped at -Mytishchi. After growing confused from pain while being carried into -the hut he again regained consciousness, and while drinking tea once -more recalled all that had happened to him, and above all vividly -remembered the moment at the ambulance station when, at the sight of -the sufferings of a man he disliked, those new thoughts had come to -him which promised him happiness. And those thoughts, though now vague -and indefinite, again possessed his soul. He remembered that he had -now a new source of happiness and that this happiness had something to -do with the Gospels. That was why he asked for a copy of them. The -uncomfortable position in which they had put him and turned him over -again confused his thoughts, and when he came to himself a third -time it was in the complete stillness of the night. Everybody near him -was sleeping. A cricket chirped from across the passage; someone was -shouting and singing in the street; cockroaches rustled on the -table, on the icons, and on the walls, and a big fly flopped at the -head of the bed and around the candle beside him, the wick of which -was charred and had shaped itself like a mushroom. - -His mind was not in a normal state. A healthy man usually thinks of, -feels, and remembers innumerable things simultaneously, but has the -power and will to select one sequence of thoughts or events on which -to fix his whole attention. A healthy man can tear himself away from -the deepest reflections to say a civil word to someone who comes in -and can then return again to his own thoughts. But Prince Andrew's -mind was not in a normal state in that respect. All the powers of -his mind were more active and clearer than ever, but they acted -apart from his will. Most diverse thoughts and images occupied him -simultaneously. At times his brain suddenly began to work with a -vigor, clearness, and depth it had never reached when he was in -health, but suddenly in the midst of its work it would turn to some -unexpected idea and he had not the strength to turn it back again. - -"Yes, a new happiness was revealed to me of which man cannot be -deprived," he thought as he lay in the semi-darkness of the quiet hut, -gazing fixedly before him with feverish wide open eyes. "A happiness -lying beyond material forces, outside the material influences that act -on man--a happiness of the soul alone, the happiness of loving. -Every man can understand it, but to conceive it and enjoin it was -possible only for God. But how did God enjoin that law? And why was -the Son...?" - -And suddenly the sequence of these thoughts broke off, and Prince -Andrew heard (without knowing whether it was a delusion or reality) -a soft whispering voice incessantly and rhythmically repeating -"piti-piti-piti," and then "titi," and then again "piti-piti-piti," -and "ti-ti" once more. At the same time he felt that above his face, -above the very middle of it, some strange airy structure was being -erected out of slender needles or splinters, to the sound of this -whispered music. He felt that he had to balance carefully (though it -was difficult) so that this airy structure should not collapse; but -nevertheless it kept collapsing and again slowly rising to the sound -of whispered rhythmic music--"it stretches, stretches, spreading out -and stretching," said Prince Andrew to himself. While listening to -this whispering and feeling the sensation of this drawing out and -the construction of this edifice of needles, he also saw by glimpses a -red halo round the candle, and heard the rustle of the cockroaches and -the buzzing of the fly that flopped against his pillow and his face. -Each time the fly touched his face it gave him a burning sensation and -yet to his surprise it did not destroy the structure, though it -knocked against the very region of his face where it was rising. But -besides this there was something else of importance. It was -something white by the door--the statue of a sphinx, which also -oppressed him. - -"But perhaps that's my shirt on the table," he thought, "and -that's my legs, and that is the door, but why is it always -stretching and drawing itself out, and 'piti-piti-piti' and 'ti-ti' -and 'piti-piti-piti'...? That's enough, please leave off!" Prince -Andrew painfully entreated someone. And suddenly thoughts and feelings -again swam to the surface of his mind with peculiar clearness and -force. - -"Yes--love," he thought again quite clearly. "But not love which -loves for something, for some quality, for some purpose, or for some -reason, but the love which I--while dying--first experienced when I -saw my enemy and yet loved him. I experienced that feeling of love -which is the very essence of the soul and does not require an -object. Now again I feel that bliss. To love one's neighbors, to -love one's enemies, to love everything, to love God in all His -manifestations. It is possible to love someone dear to you with -human love, but an enemy can only be loved by divine love. That is why -I experienced such joy when I felt that I loved that man. What has -become of him? Is he alive?... - -"When loving with human love one may pass from love to hatred, but -divine love cannot change. No, neither death nor anything else can -destroy it. It is the very essence of the soul. Yet how many people -have I hated in my life? And of them all, I loved and hated none as -I did her." And he vividly pictured to himself Natasha, not as he -had done in the past with nothing but her charms which gave him -delight, but for the first time picturing to himself her soul. And -he understood her feelings, her sufferings, shame, and remorse. He now -understood for the first time all the cruelty of his rejection of her, -the cruelty of his rupture with her. "If only it were possible for -me to see her once more! Just once, looking into those eyes to say..." - - -"Piti-piti-piti and ti-ti and piti-piti-piti boom!" flopped the -fly... And his attention was suddenly carried into another world, a -world of reality and delirium in which something particular was -happening. In that world some structure was still being erected and -did not fall, something was still stretching out, and the candle -with its red halo was still burning, and the same shirtlike sphinx lay -near the door; but besides all this something creaked, there was a -whiff of fresh air, and a new white sphinx appeared, standing at the -door. And that sphinx had the pale face and shining eyes of the very -Natasha of whom he had just been thinking. - -"Oh, how oppressive this continual delirium is," thought Prince -Andrew, trying to drive that face from his imagination. But the face -remained before him with the force of reality and drew nearer. -Prince Andrew wished to return that former world of pure thought, -but he could not, and delirium drew him back into its domain. The soft -whispering voice continued its rhythmic murmur, something oppressed -him and stretched out, and the strange face was before him. Prince -Andrew collected all his strength in an effort to recover his -senses, he moved a little, and suddenly there was a ringing in his -ears, a dimness in his eyes, and like a man plunged into water he lost -consciousness. When he came to himself, Natasha, that same living -Natasha whom of all people he most longed to love with this new pure -divine love that had been revealed to him, was kneeling before him. He -realized that it was the real living Natasha, and he was not surprised -but quietly happy. Natasha, motionless on her knees (she was unable to -stir), with frightened eyes riveted on him, was restraining her -sobs. Her face was pale and rigid. Only in the lower part of it -something quivered. - -Prince Andrew sighed with relief, smiled, and held out his hand. - -"You?" he said. "How fortunate!" - -With a rapid but careful movement Natasha drew nearer to him on -her knees and, taking his hand carefully, bent her face over it and -began kissing it, just touching it lightly with her lips. - -"Forgive me!" she whispered, raising her head and glancing at him. -"Forgive me!" - -"I love you," said Prince Andrew. - -"Forgive...!" - -"Forgive what?" he asked. - -"Forgive me for what I ha-ve do-ne!" faltered Natasha in a -scarcely audible, broken whisper, and began kissing his hand more -rapidly, just touching it with her lips. - -"I love you more, better than before," said Prince Andrew, lifting -her face with his hand so as to look into her eyes. - -Those eyes, filled with happy tears, gazed at him timidly, -compassionately, and with joyous love. Natasha's thin pale face, -with its swollen lips, was more than plain--it was dreadful. But -Prince Andrew did not see that, he saw her shining eyes which were -beautiful. They heard the sound of voices behind them. - -Peter the valet, who was now wide awake, had roused the doctor. -Timokhin, who had not slept at all because of the pain in his leg, had -long been watching all that was going on, carefully covering his -bare body with the sheet as he huddled up on his bench. - -"What's this?" said the doctor, rising from his bed. "Please go -away, madam!" - -At that moment a maid sent by the countess, who had noticed her -daughter's absence, knocked at the door. - -Like a somnambulist aroused from her sleep Natasha went out of the -room and, returning to her hut, fell sobbing on her bed. - - -From that time, during all the rest of the Rostovs' journey, at -every halting place and wherever they spent a night, Natasha never -left the wounded Bolkonski, and the doctor had to admit that he had -not expected from a young girl either such firmness or such skill in -nursing a wounded man. - -Dreadful as the countess imagined it would be should Prince Andrew -die in her daughter's arms during the journey--as, judging by what the -doctor said, it seemed might easily happen--she could not oppose -Natasha. Though with the intimacy now established between the -wounded man and Natasha the thought occurred that should he recover -their former engagement would be renewed, no one--least of all Natasha -and Prince Andrew--spoke of this: the unsettled question of life and -death, which hung not only over Bolkonski but over all Russia, shut -out all other considerations. - - - - - -CHAPTER XXXIII - - -On the third of September Pierre awoke late. His head was aching, -the clothes in which he had slept without undressing felt -uncomfortable on his body, and his mind had a dim consciousness of -something shameful he had done the day before. That something shameful -was his yesterday's conversation with Captain Ramballe. - -It was eleven by the clock, but it seemed peculiarly dark out of -doors. Pierre rose, rubbed his eyes, and seeing the pistol with an -engraved stock which Gerasim had replaced on the writing table, he -remembered where he was and what lay before him that very day. - -"Am I not too late?" he thought. "No, probably he won't make his -entry into Moscow before noon." - -Pierre did not allow himself to reflect on what lay before him, -but hastened to act. - -After arranging his clothes, he took the pistol and was about to -go out. But it then occurred to him for the first time that he -certainly could not carry the weapon in his hand through the -streets. It was difficult to hide such a big pistol even under his -wide coat. He could not carry it unnoticed in his belt or under his -arm. Besides, it had been discharged, and he had not had time to -reload it. "No matter, dagger will do," he said to himself, though -when planning his design he had more than once come to the -conclusion that the chief mistake made by the student in 1809 had been -to try to kill Napoleon with a dagger. But as his chief aim -consisted not in carrying out his design, but in proving to himself -that he would not abandon his intention and was doing all he could -to achieve it, Pierre hastily took the blunt jagged dagger in a -green sheath which he had bought at the Sukharev market with the -pistol, and hid it under his waistcoat. - -Having tied a girdle over his coat and pulled his cap low on his -head, Pierre went down the corridor, trying to avoid making a noise or -meeting the captain, and passed out into the street. - -The conflagration, at which he had looked with so much -indifference the evening before, had greatly increased during the -night. Moscow was on fire in several places. The buildings in Carriage -Row, across the river, in the Bazaar and the Povarskoy, as well as the -barges on the Moskva River and the timber yards by the Dorogomilov -Bridge, were all ablaze. - -Pierre's way led through side streets to the Povarskoy and from -there to the church of St. Nicholas on the Arbat, where he had long -before decided that the deed should should be done. The gates of -most of the houses were locked and the shutters up. The streets and -lanes were deserted. The air was full of smoke and the smell of -burning. Now and then he met Russians with anxious and timid faces, -and Frenchmen with an air not of the city but of the camp, walking -in the middle of the streets. Both the Russians and the French -looked at Pierre with surprise. Besides his height and stoutness, -and the strange morose look of suffering in his face and whole figure, -the Russians stared at Pierre because they could not make out to -what class he could belong. The French followed him with -astonishment in their eyes chiefly because Pierre, unlike all the -other Russians who gazed at the French with fear and curiosity, paid -no attention to them. At the gate of one house three Frenchmen, who -were explaining something to some Russians who did not understand -them, stopped Pierre asking if he did not know French. - -Pierre shook his head and went on. In another side street a sentinel -standing beside a green caisson shouted at him, but only when the -shout was threateningly repeated and he heard the click of the man's -musket as he raised it did Pierre understand that he had to pass on -the other side of the street. He heard nothing and saw nothing of what -went on around him. He carried his resolution within himself in terror -and haste, like something dreadful and alien to him, for, after the -previous night's experience, he was afraid of losing it. But he was -not destined to bring his mood safely to his destination. And even had -he not been hindered by anything on the way, his intention could not -now have been carried out, for Napoleon had passed the Arbat more than -four hours previously on his way from the Dorogomilov suburb to the -Kremlin, and was now sitting in a very gloomy frame of mind in a royal -study in the Kremlin, giving detailed and exact orders as to -measures to be taken immediately to extinguish the fire, to prevent -looting, and to reassure the inhabitants. But Pierre did not know -this; he was entirely absorbed in what lay before him, and was -tortured--as those are who obstinately undertake a task that is -impossible for them not because of its difficulty but because of its -incompatibility with their natures--by the fear of weakening at the -decisive moment and so losing his self-esteem. - -Though he heard and saw nothing around him he found his way by -instinct and did not go wrong in the side streets that led to the -Povarskoy. - -As Pierre approached that street the smoke became denser and denser- -he even felt the heat of the fire. Occasionally curly tongues of flame -rose from under the roofs of the houses. He met more people in the -streets and they were more excited. But Pierre, though he felt that -something unusual was happening around him, did not realize that he -was approaching the fire. As he was going along a foot path across a -wide-open space adjoining the Povarskoy on one side and the gardens of -Prince Gruzinski's house on the other, Pierre suddenly heard the -desperate weeping of a woman close to him. He stopped as if -awakening from a dream and lifted his head. - -By the side of the path, on the dusty dry grass, all sorts of -household goods lay in a heap: featherbeds, a samovar, icons, and -trunks. On the ground, beside the trunks, sat a thin woman no longer -young, with long, prominent upper teeth, and wearing a black cloak and -cap. This woman, swaying to and fro and muttering something, was -choking with sobs. Two girls of about ten and twelve, dressed in dirty -short frocks and cloaks, were staring at their mother with a look of -stupefaction on their pale frightened faces. The youngest child, a boy -of about seven, who wore an overcoat and an immense cap evidently -not his own, was crying in his old nurse's arms. A dirty, barefooted -maid was sitting on a trunk, and, having undone her pale-colored -plait, was pulling it straight and sniffing at her singed hair. The -woman's husband, a short, round-shouldered man in the undress -uniform of a civilian official, with sausage-shaped whiskers and -showing under his square-set cap the hair smoothly brushed forward -over his temples, with expressionless face was moving the trunks, -which were placed one on another, and was dragging some garments -from under them. - -As soon as she saw Pierre, the woman almost threw herself at his -feet. - -"Dear people, good Christians, save me, help me, dear friends... -help us, somebody," she muttered between her sobs. "My girl... My -daughter! My youngest daughter is left behind. She's burned! Ooh! -Was it for this I nursed you.... Ooh!" - -"Don't, Mary Nikolievna!" said her husband to her in a low voice, -evidently only to justify himself before the stranger. "Sister must -have taken her, or else where can she be?" he added. - -"Monster! Villain!" shouted the woman angrily, suddenly ceasing to -weep. "You have no heart, you don't feel for your own child! Another -man would have rescued her from the fire. But this is a monster and -neither a man nor a father! You, honored sir, are a noble man," she -went on, addressing Pierre rapidly between her sobs. "The fire broke -out alongside, and blew our way, the maid called out 'Fire!' and we -rushed to collect our things. We ran out just as we were.... This is -what we have brought away.... The icons, and my dowry bed, all the -rest is lost. We seized the children. But not Katie! Ooh! O -Lord!..." and again she began to sob. "My child, my dear one! -Burned, burned!" - -"But where was she left?" asked Pierre. - -From the expression of his animated face the woman saw that this man -might help her. - -"Oh, dear sir!" she cried, seizing him by the legs. "My -benefactor, set my heart at ease.... Aniska, go, you horrid girl, show -him the way!" she cried to the maid, angrily opening her mouth and -still farther exposing her long teeth. - -"Show me the way, show me, I... I'll do it," gasped Pierre rapidly. - -The dirty maidservant stepped from behind the trunk, put up her -plait, sighed, and went on her short, bare feet along the path. Pierre -felt as if he had come back to life after a heavy swoon. He held his -head higher, his eyes shone with the light of life, and with swift -steps he followed the maid, overtook her, and came out on the -Povarskoy. The whole street was full of clouds of black smoke. Tongues -of flame here and there broke through that cloud. A great number of -people crowded in front of the conflagration. In the middle of the -street stood a French general saying something to those around him. -Pierre, accompanied by the maid, was advancing to the spot where the -general stood, but the French soldiers stopped him. - -"On ne passe pas!"* cried a voice. - - -*"You can't pass! - - -"This way, uncle," cried the girl. "We'll pass through the side -street, by the Nikulins'!" - -Pierre turned back, giving a spring now and then to keep up with -her. She ran across the street, turned down a side street to the left, -and, passing three houses, turned into a yard on the right. - -"It's here, close by," said she and, running across the yard, opened -a gate in a wooden fence and, stopping, pointed out to him a small -wooden wing of the house, which was burning brightly and fiercely. One -of its sides had fallen in, another was on fire, and bright flames -issued from the openings of the windows and from under the roof. - -As Pierre passed through the fence gate, he was enveloped by hot air -and involuntarily stopped. - -"Which is it? Which is your house?" he asked. - -"Ooh!" wailed the girl, pointing to the wing. "That's it, that was -our lodging. You've burned to death, our treasure, Katie, my -precious little missy! Ooh!" lamented Aniska, who at the sight of -the fire felt that she too must give expression to her feelings. - -Pierre rushed to the wing, but the heat was so great that he -involuntarily passed round in a curve and came upon the large house -that was as yet burning only at one end, just below the roof, and -around which swarmed a crowd of Frenchmen. At first Pierre did not -realize what these men, who were dragging something out, were about; -but seeing before him a Frenchman hitting a peasant with a blunt saber -and trying to take from him a fox-fur coat, he vaguely understood that -looting was going on there, but he had no time to dwell on that idea. - -The sounds of crackling and the din of falling walls and ceilings, -the whistle and hiss of the flames, the excited shouts of the -people, and the sight of the swaying smoke, now gathering into thick -black clouds and now soaring up with glittering sparks, with here -and there dense sheaves of flame (now red and now like golden fish -scales creeping along the walls), and the heat and smoke and -rapidity of motion, produced on Pierre the usual animating effects -of a conflagration. It had a peculiarly strong effect on him because -at the sight of the fire he felt himself suddenly freed from the ideas -that had weighed him down. He felt young, bright, adroit, and -resolute. He ran round to the other side of the lodge and was about to -dash into that part of it which was still standing, when just above -his head he heard several voices shouting and then a cracking sound -and the ring of something heavy falling close beside him. - -Pierre looked up and saw at a window of the large house some -Frenchmen who had just thrown out the drawer of a chest, filled with -metal articles. Other French soldiers standing below went up to the -drawer. - -"What does this fellow want?" shouted one of them referring to -Pierre. - -"There's a child in that house. Haven't you seen a child?" cried -Pierre. - -"What's he talking about? Get along!" said several voices, and one -of the soldiers, evidently afraid that Pierre might want to take -from them some of the plate and bronzes that were in the drawer, moved -threateningly toward him. - -"A child?" shouted a Frenchman from above. "I did hear something -squealing in the garden. Perhaps it's his brat that the fellow is -looking for. After all, one must be human, you know...." - -"Where is it? Where?" said Pierre. - -"There! There!" shouted the Frenchman at the window, pointing to the -garden at the back of the house. "Wait a bit--I'm coming down." - -And a minute or two later the Frenchman, a black-eyed fellow with -a spot on his cheek, in shirt sleeves, really did jump out of a window -on the ground floor, and clapping Pierre on the shoulder ran with -him into the garden. - -"Hurry up, you others!" he called out to his comrades. "It's getting -hot." - -When they reached a gravel path behind the house the Frenchman -pulled Pierre by the arm and pointed to a round, graveled space -where a three-year-old girl in a pink dress was lying under a seat. - -"There is your child! Oh, a girl, so much the better!" said the -Frenchman. "Good-by, Fatty. We must be human, we are all mortal you -know!" and the Frenchman with the spot on his cheek ran back to his -comrades. - -Breathless with joy, Pierre ran to the little girl and was going -to take her in his arms. But seeing a stranger the sickly, -scrofulous-looking child, unattractively like her mother, began to -yell and run away. Pierre, however, seized her and lifted her in his -arms. She screamed desperately and angrily and tried with her little -hands to pull Pierre's hands away and to bite them with her slobbering -mouth. Pierre was seized by a sense of horror and repulsion such as he -had experienced when touching some nasty little animal. But he made an -effort not to throw the child down and ran with her to the large -house. It was now, however, impossible to get back the way he had -come; the maid, Aniska, was no longer there, and Pierre with a feeling -of pity and disgust pressed the wet, painfully sobbing child to -himself as tenderly as he could and ran with her through the garden -seeking another way out. - - - - - -CHAPTER XXXIV - - -Having run through different yards and side streets, Pierre got back -with his little burden to the Gruzinski garden at the corner of the -Povarskoy. He did not at first recognize the place from which he had -set out to look for the child, so crowded was it now with people and -goods that had been dragged out of the houses. Besides Russian -families who had taken refuge here from the fire with their -belongings, there were several French soldiers in a variety of -clothing. Pierre took no notice of them. He hurried to find the family -of that civil servant in order to restore the daughter to her mother -and go to save someone else. Pierre felt that he had still much to -do and to do quickly. Glowing with the heat and from running, he -felt at that moment more strongly than ever the sense of youth, -animation, and determination that had come on him when he ran to -save the child. She had now become quiet and, clinging with her little -hands to Pierre's coat, sat on his arm gazing about her like some -little wild animal. He glanced at her occasionally with a slight -smile. He fancied he saw something pathetically innocent in that -frightened, sickly little face. - -He did not find the civil servant or his wife where he had left -them. He walked among the crowd with rapid steps, scanning the various -faces he met. Involuntarily he noticed a Georgian or Armenian family -consisting of a very handsome old man of Oriental type, wearing a new, -cloth-covered, sheepskin coat and new boots, an old woman of similar -type, and a young woman. That very young woman seemed to Pierre the -perfection of Oriental beauty, with her sharply outlined, arched, -black eyebrows and the extraordinarily soft, bright color of her long, -beautiful, expressionless face. Amid the scattered property and the -crowd on the open space, she, in her rich satin cloak with a bright -lilac shawl on her head, suggested a delicate exotic plant thrown -out onto the snow. She was sitting on some bundles a little behind the -old woman, and looked from under her long lashes with motionless, -large, almond-shaped eyes at the ground before her. Evidently she -was aware of her beauty and fearful because of it. Her face struck -Pierre and, hurrying along by the fence, he turned several times to -look at her. When he had reached the fence, still without finding -those he sought, he stopped and looked about him. - -With the child in his arms his figure was now more conspicuous -than before, and a group of Russians, both men and women, gathered -about him. - -"Have you lost anyone, my dear fellow? You're of the gentry -yourself, aren't you? Whose child is it?" they asked him. - -Pierre replied that the child belonged to a woman in a black coat -who had been sitting there with her other children, and he asked -whether anyone knew where she had gone. - -"Why, that must be the Anferovs," said an old deacon, addressing a -pockmarked peasant woman. "Lord have mercy, Lord have mercy!" he added -in his customary bass. - -"The Anferovs? No," said the woman. "They left in the morning. -That must be either Mary Nikolievna's or the Ivanovs'!" - -"He says 'a woman,' and Mary Nikolievna is a lady," remarked a house -serf. - -"Do you know her? She's thin, with long teeth," said Pierre. - -"That's Mary Nikolievna! They went inside the garden when these -wolves swooped down," said the woman, pointing to the French soldiers. - -"O Lord, have mercy!" added the deacon. - -"Go over that way, they're there. It's she! She kept on lamenting -and crying," continued the woman. "It's she. Here, this way!" - -But Pierre was not listening to the woman. He had for some seconds -been intently watching what was going on a few steps away. He was -looking at the Armenian family and at two French soldiers who had gone -up to them. One of these, a nimble little man, was wearing a blue coat -tied round the waist with a rope. He had a nightcap on his head and -his feet were bare. The other, whose appearance particularly struck -Pierre, was a long, lank, round-shouldered, fair-haired man, slow in -his movements and with an idiotic expression of face. He wore a -woman's loose gown of frieze, blue trousers, and large torn Hessian -boots. The little barefooted Frenchman in the blue coat went up to the -Armenians and, saying something, immediately seized the old man by his -legs and the old man at once began pulling off his boots. The other in -the frieze gown stopped in front of the beautiful Armenian girl and -with his hands in his pockets stood staring at her, motionless and -silent. - -"Here, take the child!" said Pierre peremptorily and hurriedly to -the woman, handing the little girl to her. "Give her back to them, -give her back!" he almost shouted, putting the child, who began -screaming, on the ground, and again looking at the Frenchman and the -Armenian family. - -The old man was already sitting barefoot. The little Frenchman had -secured his second boot and was slapping one boot against the other. -The old man was saying something in a voice broken by sobs, but Pierre -caught but a glimpse of this, his whole attention was directed to -the Frenchman in the frieze gown who meanwhile, swaying slowly from -side to side, had drawn nearer to the young woman and taking his hands -from his pockets had seized her by the neck. - -The beautiful Armenian still sat motionless and in the same -attitude, with her long lashes drooping as if she did not see or -feel what the soldier was doing to her. - -While Pierre was running the few steps that separated him from the -Frenchman, the tall marauder in the frieze gown was already tearing -from her neck the necklace the young Armenian was wearing, and the -young woman, clutching at her neck, screamed piercingly. - -"Let that woman alone!" exclaimed Pierre hoarsely in a furious -voice, seizing the soldier by his round shoulders and throwing him -aside. - -The soldier fell, got up, and ran away. But his comrade, throwing -down the boots and drawing his sword, moved threateningly toward -Pierre. - -"Voyons, Pas de betises!"* he cried. - - -*"Look here, no nonsense!" - - -Pierre was in such a transport of rage that he remembered nothing -and his strength increased tenfold. He rushed at the barefooted -Frenchman and, before the latter had time to draw his sword, knocked -him off his feet and hammered him with his fists. Shouts of approval -were heard from the crowd around, and at the same moment a mounted -patrol of French Uhlans appeared from round the corner. The Uhlans -came up at a trot to Pierre and the Frenchman and surrounded them. -Pierre remembered nothing of what happened after that. He only -remembered beating someone and being beaten and finally feeling that -his hands were bound and that a crowd of French soldiers stood -around him and were searching him. - -"Lieutenant, he has a dagger," were the first words Pierre -understood. - -"Ah, a weapon?" said the officer and turned to the barefooted -soldier who had been arrested with Pierre. "All right, you can tell -all about it at the court-martial." Then he turned to Pierre. "Do -you speak French?" - -Pierre looked around him with bloodshot eyes and did not reply. -His face probably looked very terrible, for the officer said something -in a whisper and four more Uhlans left the ranks and placed themselves -on both sides of Pierre. - -"Do you speak French?" the officer asked again, keeping at a -distance from Pierre. "Call the interpreter." - -A little man in Russian civilian clothes rode out from the ranks, -and by his clothes and manner of speaking Pierre at once knew him to -be a French salesman from one of the Moscow shops. - -"He does not look like a common man," said the interpreter, after -a searching look at Pierre. - -"Ah, he looks very much like an incendiary," remarked the officer. -"And ask him who he is," he added. - -"Who are you?" asked the interpreter in poor Russian. "You must -answer the chief." - -"I will not tell you who I am. I am your prisoner--take me!" -Pierre suddenly replied in French. - -"Ah, ah!" muttered the officer with a frown. "Well then, march!" - -A crowd had collected round the Uhlans. Nearest to Pierre stood -the pockmarked peasant woman with the little girl, and when the patrol -started she moved forward. - -"Where are they taking you to, you poor dear?" said she. "And the -little girl, the little girl, what am I to do with her if she's not -theirs?" said the woman. - -"What does that woman want?" asked the officer. - -Pierre was as if intoxicated. His elation increased at the sight -of the little girl he had saved. - -"What does she want?" he murmured. "She is bringing me my daughter -whom I have just saved from the flames," said he. "Good-by!" And -without knowing how this aimless lie had escaped him, he went along -with resolute and triumphant steps between the French soldiers. - -The French patrol was one of those sent out through the various -streets of Moscow by Durosnel's order to put a stop to the pillage, -and especially to catch the incendiaries who, according to the general -opinion which had that day originated among the higher French -officers, were the cause of the conflagrations. After marching through -a number of streets the patrol arrested five more Russian suspects: -a small shopkeeper, two seminary students, a peasant, and a house -serf, besides several looters. But of all these various suspected -characters, Pierre was considered to be the most suspicious of all. -When they had all been brought for the night to a large house on the -Zubov Rampart that was being used as a guardhouse, Pierre was placed -apart under strict guard. - - - - - -BOOK TWELVE: 1812 - - - - - -CHAPTER I - - -In Petersburg at that time a complicated struggle was being -carried on with greater heat than ever in the highest circles, between -the parties of Rumyantsev, the French, Marya Fedorovna, the Tsarevich, -and others, drowned as usual by the buzzing of the court drones. But -the calm, luxurious life of Petersburg, concerned only about -phantoms and reflections of real life, went on in its old way and made -it hard, except by a great effort, to realize the danger and the -difficult position of the Russian people. There were the same -receptions and balls, the same French theater, the same court -interests and service interests and intrigues as usual. Only in the -very highest circles were attempts made to keep in mind the -difficulties of the actual position. Stories were whispered of how -differently the two Empresses behaved in these difficult -circumstances. The Empress Marya, concerned for the welfare of the -charitable and educational institutions under her patronage, had given -directions that they should all be removed to Kazan, and the things -belonging to these institutions had already been packed up. The -Empress Elisabeth, however, when asked what instructions she would -be pleased to give--with her characteristic Russian patriotism had -replied that she could give no directions about state institutions for -that was the affair of the sovereign, but as far as she personally was -concerned she would be the last to quit Petersburg. - -At Anna Pavlovna's on the twenty-sixth of August, the very day of -the battle of Borodino, there was a soiree, the chief feature of which -was to be the reading of a letter from His Lordship the Bishop when -sending the Emperor an icon of the Venerable Sergius. It was -regarded as a model of ecclesiastical, patriotic eloquence. Prince -Vasili himself, famed for his elocution, was to read it. (He used to -read at the Empress'.) The art of his reading was supposed to lie in -rolling out the words, quite independently of their meaning, in a loud -and singsong voice alternating between a despairing wail and a -tender murmur, so that the wail fell quite at random on one word and -the murmur on another. This reading, as was always the case at Anna -Pavlovna's soirees, had a political significance. That evening she -expected several important personages who had to be made ashamed of -their visits to the French theater and aroused to a patriotic -temper. A good many people had already arrived, but Anna Pavlovna, not -yet seeing all those whom she wanted in her drawing room, did not -let the reading begin but wound up the springs of a general -conversation. - -The news of the day in Petersburg was the illness of Countess -Bezukhova. She had fallen ill unexpectedly a few days previously, -had missed several gatherings of which she was usually ornament, and -was said to be receiving no one, and instead of the celebrated -Petersburg doctors who usually attended her had entrusted herself to -some Italian doctor who was treating her in some new and unusual way. - -They all knew very well that the enchanting countess' illness -arose from an inconvenience resulting from marrying two husbands at -the same time, and that the Italian's cure consisted in removing -such inconvenience; but in Anna Pavlovna's presence no one dared to -think of this or even appear to know it. - -"They say the poor countess is very ill. The doctor says it is -angina pectoris." - -"Angina? Oh, that's a terrible illness!" - -"They say that the rivals are reconciled, thanks to the angina..." -and the word angina was repeated with great satisfaction. - -"The count is pathetic, they say. He cried like a child when the -doctor told him the case was dangerous." - -"Oh, it would be a terrible loss, she is an enchanting woman." - -"You are speaking of the poor countess?" said Anna Pavlovna, -coming up just then. "I sent to ask for news, and hear that she is a -little better. Oh, she is certainly the most charming woman in the -world," she went on, with a smile at her own enthusiasm. "We belong to -different camps, but that does not prevent my esteeming her as she -deserves. She is very unfortunate!" added Anna Pavlovna. - -Supposing that by these words Anna Pavlovna was somewhat lifting the -veil from the secret of the countess' malady, an unwary young man -ventured to express surprise that well known doctors had not been -called in and that the countess was being attended by a charlatan -who might employ dangerous remedies. - -"Your information maybe better than mine," Anna Pavlovna suddenly -and venomously retorted on the inexperienced young man, "but I know on -good authority that this doctor is a very learned and able man. He -is private physician to the Queen of Spain." - -And having thus demolished the young man, Anna Pavlovna turned to -another group where Bilibin was talking about the Austrians: having -wrinkled up his face he was evidently preparing to smooth it out again -and utter one of his mots. - -"I think it is delightful," he said, referring to a diplomatic -note that had been sent to Vienna with some Austrian banners -captured from the French by Wittgenstein, "the hero of Petropol" as he -was then called in Petersburg. - -"What? What's that?" asked Anna Pavlovna, securing silence for the -mot, which she had heard before. - -And Bilibin repeated the actual words of the diplomatic dispatch, -which he had himself composed. - -"The Emperor returns these Austrian banners," said Bilibin, -"friendly banners gone astray and found on a wrong path," and his brow -became smooth again. - -"Charming, charming!" observed Prince Vasili. - -"The path to Warsaw, perhaps," Prince Hippolyte remarked loudly -and unexpectedly. Everybody looked at him, understanding what he -meant. Prince Hippolyte himself glanced around with amused surprise. -He knew no more than the others what his words meant. During his -diplomatic career he had more than once noticed that such utterances -were received as very witty, and at every opportunity he uttered in -that way the first words that entered his head. "It may turn out -very well," he thought, "but if not, they'll know how to arrange -matters." And really, during the awkward silence that ensued, that -insufficiently patriotic person entered whom Anna Pavlovna had been -waiting for and wished to convert, and she, smiling and shaking a -finger at Hippolyte, invited Prince Vasili to the table and bringing -him two candles and the manuscript begged him to begin. Everyone -became silent. - - -"Most Gracious Sovereign and Emperor!" Prince Vasili sternly -declaimed, looking round at his audience as if to inquire whether -anyone had anything to say to the contrary. But no one said -anything. "Moscow, our ancient capital, the New Jerusalem, receives -her Christ"--he placed a sudden emphasis on the word her--"as a mother -receives her zealous sons into her arms, and through the gathering -mists, foreseeing the brilliant glory of thy rule, sings in -exultation, 'Hosanna, blessed is he that cometh!'" - - -Prince Vasili pronounced these last words in a tearful voice. - -Bilibin attentively examined his nails, and many of those present -appeared intimidated, as if asking in what they were to blame. Anna -Pavlovna whispered the next words in advance, like an old woman -muttering the prayer at Communion: "Let the bold and insolent -Goliath..." she whispered. - -Prince Vasili continued. - - -"Let the bold and insolent Goliath from the borders of France -encompass the realms of Russia with death-bearing terrors; humble -Faith, the sling of the Russian David, shall suddenly smite his head -in his blood-thirsty pride. This icon of the Venerable Sergius, the -servant of God and zealous champion of old of our country's weal, is -offered to Your Imperial Majesty. I grieve that my waning strength -prevents rejoicing in the sight of your most gracious presence. I -raise fervent prayers to Heaven that the Almighty may exalt the race -of the just, and mercifully fulfill the desires of Your Majesty." - - -"What force! What a style!" was uttered in approval both of reader -and of author. - -Animated by that address Anna Pavlovna's guests talked for a long -time of the state of the fatherland and offered various conjectures as -to the result of the battle to be fought in a few days. - -"You will see," said Anna Pavlovna, "that tomorrow, on the Emperor's -birthday, we shall receive news. I have a favorable presentiment!" - - - - - -CHAPTER II - - -Anna Pavlovna's presentiment was in fact fulfilled. Next day -during the service at the palace church in honor of the Emperor's -birthday, Prince Volkonski was called out of the church and received a -dispatch from Prince Kutuzov. It was Kutuzov's report, written from -Tatarinova on the day of the battle. Kutuzov wrote that the Russians -had not retreated a step, that the French losses were much heavier -than ours, and that he was writing in haste from the field of battle -before collecting full information. It followed that there must have -been a victory. And at once, without leaving the church, thanks were -rendered to the Creator for His help and for the victory. - -Anna Pavlovna's presentiment was justified, and all that morning a -joyously festive mood reigned in the city. Everyone believed the -victory to have been complete, and some even spoke of Napoleon's -having been captured, of his deposition, and of the choice of a new -ruler for France. - -It is very difficult for events to be reflected in their real -strength and completeness amid the conditions of court life and far -from the scene of action. General events involuntarily group -themselves around some particular incident. So now the courtiers' -pleasure was based as much on the fact that the news had arrived on -the Emperor's birthday as on the fact of the victory itself. It was -like a successfully arranged surprise. Mention was made in Kutuzov's -report of the Russian losses, among which figured the names of -Tuchkov, Bagration, and Kutaysov. In the Petersburg world this sad -side of the affair again involuntarily centered round a single -incident: Kutaysov's death. Everybody knew him, the Emperor liked him, -and he was young and interesting. That day everyone met with the -words: - -"What a wonderful coincidence! Just during the service. But what a -loss Kutaysov is! How sorry I am!" - -"What did I tell about Kutuzov?" Prince Vasili now said with a -prophet's pride. "I always said he was the only man capable of -defeating Napoleon." - -But next day no news arrived from the army and the public mood -grew anxious. The courtiers suffered because of the suffering the -suspense occasioned the Emperor. - -"Fancy the Emperor's position!" said they, and instead of -extolling Kutuzov as they had done the day before, they condemned -him as the cause of the Emperor's anxiety. That day Prince Vasili no -longer boasted of his protege Kutuzov, but remained silent when the -commander in chief was mentioned. Moreover, toward evening, as if -everything conspired to make Petersburg society anxious and uneasy, -a terrible piece of news was added. Countess Helene Bezukhova had -suddenly died of that terrible malady it had been so agreeable to -mention. Officially, at large gatherings, everyone said that -Countess Bezukhova had died of a terrible attack of angina pectoris, -but in intimate circles details were mentioned of how the private -physician of the Queen of Spain had prescribed small doses of a -certain drug to produce a certain effect; but Helene, tortured by -the fact that the old count suspected her and that her husband to whom -she had written (that wretched, profligate Pierre) had not replied, -had suddenly taken a very large dose of the drug, and had died in -agony before assistance could be rendered her. It was said that Prince -Vasili and the old count had turned upon the Italian, but the latter -had produced such letters from the unfortunate deceased that they -had immediately let the matter drop. - -Talk in general centered round three melancholy facts: the Emperor's -lack of news, the loss of Kutuzov, and the death of Helene. - -On the third day after Kutuzov's report a country gentleman -arrived from Moscow, and news of the surrender of Moscow to the French -spread through the whole town. This was terrible! What a position -for the Emperor to be in! Kutuzov was a traitor, and Prince Vasili -during the visits of condolence paid to him on the occasion of his -daughter's death said of Kutuzov, whom he had formerly praised (it was -excusable for him in his grief to forget what he had said), that it -was impossible to expect anything else from a blind and depraved old -man. - -"I only wonder that the fate of Russia could have been entrusted -to such a man." - -As long as this news remained unofficial it was possible to doubt -it, but the next day the following communication was received from -Count Rostopchin: - - -Prince Kutuzov's adjutant has brought me a letter in which he -demands police officers to guide the army to the Ryazan road. He -writes that he is regretfully abandoning Moscow. Sire! Kutuzov's -action decides the fate of the capital and of your empire! Russia will -shudder to learn of the abandonment of the city in which her greatness -is centered and in which lie the ashes of your ancestors! I shall -follow the army. I have had everything removed, and it only remains -for me to weep over the fate of my fatherland. - - -On receiving this dispatch the Emperor sent Prince Volkonski to -Kutuzov with the following rescript: - - -Prince Michael Ilarionovich! Since the twenty-ninth of August I have -received no communication from you, yet on the first of September I -received from the commander in chief of Moscow, via Yaroslavl, the sad -news that you, with the army, have decided to abandon Moscow. You -can yourself imagine the effect this news has had on me, and your -silence increases my astonishment. I am sending this by -Adjutant-General Prince Volkonski, to hear from you the situation of -the army and the reasons that have induced you to take this melancholy -decision. - - - - - -CHAPTER III - - -Nine days after the abandonment of Moscow, a messenger from -Kutuzov reached Petersburg with the official announcement of that -event. This messenger was Michaud, a Frenchman who did not know -Russian, but who was quoique etranger, russe de coeur et d'ame,* as he -said of himself. - - -*Though a foreigner, Russian in heart and soul. - - -The Emperor at once received this messenger in his study at the -palace on Stone Island. Michaud, who had never seen Moscow before -the campaign and who did not know Russian, yet felt deeply moved (as -he wrote) when he appeared before notre tres gracieux souverain* -with the news of the burning of Moscow, dont les flammes eclairaient -sa route.*[2] - - -*Our most gracious sovereign. - -*[2] Whose flames illumined his route. - - -Though the source of M. Michaud's chagrin must have been different -from that which caused Russians to grieve, he had such a sad face when -shown into the Emperor's study that the latter at once asked: - -"Have you brought me sad news, Colonel?" - -"Very sad, sire," replied Michaud, lowering his eyes with a sigh. -"The abandonment of Moscow." - -"Have they surrendered my ancient capital without a battle?" asked -the Emperor quickly, his face suddenly flushing. - -Michaud respectfully delivered the message Kutuzov had entrusted -to him, which was that it had been impossible to fight before -Moscow, and that as the only remaining choice was between losing the -army as well as Moscow, or losing Moscow alone, the field marshal -had to choose the latter. - -The Emperor listened in silence, not looking at Michaud. - -"Has the enemy entered the city?" he asked. - -"Yes, sire, and Moscow is now in ashes. I left it all in flames," -replied Michaud in a decided tone, but glancing at the Emperor he -was frightened by what he had done. - -The Emperor began to breathe heavily and rapidly, his lower lip -trembled, and tears instantly appeared in his fine blue eyes. - -But this lasted only a moment. He suddenly frowned, as if blaming -himself for his weakness, and raising his head addressed Michaud in -a firm voice: - -"I see, Colonel, from all that is happening, that Providence -requires great sacrifices of us... I am ready to submit myself in -all things to His will; but tell me, Michaud, how did you leave the -army when it saw my ancient capital abandoned without a battle? Did -you not notice discouragement?..." - -Seeing that his most gracious ruler was calm once more, Michaud also -grew calm, but was not immediately ready to reply to the Emperor's -direct and relevant question which required a direct answer. - -"Sire, will you allow me to speak frankly as befits a loyal -soldier?" he asked to gain time. - -"Colonel, I always require it," replied the Emperor. "Conceal -nothing from me, I wish to know absolutely how things are." - -"Sire!" said Michaud with a subtle, scarcely perceptible smile on -his lips, having now prepared a well-phrased reply, "sire, I left -the whole army, from its chiefs to the lowest soldier, without -exception in desperate and agonized terror..." - -"How is that?" the Emperor interrupted him, frowning sternly. "Would -misfortune make my Russians lose heart?... Never!" - -Michaud had only waited for this to bring out the phrase he had -prepared. - -"Sire," he said, with respectful playfulness, "they are only -afraid lest Your Majesty, in the goodness of your heart, should -allow yourself to be persuaded to make peace. They are burning for the -combat," declared this representative of the Russian nation, "and to -prove to Your Majesty by the sacrifice of their lives how devoted they -are...." - -"Ah!" said the Emperor reassured, and with a kindly gleam in his -eyes, he patted Michaud on the shoulder. "You set me at ease, -Colonel." - -He bent his head and was silent for some time. - -"Well, then, go back to the army," he said, drawing himself up to -his full height and addressing Michaud with a gracious and majestic -gesture, "and tell our brave men and all my good subjects wherever you -go that when I have not a soldier left I shall put myself at the -head of my beloved nobility and my good peasants and so use the last -resources of my empire. It still offers me more than my enemies -suppose," said the Emperor growing more and more animated; "but should -it ever be ordained by Divine Providence," he continued, raising to -heaven his fine eyes shining with emotion, "that my dynasty should -cease to reign on the throne of my ancestors, then after exhausting -all the means at my command, I shall let my beard grow to here" (he -pointed halfway down his chest) "and go and eat potatoes with the -meanest of my peasants, rather than sign the disgrace of my country -and of my beloved people whose sacrifices I know how to appreciate." - -Having uttered these words in an agitated voice the Emperor suddenly -turned away as if to hide from Michaud the tears that rose to his -eyes, and went to the further end of his study. Having stood there a -few moments, he strode back to Michaud and pressed his arm below the -elbow with a vigorous movement. The Emperor's mild and handsome face -was flushed and his eyes gleamed with resolution and anger. - -"Colonel Michaud, do not forget what I say to you here, perhaps we -may recall it with pleasure someday... Napoleon or I," said the -Emperor, touching his breast. "We can no longer both reign together. I -have learned to know him, and he will not deceive me any more...." - -And the Emperor paused, with a frown. - -When he heard these words and saw the expression of firm -resolution in the Emperor's eyes, Michaud--quoique etranger, russe -de coeur et d'ame--at that solemn moment felt himself enraptured by -all that he had heard (as he used afterwards to say), and gave -expression to his own feelings and those of the Russian people whose -representative he considered himself to be, in the following words: - -"Sire!" said he, "Your Majesty is at this moment signing the glory -of the nation and the salvation of Europe!" - -With an inclination of the head the Emperor dismissed him. - - - - - -CHAPTER IV - - -It is natural for us who were not living in those days to imagine -that when half Russia had been conquered and the inhabitants were -fleeing to distant provinces, and one levy after another was being -raised for the defense of the fatherland, all Russians from the -greatest to the least were solely engaged in sacrificing themselves, -saving their fatherland, or weeping over its downfall. The tales and -descriptions of that time without exception speak only of the -self-sacrifice, patriotic devotion, despair, grief, and the heroism of -the Russians. But it was not really so. It appears so to us because we -see only the general historic interest of that time and do not see all -the personal human interests that people had. Yet in reality those -personal interests of the moment so much transcend the general -interests that they always prevent the public interest from being felt -or even noticed. Most of the people at that time paid no attention -to the general progress of events but were guided only by their -private interests, and they were the very people whose activities at -that period were most useful. - -Those who tried to understand the general course of events and to -take part in it by self-sacrifice and heroism were the most useless -members of society, they saw everything upside down, and all they -did for the common good turned out to be useless and foolish--like -Pierre's and Mamonov's regiments which looted Russian villages, and -the lint the young ladies prepared and that never reached the wounded, -and so on. Even those, fond of intellectual talk and of expressing -their feelings, who discussed Russia's position at the time -involuntarily introduced into their conversation either a shade of -pretense and falsehood or useless condemnation and anger directed -against people accused of actions no one could possibly be guilty -of. In historic events the rule forbidding us to eat of the fruit of -the Tree of Knowledge is specially applicable. Only unconscious action -bears fruit, and he who plays a part in an historic event never -understands its significance. If he tries to realize it his efforts -are fruitless. - -The more closely a man was engaged in the events then taking place -in Russia the less did he realize their significance. In Petersburg -and in the provinces at a distance from Moscow, ladies, and -gentlemen in militia uniforms, wept for Russia and its ancient capital -and talked of self-sacrifice and so on; but in the army which -retired beyond Moscow there was little talk or thought of Moscow, -and when they caught sight of its burned ruins no one swore to be -avenged on the French, but they thought about their next pay, their -next quarters, of Matreshka the vivandiere, and like matters. - -As the war had caught him in the service, Nicholas Rostov took a -close and prolonged part in the defense of his country, but did so -casually, without any aim at self-sacrifice, and he therefore looked -at what was going on in Russia without despair and without dismally -racking his brains over it. Had he been asked what he thought of the -state of Russia, he would have said that it was not his business to -think about it, that Kutuzov and others were there for that purpose, -but that he had heard that the regiments were to be made up to their -full strength, that fighting would probably go on for a long time yet, -and that things being so it was quite likely he might be in command of -a regiment in a couple of years' time. - -As he looked at the matter in this way, he learned that he was being -sent to Voronezh to buy remounts for his division, not only without -regret at being prevented from taking part in the coming battle, but -with the greatest pleasure--which he did not conceal and which his -comrades fully understood. - -A few days before the battle of Borodino, Nicholas received the -necessary money and warrants, and having sent some hussars on in -advance, he set out with post horses for Voronezh. - -Only a man who has experienced it--that is, has passed some months -continuously in an atmosphere of campaigning and war--can understand -the delight Nicholas felt when he escaped from the region covered by -the army's foraging operations, provision trains, and hospitals. When- -free from soldiers, wagons, and the filthy traces of a camp--he saw -villages with peasants and peasant women, gentlemen's country -houses, fields where cattle were grazing, posthouses with -stationmasters asleep in them, he rejoiced as though seeing all this -for the first time. What for a long while specially surprised and -delighted him were the women, young and healthy, without a dozen -officers making up to each of them; women, too, who were pleased and -flattered that a passing officer should joke with them. - -In the highest spirits Nicholas arrived at night at a hotel in -Voronezh, ordered things he had long been deprived of in camp, and -next day, very clean-shaven and in a full-dress uniform he had not -worn for a long time, went to present himself to the authorities. - -The commander of the militia was a civilian general, an old man -who was evidently pleased with his military designation and rank. He -received Nicholas brusquely (imagining this to be characteristically -military) and questioned him with an important air, as if -considering the general progress of affairs and approving and -disapproving with full right to do so. Nicholas was in such good -spirits that this merely amused him. - -From the commander of the militia he drove to the governor. The -governor was a brisk little man, very simple and affable. He indicated -the stud farms at which Nicholas might procure horses, recommended -to him a horse dealer in the town and a landowner fourteen miles out -of town who had the best horses, and promised to assist him in every -way. - -"You are Count Ilya Rostov's son? My wife was a great friend of your -mother's. We are at home on Thursdays--today is Thursday, so please -come and see us quite informally," said the governor, taking leave -of him. - -Immediately on leaving the governor's, Nicholas hired post horses -and, taking his squadron quartermaster with him, drove at a gallop -to the landowner, fourteen miles away, who had the stud. Everything -seemed to him pleasant and easy during that first part of his stay -in Voronezh and, as usually happens when a man is in a pleasant -state of mind, everything went well and easily. - -The landowner to whom Nicholas went was a bachelor, an old -cavalryman, a horse fancier, a sportsman, the possessor of some -century-old brandy and some old Hungarian wine, who had a snuggery -where he smoked, and who owned some splendid horses. - -In very few words Nicholas bought seventeen picked stallions for six -thousand rubles--to serve, as he said, as samples of his remounts. -After dining and taking rather too much of the Hungarian wine, -Nicholas--having exchanged kisses with the landowner, with whom he was -already on the friendliest terms--galloped back over abominable roads, -in the brightest frame of mind, continually urging on the driver so as -to be in time for the governor's party. - -When he had changed, poured water over his head, and scented -himself, Nicholas arrived at the governor's rather late, but with -the phrase "better late than never" on his lips. - -It was not a ball, nor had dancing been announced, but everyone knew -that Catherine Petrovna would play valses and the ecossaise on the -clavichord and that there would be dancing, and so everyone had come -as to a ball. - -Provincial life in 1812 went on very much as usual, but with this -difference, that it was livelier in the towns in consequence of the -arrival of many wealthy families from Moscow, and as in everything -that went on in Russia at that time a special recklessness was -noticeable, an "in for a penny, in for a pound--who cares?" spirit, -and the inevitable small talk, instead of turning on the weather and -mutual acquaintances, now turned on Moscow, the army, and Napoleon. - -The society gathered together at the governor's was the best in -Voronezh. - -There were a great many ladies and some of Nicholas' Moscow -acquaintances, but there were no men who could at all vie with the -cavalier of St. George, the hussar remount officer, the good-natured -and well-bred Count Rostov. Among the men was an Italian prisoner, -an officer of the French army; and Nicholas felt that the presence -of that prisoner enhanced his own importance as a Russian hero. The -Italian was, as it were, a war trophy. Nicholas felt this, it seemed -to him that everyone regarded the Italian in the same light, and he -treated him cordially though with dignity and restraint. - -As soon as Nicholas entered in his hussar uniform, diffusing -around him a fragrance of perfume and wine, and had uttered the -words "better late than never" and heard them repeated several times -by others, people clustered around him; all eyes turned on him, and he -felt at once that he had entered into his proper position in the -province--that of a universal favorite: a very pleasant position, -and intoxicatingly so after his long privations. At posting -stations, at inns, and in the landowner's snuggery, maidservants had -been flattered by his notice, and here too at the governor's party -there were (as it seemed to Nicholas) an inexhaustible number of -pretty young women, married and unmarried, impatiently awaiting his -notice. The women and girls flirted with him and, from the first -day, the people concerned themselves to get this fine young -daredevil of an hussar married and settled down. Among these was the -governor's wife herself, who welcomed Rostov as a near relative and -called him "Nicholas." - -Catherine Petrovna did actually play valses and the ecossaise, and -dancing began in which Nicholas still further captivated the -provincial society by his agility. His particularly free manner of -dancing even surprised them all. Nicholas was himself rather surprised -at the way he danced that evening. He had never danced like that in -Moscow and would even have considered such a very free and easy manner -improper and in bad form, but here he felt it incumbent on him to -astonish them all by something unusual, something they would have to -accept as the regular thing in the capital though new to them in the -provinces. - -All the evening Nicholas paid attention to a blue-eyed, plump and -pleasing little blonde, the wife of one of the provincial officials. -With the naive conviction of young men in a merry mood that other -men's wives were created for them, Rostov did not leave the lady's -side and treated her husband in a friendly and conspiratorial style, -as if, without speaking of it, they knew how capitally Nicholas and -the lady would get on together. The husband, however, did not seem -to share that conviction and tried to behave morosely with Rostov. But -the latter's good-natured naivete was so boundless that sometimes even -he involuntarily yielded to Nicholas' good humor. Toward the end of -the evening, however, as the wife's face grew more flushed and -animated, the husband's became more and more melancholy and solemn, as -though there were but a given amount of animation between them and -as the wife's share increased the husband's diminished. - - - - - -CHAPTER V - - -Nicholas sat leaning slightly forward in an armchair, bending -closely over the blonde lady and paying her mythological compliments -with a smile that never left his face. Jauntily shifting the -position of his legs in their tight riding breeches, diffusing an odor -of perfume, and admiring his partner, himself, and the fine outlines -of his legs in their well-fitting Hessian boots, Nicholas told the -blonde lady that he wished to run away with a certain lady here in -Voronezh. - -"Which lady?" - -"A charming lady, a divine one. Her eyes" (Nicholas looked at his -partner) "are blue, her mouth coral and ivory; her figure" (he glanced -at her shoulders) "like Diana's...." - -The husband came up and sullenly asked his wife what she was talking -about. - -"Ah, Nikita Ivanych!" cried Nicholas, rising politely, and as if -wishing Nikita Ivanych to share his joke, he began to tell him of -his intention to elope with a blonde lady. - -The husband smiled gloomily, the wife gaily. The governor's -good-natured wife came up with a look of disapproval. - -"Anna Ignatyevna wants to see you, Nicholas," said she, -pronouncing the name so that Nicholas at once understood that Anna -Ignatyevna was a very important person. "Come, Nicholas! You know -you let me call you so?" - -"Oh, yes, Aunt. Who is she?" - -"Anna Ignatyevna Malvintseva. She has heard from her niece how you -rescued her... Can you guess?" - -"I rescued such a lot of them!" said Nicholas. - -"Her niece, Princess Bolkonskaya. She is here in Voronezh with her -aunt. Oho! How you blush. Why, are...?" - -"Not a bit! Please don't, Aunt!" - -"Very well, very well!... Oh, what a fellow you are!" - -The governor's wife led him up to a tall and very stout old lady -with a blue headdress, who had just finished her game of cards with -the most important personages of the town. This was Malvintseva, -Princess Mary's aunt on her mother's side, a rich, childless widow who -always lived in Voronezh. When Rostov approached her she was -standing settling up for the game. She looked at him and, screwing -up her eyes sternly, continued to upbraid the general who had won from -her. - -"Very pleased, mon cher," she then said, holding out her hand to -Nicholas. "Pray come and see me." - -After a few words about Princess Mary and her late father, whom -Malvintseva had evidently not liked, and having asked what Nicholas -knew of Prince Andrew, who also was evidently no favorite of hers, the -important old lady dismissed Nicholas after repeating her invitation -to come to see her. - -Nicholas promised to come and blushed again as he bowed. At the -mention of Princess Mary he experienced a feeling of shyness and -even of fear, which he himself did not understand. - -When he had parted from Malvintseva Nicholas wished to return to the -dancing, but the governor's little wife placed her plump hand on his -sleeve and, saying that she wanted to have a talk with him, led him to -her sitting room, from which those who were there immediately withdrew -so as not to be in her way. - -"Do you know, dear boy," began the governor's wife with a serious -expression on her kind little face, "that really would be the match -for you: would you like me to arrange it?" - -"Whom do you mean, Aunt?" asked Nicholas. - -"I will make a match for you with the princess. Catherine Petrovna -speaks of Lily, but I say, no--the princess! Do you want me to do -it? I am sure your mother will be grateful to me. What a charming girl -she is, really! And she is not at all so plain, either." - -"Not at all," replied Nicholas as if offended at the idea. "As -befits a soldier, Aunt, I don't force myself on anyone or refuse -anything," he said before he had time to consider what he was saying. - -"Well then, remember, this is not a joke!" - -"Of course not!" - -"Yes, yes," the governor's wife said as if talking to herself. "But, -my dear boy, among other things you are too attentive to the other, -the blonde. One is sorry for the husband, really...." - -"Oh no, we are good friends with him," said Nicholas in the -simplicity of his heart; it did not enter his head that a pastime so -pleasant to himself might not be pleasant to someone else. - -"But what nonsense I have been saying to the governor's wife!" -thought Nicholas suddenly at supper. "She will really begin to arrange -a match... and Soyna...?" And on taking leave of the governor's -wife, when she again smilingly said to him, "Well then, remember!" -he drew her aside. - -"But see here, to tell the truth, Aunt..." - -"What is it, my dear? Come, let's sit down here," said she. - -Nicholas suddenly felt a desire and need to tell his most intimate -thoughts (which he would not have told to his mother, his sister, or -his friend) to this woman who was almost a stranger. When he -afterwards recalled that impulse to unsolicited and inexplicable -frankness which had very important results for him, it seemed to -him--as it seems to everyone in such cases--that it was merely some -silly whim that seized him: yet that burst of frankness, together with -other trifling events, had immense consequences for him and for all -his family. - -"You see, Aunt, Mamma has long wanted me to marry an heiress, but -the very idea of marrying for money is repugnant to me." - -"Oh yes, I understand," said the governor's wife. - -"But Princess Bolkonskaya--that's another matter. I will tell you -the truth. In the first place I like her very much, I feel drawn to -her; and then, after I met her under such circumstances--so strangely, -the idea often occurred to me: 'This is fate.' Especially if you -remember that Mamma had long been thinking of it; but I had never -happened to meet her before, somehow it had always happened that we -did not meet. And as long as my sister Natasha was engaged to her -brother it was of course out of the question for me to think of -marrying her. And it must needs happen that I should meet her just -when Natasha's engagement had been broken off... and then -everything... So you see... I never told this to anyone and never -will, only to you." - -The governor's wife pressed his elbow gratefully. - -"You know Sonya, my cousin? I love her, and promised to marry her, -and will do so.... So you see there can be no question about-" said -Nicholas incoherently and blushing. - -"My dear boy, what a way to look at it! You know Sonya has nothing -and you yourself say your Papa's affairs are in a very bad way. And -what about your mother? It would kill her, that's one thing. And -what sort of life would it be for Sonya--if she's a girl with a heart? -Your mother in despair, and you all ruined.... No, my dear, you and -Sonya ought to understand that." - -Nicholas remained silent. It comforted him to hear these arguments. - -"All the same, Aunt, it is impossible," he rejoined with a sigh, -after a short pause. "Besides, would the princess have me? And -besides, she is now in mourning. How can one think of it!" - -"But you don't suppose I'm going to get you married at once? There -is always a right way of doing things," replied the governor's wife. - -"What a matchmaker you are, Aunt..." said Nicholas, kissing her -plump little hand. - - - - - -CHAPTER VI - - -On reaching Moscow after her meeting with Rostov, Princess Mary -had found her nephew there with his tutor, and a letter from Prince -Andrew giving her instructions how to get to her Aunt Malvintseva at -Voronezh. That feeling akin to temptation which had tormented her -during her father's illness, since his death, and especially since her -meeting with Rostov was smothered by arrangements for the journey, -anxiety about her brother, settling in a new house, meeting new -people, and attending to her nephew's education. She was sad. Now, -after a month passed in quiet surroundings, she felt more and more -deeply the loss of her father which was associated in her mind with -the ruin of Russia. She was agitated and incessantly tortured by the -thought of the dangers to which her brother, the only intimate -person now remaining to her, was exposed. She was worried too about -her nephew's education for which she had always felt herself -incompetent, but in the depths of her soul she felt at peace--a -peace arising from consciousness of having stifled those personal -dreams and hopes that had been on the point of awakening within her -and were related to her meeting with Rostov. - -The day after her party the governor's wife came to see -Malvintseva and, after discussing her plan with the aunt, remarked -that though under present circumstances a formal betrothal was, of -course, not to be thought of, all the same the young people might be -brought together and could get to know one another. Malvintseva -expressed approval, and the governor's wife began to speak of Rostov -in Mary's presence, praising him and telling how he had blushed when -Princess Mary's name was mentioned. But Princess Mary experienced a -painful rather than a joyful feeling--her mental tranquillity was -destroyed, and desires, doubts, self-reproach, and hopes reawoke. - -During the two days that elapsed before Rostov called, Princess Mary -continually thought of how she ought to behave to him. First she -decided not to come to the drawing room when he called to see her -aunt--that it would not be proper for her, in her deep mourning, to -receive visitors; then she thought this would be rude after what he -had done for her; then it occurred to her that her aunt and the -governor's wife had intentions concerning herself and Rostov--their -looks and words at times seemed to confirm this supposition--then -she told herself that only she, with her sinful nature, could think -this of them: they could not forget that situated as she was, while -still wearing deep mourning, such matchmaking would be an insult to -her and to her father's memory. Assuming that she did go down to see -him, Princess Mary imagined the words he would say to her and what she -would say to him, and these words sometimes seemed undeservedly cold -and then to mean too much. More than anything she feared lest the -confusion she felt might overwhelm her and betray her as soon as she -saw him. - -But when on Sunday after church the footman announced in the drawing -room that Count Rostov had called, the princess showed no confusion, -only a slight blush suffused her cheeks and her eyes lit up with a new -and radiant light. - -"You have met him, Aunt?" said she in a calm voice, unable herself -to understand that she could be outwardly so calm and natural. - -When Rostov entered the room, the princess dropped her eyes for an -instant, as if to give the visitor time to greet her aunt, and then -just as Nicholas turned to her she raised her head and met his look -with shining eyes. With a movement full of dignity and grace she -half rose with a smile of pleasure, held out her slender, delicate -hand to him, and began to speak in a voice in which for the first time -new deep womanly notes vibrated. Mademoiselle Bourienne, who was in -the drawing room, looked at Princess Mary in bewildered surprise. -Herself a consummate coquette, she could not have maneuvered better on -meeting a man she wished to attract. - -"Either black is particularly becoming to her or she really has -greatly improved without my having noticed it. And above all, what -tact and grace!" thought Mademoiselle Bourienne. - -Had Princess Mary been capable of reflection at that moment, she -would have been more surprised than Mademoiselle Bourienne at the -change that had taken place in herself. From the moment she recognized -that dear, loved face, a new life force took possession of her and -compelled her to speak and act apart from her own will. From the -time Rostov entered, her face became suddenly transformed. It was as -if a light had been kindled in a carved and painted lantern and the -intricate, skillful, artistic work on its sides, that previously -seemed dark, coarse, and meaningless, was suddenly shown up in -unexpected and striking beauty. For the first time all that pure, -spiritual, inward travail through which she had lived appeared on -the surface. All her inward labor, her dissatisfaction with herself, -her sufferings, her strivings after goodness, her meekness, love, -and self-sacrifice--all this now shone in those radiant eyes, in her -delicate smile, and in every trait of her gentle face. - -Rostov saw all this as clearly as if he had known her whole life. He -felt that the being before him was quite different from, and better -than, anyone he had met before, and above all better than himself. - -Their conversation was very simple and unimportant. They spoke of -the war, and like everyone else unconsciously exaggerated their sorrow -about it; they spoke of their last meeting--Nicholas trying to -change the subject--they talked of the governor's kind wife, of -Nicholas' relations, and of Princess Mary's. - -She did not talk about her brother, diverting the conversation as -soon as her aunt mentioned Andrew. Evidently she could speak of -Russia's misfortunes with a certain artificiality, but her brother was -too near her heart and she neither could nor would speak lightly of -him. Nicholas noticed this, as he noticed every shade of Princess -Mary's character with an observation unusual to him, and everything -confirmed his conviction that she was a quite unusual and -extraordinary being. Nicholas blushed and was confused when people -spoke to him about the princess (as she did when he was mentioned) and -even when he thought of her, but in her presence he felt quite at -ease, and said not at all what he had prepared, but what, quite -appropriately, occurred to him at the moment. - -When a pause occurred during his short visit, Nicholas, as is -usual when there are children, turned to Prince Andrew's little son, -caressing him and asking whether he would like to be an hussar. He -took the boy on his knee, played with him, and looked round at -Princess Mary. With a softened, happy, timid look she watched the -boy she loved in the arms of the man she loved. Nicholas also -noticed that look and, as if understanding it, flushed with pleasure -and began to kiss the boy with good natured playfulness. - -As she was in mourning Princess Mary did not go out into society, -and Nicholas did not think it the proper thing to visit her again; but -all the same the governor's wife went on with her matchmaking, passing -on to Nicholas the flattering things Princess Mary said of him and -vice versa, and insisting on his declaring himself to Princess Mary. -For this purpose she arranged a meeting between the young people at -the bishop's house before Mass. - -Though Rostov told the governeor's wife that he would not make any -declaration to Princess Mary, he promised to go. - -As at Tilsit Rostov had not allowed himself to doubt that what -everybody considered right was right, so now, after a short but -sincere struggle between his effort to arrange his life by his own -sense of justice, and in obedient submission to circumstances, he -chose the latter and yielded to the power he felt irresistibly -carrying him he knew not where. He knew that after his promise to -Sonya it would be what he deemed base to declare his feelings to -Princess Mary. And he knew that he would never act basely. But he also -knew (or rather felt at the bottom of his heart) that by resigning -himself now to the force of circumstances and to those who were -guiding him, he was not only doing nothing wrong, but was doing -something very important--more important than anything he had ever -done in his life. - -After meeting Princess Mary, though the course of his life went on -externally as before, all his former amusements lost their charm for -him and he often thought about her. But he never thought about her -as he had thought of all the young ladies without exception whom he -had met in society, nor as he had for a long time, and at one time -rapturously, thought about Sonya. He had pictured each of those -young ladies as almost all honest-hearted young men do, that is, as -a possible wife, adapting her in his imagination to all the conditions -of married life: a white dressing gown, his wife at the tea table, his -wife's carriage, little ones, Mamma and Papa, their relations to -her, and so on--and these pictures of the future had given him -pleasure. But with Princess Mary, to whom they were trying to get -him engaged, he could never picture anything of future married life. -If he tried, his pictures seemed incongruous and false. It made him -afraid. - - - - - -CHAPTER VII - - -The dreadful news of the battle of Borodino, of our losses in killed -and wounded, and the still more terrible news of the loss of Moscow -reached Voronezh in the middle of September. Princess Mary, having -learned of her brother's wound only from the Gazette and having no -definite news of him, prepared (so Nicholas heard, he had not seen her -again himself) to set off in search of Prince Andrew. - -When he received the news of the battle of Borodino and the -abandonment of Moscow, Rostov was not seized with despair, anger, -the desire for vengeance, or any feeling of that kind, but -everything in Voronezh suddenly seemed to him dull and tiresome, and -he experienced an indefinite feeling of shame and awkwardness. The -conversations he heard seemed to him insincere; he did not know how to -judge all these affairs and felt that only in the regiment would -everything again become clear to him. He made haste to finish buying -the horses, and often became unreasonably angry with his servant and -squadron quartermaster. - -A few days before his departure a special thanksgiving, at which -Nicholas was present, was held in the cathedral for the Russian -victory. He stood a little behind the governor and held himself with -military decorum through the service, meditating on a great variety of -subjects. When the service was over the governor's wife beckoned him -to her. - -"Have you seen the princess?" she asked, indicating with a -movement of her head a lady standing on the opposite side, beyond -the choir. - -Nicholas immediately recognized Princess Mary not so much by the -profile he saw under her bonnet as by the feeling of solicitude, -timidity, and pity that immediately overcame him. Princess Mary, -evidently engrossed by her thoughts, was crossing herself for the last -time before leaving the church. - -Nicholas looked at her face with surprise. It was the same face he -had seen before, there was the same general expression of refined, -inner, spiritual labor, but now it was quite differently lit up. There -was a pathetic expression of sorrow, prayer, and hope in it. As had -occurred before when she was present, Nicholas went up to her -without waiting to be prompted by the governor's wife and not asking -himself whether or not it was right and proper to address her here -in church, and told her he had heard of her trouble and sympathized -with his whole soul. As soon as she heard his voice a vivid glow -kindled in her face, lighting up both her sorrow and her joy. - -"There is one thing I wanted to tell you, Princess," said Rostov. -"It is that if your brother, Prince Andrew Nikolievich, were not -living, it would have been at once announced in the Gazette, as he -is a colonel." - -The princess looked at him, not grasping what he was saying, but -cheered by the expression of regretful sympathy on his face. - -"And I have known so many cases of a splinter wound" (the Gazette -said it was a shell) "either proving fatal at once or being very -slight," continued Nicholas. "We must hope for the best, and I am -sure..." - -Princess Mary interrupted him. - -"Oh, that would be so dread..." she began and, prevented by -agitation from finishing, she bent her head with a movement as -graceful as everything she did in his presence and, looking up at -him gratefully, went out, following her aunt. - -That evening Nicholas did not go out, but stayed at home to settle -some accounts with the horse dealers. When he had finished that -business it was already too late to go anywhere but still too early to -go to bed, and for a long time he paced up and down the room, -reflecting on his life, a thing he rarely did. - -Princess Mary had made an agreeable impression on him when he had -met her in Smolensk province. His having encountered her in such -exceptional circumstances, and his mother having at one time mentioned -her to him as a good match, had drawn his particular attention to her. -When he met her again in Voronezh the impression she made on him was -not merely pleasing but powerful. Nicholas had been struck by the -peculiar moral beauty he observed in her at this time. He was, -however, preparing to go away and it had not entered his head to -regret that he was thus depriving himself of chances of meeting her. -But that day's encounter in church had, he felt, sunk deeper than -was desirable for his peace of mind. That pale, sad, refined face, -that radiant look, those gentle graceful gestures, and especially -the deep and tender sorrow expressed in all her features agitated -him and evoked his sympathy. In men Rostov could not bear to see the -expression of a higher spiritual life (that was why he did not like -Prince Andrew) and he referred to it contemptuously as philosophy -and dreaminess, but in Princess Mary that very sorrow which revealed -the depth of a whole spiritual world foreign to him was an -irresistible attraction. - -"She must be a wonderful woman. A real angel!" he said to himself. -"Why am I not free? Why was I in such a hurry with Sonya?" And he -involuntarily compared the two: the lack of spirituality in the one -and the abundance of it in the other--a spirituality he himself lacked -and therefore valued most highly. He tried to picture what would -happen were he free. How he would propose to her and how she would -become his wife. But no, he could not imagine that. He felt awed, -and no clear picture presented itself to his mind. He had long ago -pictured to himself a future with Sonya, and that was all clear and -simple just because it had all been thought out and he knew all -there was in Sonya, but it was impossible to picture a future with -Princess Mary, because he did not understand her but simply loved her. - -Reveries about Sonya had had something merry and playful in them, -but to dream of Princess Mary was always difficult and a little -frightening. - -"How she prayed!" he thought. "It was plain that her whole soul -was in her prayer. Yes, that was the prayer that moves mountains, -and I am sure her prayer will be answered. Why don't I pray for what I -want?" he suddenly thought. "What do I want? To be free, released from -Sonya... She was right," he thought, remembering what the governor's -wife had said: "Nothing but misfortune can come of marrying Sonya. -Muddles, grief for Mamma... business difficulties... muddles, terrible -muddles! Besides, I don't love her--not as I should. O, God! release -me from this dreadful, inextricable position!" he suddenly began to -pray. "Yes, prayer can move mountains, but one must have faith and not -pray as Natasha and I used to as children, that the snow might turn -into sugar--and then run out into the yard to see whether it had -done so. No, but I am not praying for trifles now," he thought as he -put his pipe down in a corner, and folding his hands placed himself -before the icon. Softened by memories of Princess Mary he began to -pray as he had not done for a long time. Tears were in his eyes and in -his throat when the door opened and Lavrushka came in with some -papers. - -"Blockhead! Why do you come in without being called?" cried -Nicholas, quickly changing his attitude. - -"From the governor," said Lavrushka in a sleepy voice. "A courier -has arrived and there's a letter for you." - -"Well, all right, thanks. You can go!" - -Nicholas took the two letters, one of which was from his mother -and the other from Sonya. He recognized them by the handwriting and -opened Sonya's first. He had read only a few lines when he turned pale -and his eyes opened wide with fear and joy. - -"No, it's not possible!" he cried aloud. - -Unable to sit still he paced up and down the room holding the letter -and reading it. He glanced through it, then read it again, and then -again, and standing still in the middle of the room he raised his -shoulders, stretching out his hands, with his mouth wide open and -his eyes fixed. What he had just been praying for with confidence that -God would hear him had come to pass; but Nicholas was as much -astonished as if it were something extraordinary and unexpected, and -as if the very fact that it had happened so quickly proved that it had -not come from God to whom he had prayed, but by some ordinary -coincidence. - -This unexpected and, as it seemed to Nicholas, quite voluntary -letter from Sonya freed him from the knot that fettered him and from -which there had seemed no escape. She wrote that the last -unfortunate events--the loss of almost the whole of the Rostovs' -Moscow property--and the countess' repeatedly expressed wish that -Nicholas should marry Princess Bolkonskaya, together with his -silence and coldness of late, had all combined to make her decide to -release him from his promise and set him completely free. - - -It would be too painful to me to think that I might be a cause of -sorrow or discord in the family that has been so good to me (she -wrote), and my love has no aim but the happiness of those I love; -so, Nicholas, I beg you to consider yourself free, and to be assured -that, in spite of everything, no one can love you more than does - -Your Sonya - - -Both letters were written from Troitsa. The other, from the -countess, described their last days in Moscow, their departure, the -fire, and the destruction of all their property. In this letter the -countess also mentioned that Prince Andrew was among the wounded -traveling with them; his state was very critical, but the doctor -said there was now more hope. Sonya and Natasha were nursing him. - -Next day Nicholas took his mother's letter and went to see -Princess Mary. Neither he nor she said a word about what "Natasha -nursing him" might mean, but thanks to this letter Nicholas suddenly -became almost as intimate with the princess as if they were relations. - -The following day he saw Princess Mary off on her journey to -Yaroslavl, and a few days later left to rejoin his regiment. - - - - - -CHAPTER VIII - - -Sonya's letter written from Troitsa, which had come as an answer -to Nicholas' prayer, was prompted by this: the thought of getting -Nicholas married to an heiress occupied the old countess' mind more -and more. She knew that Sonya was the chief obstacle to this -happening, and Sonya's life in the countess' house had grown harder -and harder, especially after they had received a letter from -Nicholas telling of his meeting with Princess Mary in Bogucharovo. The -countess let no occasion slip of making humiliating or cruel allusions -to Sonya. - -But a few days before they left Moscow, moved and excited by all -that was going on, she called Sonya to her and, instead of reproaching -and making demands on her, tearfully implored her to sacrifice herself -and repay all that the family had done for her by breaking off her -engagement with Nicholas. - -"I shall not be at peace till you promise me this." - -Sonya burst into hysterical tears and replied through her sobs -that she would do anything and was prepared for anything, but gave -no actual promise and could not bring herself to decide to do what was -demanded of her. She must sacrifice herself for the family that had -reared and brought her up. To sacrifice herself for others was Sonya's -habit. Her position in the house was such that only by sacrifice could -she show her worth, and she was accustomed to this and loved doing it. -But in all her former acts of self-sacrifice she had been happily -conscious that they raised her in her own esteem and in that of -others, and so made her more worthy of Nicholas whom she loved more -than anything in the world. But now they wanted her to sacrifice the -very thing that constituted the whole reward for her self-sacrifice -and the whole meaning of her life. And for the first time she felt -bitterness against those who had been her benefactors only to -torture her the more painfully; she felt jealous of Natasha who had -never experienced anything of this sort, had never needed to sacrifice -herself, but made others sacrifice themselves for her and yet was -beloved by everybody. And for the first time Sonya felt that out of -her pure, quiet love for Nicholas a passionate feeling was beginning -to grow up which was stronger than principle, virtue, or religion. -Under the influence of this feeling Sonya, whose life of dependence -had taught her involuntarily to be secretive, having answered the -countess in vague general terms, avoided talking with her and resolved -to wait till she should see Nicholas, not in order to set him free but -on the contrary at that meeting to bind him to her forever. - -The bustle and terror of the Rostovs' last days in Moscow stifled -the gloomy thoughts that oppressed Sonya. She was glad to find -escape from them in practical activity. But when she heard of Prince -Andrew's presence in their house, despite her sincere pity for him and -for Natasha, she was seized by a joyful and superstitious feeling that -God did not intend her to be separated from Nicholas. She knew that -Natasha loved no one but Prince Andrew and had never ceased to love -him. She knew that being thrown together again under such terrible -circumstances they would again fall in love with one another, and that -Nicholas would then not be able to marry Princess Mary as they would -be within the prohibited degrees of affinity. Despite all the terror -of what had happened during those last days and during the first -days of their journey, this feeling that Providence was intervening in -her personal affairs cheered Sonya. - -At the Troitsa monastery the Rostovs first broke their journey for a -whole day. - -Three large rooms were assigned to them in the monastery hostelry, -one of which was occupied by Prince Andrew. The wounded man was much -better that day and Natasha was sitting with him. In the next room sat -the count and countess respectfully conversing with the prior, who was -calling on them as old acquaintances and benefactors of the monastery. -Sonya was there too, tormented by curiosity as to what Prince Andrew -and Natasha were talking about. She heard the sound of their voices -through the door. That door opened and Natasha came out, looking -excited. Not noticing the monk, who had risen to greet her and was -drawing back the wide sleeve on his right arm, she went up to Sonya -and took her hand. - -"Natasha, what are you about? Come here!" said the countess. - -Natasha went up to the monk for his blessing, and advised her to -pray for aid to God and His saint. - -As soon as the prior withdrew, Natasha took her friend by the hand -and went with her into the unoccupied room. - -"Sonya, will he live?" she asked. "Sonya, how happy I am, and how -unhappy!... Sonya, dovey, everything is as it used to be. If only he -lives! He cannot... because... because... of" and Natasha burst into -tears. - -"Yes! I knew it! Thank God!" murmured Sonya. "He will live." - -Sonya was not less agitated than her friend by the latter's fear and -grief and by her own personal feelings which she shared with no one. -Sobbing, she kissed and comforted Natasha. "If only he lives!" she -thought. Having wept, talked, and wiped away their tears, the two -friends went together to Prince Andrew's door. Natasha opened it -cautiously and glanced into the room, Sonya standing beside her at the -half-open door. - -Prince Andrew was lying raised high on three pillows. His pale -face was calm, his eyes closed, and they could see his regular -breathing. - -"O, Natasha!" Sonya suddenly almost screamed, catching her -companion's arm and stepping back from the door. - -"What? What is it?" asked Natasha. - -"It's that, that..." said Sonya, with a white face and trembling -lips. - -Natasha softly closed the door and went with Sonya to the window, -not yet understanding what the latter was telling her. - -"You remember," said Sonya with a solemn and frightened -expression. "You remember when I looked in the mirror for you... at -Otradnoe at Christmas? Do you remember what I saw?" - -"Yes, yes!" cried Natasha opening her eyes wide, and vaguely -recalling that Sonya had told her something about Prince Andrew whom -she had seen lying down. - -"You remember?" Sonya went on. "I saw it then and told everybody, -you and Dunyasha. I saw him lying on a bed," said she, making a -gesture with her hand and a lifted finger at each detail, "and that he -had his eyes closed and was covered just with a pink quilt, and that -his hands were folded," she concluded, convincing herself that the -details she had just seen were exactly what she had seen in the -mirror. - -She had in fact seen nothing then but had mentioned the first -thing that came into her head, but what she had invented then seemed -to her now as real as any other recollection. She not only -remembered what she had then said--that he turned to look at her and -smiled and was covered with something red--but was firmly convinced -that she had then seen and said that he was covered with a pink -quilt and that his eyes were closed. - -"Yes, yes, it really was pink!" cried Natasha, who now thought she -too remembered the word pink being used, and saw in this the most -extraordinary and mysterious part of the prediction. - -"But what does it mean?" she added meditatively. - -"Oh, I don't know, it is all so strange," replied Sonya, clutching -at her head. - -A few minutes later Prince Andrew rang and Natasha went to him, -but Sonya, feeling unusually excited and touched, remained at the -window thinking about the strangeness of what had occurred. - - -They had an opportunity that day to send letters to the army, and -the countess was writing to her son. - -"Sonya!" said the countess, raising her eyes from her letter as -her niece passed, "Sonya, won't you write to Nicholas?" She spoke in a -soft, tremulous voice, and in the weary eyes that looked over her -spectacles Sonya read all that the countess meant to convey with these -words. Those eyes expressed entreaty, shame at having to ask, fear -of a refusal, and readiness for relentless hatred in case of such -refusal. - -Sonya went up to the countess and, kneeling down, kissed her hand. - -"Yes, Mamma, I will write," said she. - -Sonya was softened, excited, and touched by all that had occurred -that day, especially by the mysterious fulfillment she had just seen -of her vision. Now that she knew that the renewal of Natasha's -relations with Prince Andrew would prevent Nicholas from marrying -Princess Mary, she was joyfully conscious of a return of that -self-sacrificing spirit in which she was accustomed to live and -loved to live. So with a joyful consciousness of performing a -magnanimous deed--interrupted several times by the tears that dimmed -her velvety black eyes--she wrote that touching letter the arrival -of which had so amazed Nicholas. - - - - - -CHAPTER IX - - -The officer and soldiers who had arrested Pierre treated him with -hostility but yet with respect, in the guardhouse to which he was -taken. In their attitude toward him could still be felt both -uncertainty as to who he might be--perhaps a very important person- -and hostility as a result of their recent personal conflict with him. - -But when the guard was relieved next morning, Pierre felt that for -the new guard--both officers and men--he was not as interesting as -he had been to his captors; and in fact the guard of the second day -did not recognize in this big, stout man in a peasant coat the -vigorous person who had fought so desperately with the marauder and -the convoy and had uttered those solemn words about saving a child; -they saw in him only No. 17 of the captured Russians, arrested and -detained for some reason by order of the Higher Command. If they -noticed anything remarkable about Pierre, it was only his unabashed, -meditative concentration and thoughtfulness, and the way he spoke -French, which struck them as surprisingly good. In spite of this he -was placed that day with the other arrested suspects, as the -separate room he had occupied was required by an officer. - -All the Russians confined with Pierre were men of the lowest class -and, recognizing him as a gentleman, they all avoided him, more -especially as he spoke French. Pierre felt sad at hearing them -making fun of him. - -That evening he learned that all these prisoners (he, probably, -among them) were to be tried for incendiarism. On the third day he was -taken with the others to a house where a French general with a white -mustache sat with two colonels and other Frenchmen with scarves on -their arms. With the precision and definiteness customary in -addressing prisoners, and which is supposed to preclude human frailty, -Pierre like the others was questioned as to who he was, where he had -been, with what object, and so on. - -These questions, like questions put at trials generally, left the -essence of the matter aside, shut out the possibility of that -essence's being revealed, and were designed only to form a channel -through which the judges wished the answers of the accused to flow -so as to lead to the desired result, namely a conviction. As soon as -Pierre began to say anything that did not fit in with that aim, the -channel was removed and the water could flow to waste. Pierre felt, -moreover, what the accused always feel at their trial, perplexity as -to why these questions were put to him. He had a feeling that it was -only out of condescension or a kind of civility that this device of -placing a channel was employed. He knew he was in these men's power, -that only by force had they brought him there, that force alone gave -them the right to demand answers to their questions, and that the sole -object of that assembly was to inculpate him. And so, as they had -the power and wish to inculpate him, this expedient of an inquiry -and trial seemed unnecessary. It was evident that any answer would -lead to conviction. When asked what he was doing when he was arrested, -Pierre replied in a rather tragic manner that he was restoring to -its parents a child he had saved from the flames. Why had he fought -the marauder? Pierre answered that he "was protecting a woman," and -that "to protect a woman who was being insulted was the duty of -every man; that..." They interrupted him, for this was not to the -point. Why was he in the yard of a burning house where witnesses had -seen him? He replied that he had gone out to see what was happening in -Moscow. Again they interrupted him: they had not asked where he was -going, but why he was found near the fire? Who was he? they asked, -repeating their first question, which he had declined to answer. Again -he replied that he could not answer it. - -"Put that down, that's bad... very bad," sternly remarked the -general with the white mustache and red flushed face. - - -On the fourth day fires broke out on the Zubovski rampart. - -Pierre and thirteen others were moved to the coach house of a -merchant's house near the Crimean bridge. On his way through the -streets Pierre felt stifled by the smoke which seemed to hang over the -whole city. Fires were visible on all sides. He did not then realize -the significance of the burning of Moscow, and looked at the fires -with horror. - -He passed four days in the coach house near the Crimean bridge and -during that time learned, from the talk of the French soldiers, that -all those confined there were awaiting a decision which might come any -day from the marshal. What marshal this was, Pierre could not learn -from the soldiers. Evidently for them "the marshal" represented a very -high and rather mysterious power. - -These first days, before the eighth of September when the -prisoners were had up for a second examination, were the hardest of -all for Pierre. - - - - - -CHAPTER X - - -On the eighth of September an officer--a very important one -judging by the respect the guards showed him--entered the coach -house where the prisoners were. This officer, probably someone on -the staff, was holding a paper in his hand, and called over all the -Russians there, naming Pierre as "the man who does not give his name." -Glancing indolently and indifferently at all the prisoners, he ordered -the officer in charge to have them decently dressed and tidied up -before taking them to the marshal. An hour later a squad of soldiers -arrived and Pierre with thirteen others was led to the Virgin's Field. -It was a fine day, sunny after rain, and the air was unusually pure. -The smoke did not hang low as on the day when Pierre had been taken -from the guardhouse on the Zubovski rampart, but rose through the pure -air in columns. No flames were seen, but columns of smoke rose on -all sides, and all Moscow as far as Pierre could see was one vast -charred ruin. On all sides there were waste spaces with only stoves -and chimney stacks still standing, and here and there the blackened -walls of some brick houses. Pierre gazed at the ruins and did not -recognize districts he had known well. Here and there he could see -churches that had not been burned. The Kremlin, which was not -destroyed, gleamed white in the distance with its towers and the -belfry of Ivan the Great. The domes of the New Convent of the Virgin -glittered brightly and its bells were ringing particularly clearly. -These bells reminded Pierre that it was Sunday and the feast of the -Nativity of the Virgin. But there seemed to be no one to celebrate -this holiday: everywhere were blackened ruins, and the few Russians to -be seen were tattered and frightened people who tried to hide when -they saw the French. - -It was plain that the Russian nest was ruined and destroyed, but -in place of the Russian order of life that had been destroyed, -Pierre unconsciously felt that a quite different, firm, French order -had been established over this ruined nest. He felt this in the -looks of the soldiers who, marching in regular ranks briskly and -gaily, were escorting him and the other criminals; he felt it in the -looks of an important French official in a carriage and pair driven by -a soldier, whom they met on the way. He felt it in the merry sounds of -regimental music he heard from the left side of the field, and felt -and realized it especially from the list of prisoners the French -officer had read out when he came that morning. Pierre had been -taken by one set of soldiers and led first to one and then to -another place with dozens of other men, and it seemed that they -might have forgotten him, or confused him with the others. But no: the -answers he had given when questioned had come back to him in his -designation as "the man who does not give his name," and under that -appellation, which to Pierre seemed terrible, they were now leading -him somewhere with unhesitating assurance on their faces that he and -all the other prisoners were exactly the ones they wanted and that -they were being taken to the proper place. Pierre felt himself to be -an insignificant chip fallen among the wheels of a machine whose -action he did not understand but which was working well. - -He and the other prisoners were taken to the right side of the -Virgin's Field, to a large white house with an immense garden not -far from the convent. This was Prince Shcherbitov's house, where -Pierre had often been in other days, and which, as he learned from the -talk of the soldiers, was now occupied by the marshal, the Duke of -Eckmuhl (Davout). - -They were taken to the entrance and led into the house one by one. -Pierre was the sixth to enter. He was conducted through a glass -gallery, an anteroom, and a hall, which were familiar to him, into a -long low study at the door of which stood an adjutant. - -Davout, spectacles on nose, sat bent over a table at the further end -of the room. Pierre went close up to him, but Davout, evidently -consulting a paper that lay before him, did not look up. Without -raising his eyes, he said in a low voice: - -"Who are you?" - -Pierre was silent because he was incapable of uttering a word. To -him Davout was not merely a French general, but a man notorious for -his cruelty. Looking at his cold face, as he sat like a stern -schoolmaster who was prepared to wait awhile for an answer, Pierre -felt that every instant of delay might cost him his life; but he did -not know what to say. He did not venture to repeat what he had said at -his first examination, yet to disclose his rank and position was -dangerous and embarrassing. So he was silent. But before he had -decided what to do, Davout raised his head, pushed his spectacles back -on his forehead, screwed up his eyes, and looked intently at him. - -"I know that man," he said in a cold, measured tone, evidently -calculated to frighten Pierre. - -The chill that had been running down Pierre's back now seized his -head as in a vise. - -"You cannot know me, General, I have never seen you..." - -"He is a Russian spy," Davout interrupted, addressing another -general who was present, but whom Pierre had not noticed. - -Davout turned away. With an unexpected reverberation in his voice -Pierre rapidly began: - -"No, monseigneur," he said, suddenly remembering that Davout was a -duke. "No, monseigneur, you cannot have known me. I am a militia -officer and have not quitted Moscow." - -"Your name?" asked Davout. - -"Bezukhov." - -"What proof have I that you are not lying?" - -"Monseigneur!" exclaimed Pierre, not in an offended but in a -pleading voice. - -Davout looked up and gazed intently at him. For some seconds they -looked at one another, and that look saved Pierre. Apart from -conditions of war and law, that look established human relations -between the two men. At that moment an immense number of things passed -dimly through both their minds, and they realized that they were -both children of humanity and were brothers. - -At the first glance, when Davout had only raised his head from the -papers where human affairs and lives were indicated by numbers, Pierre -was merely a circumstance, and Davout could have shot him without -burdening his conscience with an evil deed, but now he saw in him a -human being. He reflected for a moment. - -"How can you show me that you are telling the truth?" said Davout -coldly. - -Pierre remembered Ramballe, and named him and his regiment and the -street where the house was. - -"You are not what you say," returned Davout. - -In a trembling, faltering voice Pierre began adducing proofs of -the truth of his statements. - -But at that moment an adjutant entered and reported something to -Davout. - -Davout brightened up at the news the adjutant brought, and began -buttoning up his uniform. It seemed that he had quite forgotten -Pierre. - -When the adjutant reminded him of the prisoner, he jerked his head -in Pierre's direction with a frown and ordered him to be led away. But -where they were to take him Pierre did not know: back to the coach -house or to the place of execution his companions had pointed out to -him as they crossed the Virgin's Field. - -He turned his head and saw that the adjutant was putting another -question to Davout. - -"Yes, of course!" replied Davout, but what this "yes" meant, -Pierre did not know. - -Pierre could not afterwards remember how he went, whether it was -far, or in which direction. His faculties were quite numbed, he was -stupefied, and noticing nothing around him went on moving his legs -as the others did till they all stopped and he stopped too. The only -thought in his mind at that time was: who was it that had really -sentenced him to death? Not the men on the commission that had first -examined him--not one of them wished to or, evidently, could have done -it. It was not Davout, who had looked at him in so human a way. In -another moment Davout would have realized that he was doing wrong, but -just then the adjutant had come in and interrupted him. The -adjutant, also, had evidently had no evil intent though he might -have refrained from coming in. Then who was executing him, killing -him, depriving him of life--him, Pierre, with all his memories, -aspirations, hopes, and thoughts? Who was doing this? And Pierre -felt that it was no one. - -It was a system--a concurrence of circumstances. - -A system of some sort was killing him--Pierre--depriving him of -life, of everything, annihilating him. - - - - - -CHAPTER XI - - -From Prince Shcherbatov's house the prisoners were led straight down -the Virgin's Field, to the left of the nunnery, as far as a kitchen -garden in which a post had been set up. Beyond that post a fresh pit -had been dug in the ground, and near the post and the pit a large -crowd stood in a semicircle. The crowd consisted of a few Russians and -many of Napoleon's soldiers who were not on duty--Germans, Italians, -and Frenchmen, in a variety of uniforms. To the right and left of -the post stood rows of French troops in blue uniforms with red -epaulets and high boots and shakos. - -The prisoners were placed in a certain order, according to the -list (Pierre was sixth), and were led to the post. Several drums -suddenly began to beat on both sides of them, and at that sound Pierre -felt as if part of his soul had been torn away. He lost the power of -thinking or understanding. He could only hear and see. And he had only -one wish--that the frightful thing that had to happen should happen -quickly. Pierre looked round at his fellow prisoners and scrutinized -them. - -The two first were convicts with shaven heads. One was tall and -thin, the other dark, shaggy, and sinewy, with a flat nose. The -third was a domestic serf, about forty-five years old, with grizzled -hair and a plump, well-nourished body. The fourth was a peasant, a -very handsome man with a broad, light-brown beard and black eyes. -The fifth was a factory hand, a thin, sallow-faced lad of eighteen -in a loose coat. - -Pierre heard the French consulting whether to shoot them -separately or two at a time. "In couples," replied the officer in -command in a calm voice. There was a stir in the ranks of the soldiers -and it was evident that they were all hurrying--not as men hurry to do -something they understand, but as people hurry to finish a necessary -but unpleasant and incomprehensible task. - -A French official wearing a scarf came up to the right of the row of -prisoners and read out the sentence in Russian and in French. - -Then two pairs of Frenchmen approached the criminals and at the -officer's command took the two convicts who stood first in the row. -The convicts stopped when they reached the post and, while sacks -were being brought, looked dumbly around as a wounded beast looks at -an approaching huntsman. One crossed himself continually, the other -scratched his back and made a movement of the lips resembling a smile. -With hurried hands the soldiers blindfolded them, drawing the sacks -over their heads, and bound them to the post. - -Twelve sharpshooters with muskets stepped out of the ranks with a -firm regular tread and halted eight paces from the post. Pierre turned -away to avoid seeing what was going to happen. Suddenly a crackling, -rolling noise was heard which seemed to him louder than the most -terrific thunder, and he looked round. There was some smoke, and the -Frenchmen were doing something near the pit, with pale faces and -trembling hands. Two more prisoners were led up. In the same way and -with similar looks, these two glanced vainly at the onlookers with -only a silent appeal for protection in their eyes, evidently unable to -understand or believe what was going to happen to them. They could not -believe it because they alone knew what their life meant to them, -and so they neither understood nor believed that it could be taken -from them. - -Again Pierre did not wish to look and again turned away; but again -the sound as of a frightful explosion struck his ear, and at the -same moment he saw smoke, blood, and the pale, scared faces of the -Frenchmen who were again doing something by the post, their -trembling hands impeding one another. Pierre, breathing heavily, -looked around as if asking what it meant. The same question was -expressed in all the looks that met his. - -On the faces of all the Russians and of the French soldiers and -officers without exception, he read the same dismay, horror, and -conflict that were in his own heart. "But who, after all, is doing -this? They are all suffering as I am. Who then is it? Who?" flashed -for an instant through his mind. - -"Sharpshooters of the 86th, forward!" shouted someone. The fifth -prisoner, the one next to Pierre, was led away--alone. Pierre did -not understand that he was saved, that he and the rest had been -brought there only to witness the execution. With ever-growing horror, -and no sense of joy or relief, he gazed at what was taking place. -The fifth man was the factory lad in the loose cloak. The moment -they laid hands on him he sprang aside in terror and clutched at -Pierre. (Pierre shuddered and shook himself free.) The lad was -unable to walk. They dragged him along, holding him up under the arms, -and he screamed. When they got him to the post he grew quiet, as if he -suddenly understood something. Whether he understood that screaming -was useless or whether he thought it incredible that men should kill -him, at any rate he took his stand at the post, waiting to be -blindfolded like the others, and like a wounded animal looked around -him with glittering eyes. - -Pierre was no longer able to turn away and close his eyes. His -curiosity and agitation, like that of the whole crowd, reached the -highest pitch at this fifth murder. Like the others this fifth man -seemed calm; he wrapped his loose cloak closer and rubbed one bare -foot with the other. - -When they began to blindfold him he himself adjusted the knot -which hurt the back of his head; then when they propped him against -the bloodstained post, he leaned back and, not being comfortable in -that position, straightened himself, adjusted his feet, and leaned -back again more comfortably. Pierre did not take his eyes from him and -did not miss his slightest movement. - -Probably a word of command was given and was followed by the reports -of eight muskets; but try as he would Pierre could not afterwards -remember having heard the slightest sound of the shots. He only saw -how the workman suddenly sank down on the cords that held him, how -blood showed itself in two places, how the ropes slackened under the -weight of the hanging body, and how the workman sat down, his head -hanging unnaturally and one leg bent under him. Pierre ran up to the -post. No one hindered him. Pale, frightened people were doing -something around the workman. The lower jaw of an old Frenchman with a -thick mustache trembled as he untied the ropes. The body collapsed. -The soldiers dragged it awkwardly from the post and began pushing it -into the pit. - -They all plainly and certainly knew that they were criminals who -must hide the traces of their guilt as quickly as possible. - -Pierre glanced into the pit and saw that the factory lad was lying -with his knees close up to his head and one shoulder higher than the -other. That shoulder rose and fell rhythmically and convulsively, -but spadefuls of earth were already being thrown over the whole -body. One of the soldiers, evidently suffering, shouted gruffly and -angrily at Pierre to go back. But Pierre did not understand him and -remained near the post, and no one drove him away. - -When the pit had been filled up a command was given. Pierre was -taken back to his place, and the rows of troops on both sides of the -post made a half turn and went past it at a measured pace. The -twenty-four sharpshooters with discharged muskets, standing in the -center of the circle, ran back to their places as the companies passed -by. - -Pierre gazed now with dazed eyes at these sharpshooters who ran in -couples out of the circle. All but one rejoined their companies. -This one, a young soldier, his face deadly pale, his shako pushed -back, and his musket resting on the ground, still stood near the pit -at the spot from which he had fired. He swayed like a drunken man, -taking some steps forward and back to save himself from falling. An -old, noncommissioned officer ran out of the ranks and taking him by -the elbow dragged him to his company. The crowd of Russians and -Frenchmen began to disperse. They all went away silently and with -drooping heads. - -"That will teach them to start fires," said one of the Frenchmen. - -Pierre glanced round at the speaker and saw that it was a soldier -who was trying to find some relief after what had been done, but was -not able to do so. Without finishing what he had begun to say he -made a hopeless movement with his arm and went away. - - - - - -CHAPTER XII - - -After the execution Pierre was separated from the rest of the -prisoners and placed alone in a small, ruined, and befouled church. - -Toward evening a noncommissioned officer entered with two soldiers -and told him that he had been pardoned and would now go to the -barracks for the prisoners of war. Without understanding what was said -to him, Pierre got up and went with the soldiers. They took him to the -upper end of the field, where there were some sheds built of charred -planks, beams, and battens, and led him into one of them. In the -darkness some twenty different men surrounded Pierre. He looked at -them without understanding who they were, why they were there, or what -they wanted of him. He heard what they said, but did not understand -the meaning of the words and made no kind of deduction from or -application of them. He replied to questions they put to him, but -did not consider who was listening to his replies, nor how they -would understand them. He looked at their faces and figures, but -they all seemed to him equally meaningless. - -From the moment Pierre had witnessed those terrible murders -committed by men who did not wish to commit them, it was as if the -mainspring of his life, on which everything depended and which made -everything appear alive, had suddenly been wrenched out and everything -had collapsed into a heap of meaningless rubbish. Though he did not -acknowledge it to himself, his faith in the right ordering of the -universe, in humanity, in his own soul, and in God, had been -destroyed. He had experienced this before, but never so strongly as -now. When similar doubts had assailed him before, they had been the -result of his own wrongdoing, and at the bottom of his heart he had -felt that relief from his despair and from those doubts was to be -found within himself. But now he felt that the universe had crumbled -before his eyes and only meaningless ruins remained, and this not by -any fault of his own. He felt that it was not in his power to regain -faith in the meaning of life. - -Around him in the darkness men were standing and evidently something -about him interested them greatly. They were telling him something and -asking him something. Then they led him away somewhere, and at last he -found himself in a corner of the shed among men who were laughing -and talking on all sides. - -"Well, then, mates... that very prince who..." some voice at the -other end of the shed was saying, with a strong emphasis on the word -who. - -Sitting silent and motionless on a heap of straw against the wall, -Pierre sometimes opened and sometimes closed his eyes. But as soon -as he closed them he saw before him the dreadful face of the factory -lad--especially dreadful because of its simplicity--and the faces of -the murderers, even more dreadful because of their disquiet. And he -opened his eyes again and stared vacantly into the darkness around -him. - -Beside him in a stooping position sat a small man of whose -presence he was first made aware by a strong smell of perspiration -which came from him every time he moved. This man was doing -something to his legs in the darkness, and though Pierre could not see -his face he felt that the man continually glanced at him. On growing -used to the darkness Pierre saw that the man was taking off his leg -bands, and the way he did it aroused Pierre's interest. - -Having unwound the string that tied the band on one leg, he -carefully coiled it up and immediately set to work on the other leg, -glancing up at Pierre. While one hand hung up the first string the -other was already unwinding the band on the second leg. In this way, -having carefully removed the leg bands by deft circular motions of his -arm following one another uninterruptedly, the man hung the leg -bands up on some pegs fixed above his head. Then he took out a -knife, cut something, closed the knife, placed it under the head of -his bed, and, seating himself comfortably, clasped his arms round -his lifted knees and fixed his eyes on Pierre. The latter was -conscious of something pleasant, comforting, and well rounded in these -deft movements, in the man's well-ordered arrangements in his -corner, and even in his very smell, and he looked at the man without -taking his eyes from him. - -"You've seen a lot of trouble, sir, eh?" the little man suddenly -said. - -And there was so much kindliness and simplicity in his singsong -voice that Pierre tried to reply, but his jaw trembled and he felt -tears rising to his eyes. The little fellow, giving Pierre no time -to betray his confusion, instantly continued in the same pleasant -tones: - -"Eh, lad, don't fret!" said he, in the tender singsong caressing -voice old Russian peasant women employ. "Don't fret, friend--'suffer -an hour, live for an age!' that's how it is, my dear fellow. And -here we live, thank heaven, without offense. Among these folk, too, -there are good men as well as bad," said he, and still speaking, he -turned on his knees with a supple movement, got up, coughed, and -went off to another part of the shed. - -"Eh, you rascal!" Pierre heard the same kind voice saying at the -other end of the shed. "So you've come, you rascal? She remembers... -Now, now, that'll do!" - -And the soldier, pushing away a little dog that was jumping up at -him, returned to his place and sat down. In his hands he had something -wrapped in a rag. - -"Here, eat a bit, sir," said he, resuming his former respectful tone -as he unwrapped and offered Pierre some baked potatoes. "We had soup -for dinner and the potatoes are grand!" - -Pierre had not eaten all day and the smell of the potatoes seemed -extremely pleasant to him. He thanked the soldier and began to eat. - -"Well, are they all right?" said the soldier with a smile. "You -should do like this." - -He took a potato, drew out his clasp knife, cut the potato into -two equal halves on the palm of his hand, sprinkled some salt on it -from the rag, and handed it to Pierre. - -"The potatoes are grand!" he said once more. "Eat some like that!" - -Pierre thought he had never eaten anything that tasted better. - -"Oh, I'm all right," said he, "but why did they shoot those poor -fellows? The last one was hardly twenty." - -"Tss, tt...!" said the little man. "Ah, what a sin... what a sin!" -he added quickly, and as if his words were always waiting ready in his -mouth and flew out involuntarily he went on: "How was it, sir, that -you stayed in Moscow?" - -"I didn't think they would come so soon. I stayed accidentally," -replied Pierre. - -"And how did they arrest you, dear lad? At your house?" - -"No, I went to look at the fire, and they arrested me there, and -tried me as an incendiary." - -"Where there's law there's injustice," put in the little man. - -"And have you been here long?" Pierre asked as he munched the last -of the potato. - -"I? It was last Sunday they took me, out of a hospital in Moscow." - -"Why, are you a soldier then?" - -"Yes, we are soldiers of the Apsheron regiment. I was dying of -fever. We weren't told anything. There were some twenty of us lying -there. We had no idea, never guessed at all." - -"And do you feel sad here?" Pierre inquired. - -"How can one help it, lad? My name is Platon, and the surname is -Karataev," he added, evidently wishing to make it easier for Pierre to -address him. "They call me 'little falcon' in the regiment. How is one -to help feeling sad? Moscow--she's the mother of cities. How can one -see all this and not feel sad? But 'the maggot gnaws the cabbage, -yet dies first'; that's what the old folks used to tell us," he -added rapidly. - -"What? What did you say?" asked Pierre. - -"Who? I?" said Karataev. "I say things happen not as we plan but -as God judges," he replied, thinking that he was repeating what he had -said before, and immediately continued: - -"Well, and you, have you a family estate, sir? And a house? So you -have abundance, then? And a housewife? And your old parents, are -they still living?" he asked. - -And though it was too dark for Pierre to see, he felt that a -suppressed smile of kindliness puckered the soldier's lips as he put -these questions. He seemed grieved that Pierre had no parents, -especially that he had no mother. - -"A wife for counsel, a mother-in-law for welcome, but there's none -as dear as one's own mother!" said he. "Well, and have you little -ones?" he went on asking. - -Again Pierre's negative answer seemed to distress him, and he -hastened to add: - -"Never mind! You're young folks yet, and please God may still have -some. The great thing is to live in harmony...." - -"But it's all the same now," Pierre could not help saying. - -"Ah, my dear fellow!" rejoined Karataev, "never decline a prison -or a beggar's sack!" - -He seated himself more comfortably and coughed, evidently -preparing to tell a long story. - -"Well, my dear fellow, I was still living at home," he began. "We -had a well-to-do homestead, plenty of land, we peasants lived well and -our house was one to thank God for. When Father and we went out mowing -there were seven of us. We lived well. We were real peasants. It so -happened..." - -And Platon Karataev told a long story of how he had gone into -someone's copse to take wood, how he had been caught by the keeper, -had been tried, flogged, and sent to serve as a soldier. - -"Well, lad," and a smile changed the tone of his voice "we thought -it was a misfortune but it turned out a blessing! If it had not been -for my sin, my brother would have had to go as a soldier. But he, my -younger brother, had five little ones, while I, you see, only left a -wife behind. We had a little girl, but God took her before I went as a -soldier. I come home on leave and I'll tell you how it was, I look and -see that they are living better than before. The yard full of -cattle, the women at home, two brothers away earning wages, and only -Michael the youngest, at home. Father, he says, 'All my children are -the same to me: it hurts the same whichever finger gets bitten. But if -Platon hadn't been shaved for a soldier, Michael would have had to -go.' called us all to him and, will you believe it, placed us in front -of the icons. 'Michael,' he says, 'come here and bow down to his feet; -and you, young woman, you bow down too; and you, grandchildren, also -bow down before him! Do you understand?' he says. That's how it is, -dear fellow. Fate looks for a head. But we are always judging, 'that's -not well--that's not right!' Our luck is like water in a dragnet: -you pull at it and it bulges, but when you've drawn it out it's empty! -That's how it is." - -And Platon shifted his seat on the straw. - -After a short silence he rose. - -"Well, I think you must be sleepy," said he, and began rapidly -crossing himself and repeating: - -"Lord Jesus Christ, holy Saint Nicholas, Frola and Lavra! Lord Jesus -Christ, holy Saint Nicholas, Frola and Lavra! Lord Jesus Christ, -have mercy on us and save us!" he concluded, then bowed to the ground, -got up, sighed, and sat down again on his heap of straw. "That's the -way. Lay me down like a stone, O God, and raise me up like a loaf," he -muttered as he lay down, pulling his coat over him. - -"What prayer was that you were saying?" asked Pierre. - -"Eh?" murmured Platon, who had almost fallen asleep. "What was I -saying? I was praying. Don't you pray?" - -"Yes, I do," said Pierre. "But what was that you said: Frola and -Lavra?" - -"Well, of course," replied Platon quickly, "the horses' saints. -One must pity the animals too. Eh, the rascal! Now you've curled up -and got warm, you daughter of a bitch!" said Karataev, touching the -dog that lay at his feet, and again turning over he fell asleep -immediately. - -Sounds of crying and screaming came from somewhere in the distance -outside, and flames were visible through the cracks of the shed, but -inside it was quiet and dark. For a long time Pierre did not sleep, -but lay with eyes open in the darkness, listening to the regular -snoring of Platon who lay beside him, and he felt that the world -that had been shattered was once more stirring in his soul with a -new beauty and on new and unshakable foundations. - - - - - -CHAPTER XIII - - -Twenty-three soldiers, three officers, and two officials were -confined in the shed in which Pierre had been placed and where he -remained for four weeks. - -When Pierre remembered them afterwards they all seemed misty figures -to him except Platon Karataev, who always remained in his mind a -most vivid and precious memory and the personification of everything -Russian, kindly, and round. When Pierre saw his neighbor next -morning at dawn the first impression of him, as of something round, -was fully confirmed: Platon's whole figure--in a French overcoat -girdled with a cord, a soldier's cap, and bast shoes--was round. His -head was quite round, his back, chest, shoulders, and even his arms, -which he held as if ever ready to embrace something, were rounded, his -pleasant smile and his large, gentle brown eyes were also round. - -Platon Karataev must have been fifty, judging by his stories of -campaigns he had been in, told as by an old soldier. He did not -himself know his age and was quite unable to determine it. But his -brilliantly white, strong teeth which showed in two unbroken -semicircles when he laughed--as he often did--were all sound and good, -there was not a gray hair in his beard or on his head, and his whole -body gave an impression of suppleness and especially of firmness and -endurance. - -His face, despite its fine, rounded wrinkles, had an expression of -innocence and youth, his voice was pleasant and musical. But the chief -peculiarity of his speech was its directness and appositeness. It -was evident that he never considered what he had said or was going -to say, and consequently the rapidity and justice of his intonation -had an irresistible persuasiveness. - -His physical strength and agility during the first days of his -imprisonment were such that he seemed not to know what fatigue and -sickness meant. Every night before lying down, he said: "Lord, lay -me down as a stone and raise me up as a loaf!" and every morning on -getting up, he said: "I lay down and curled up, I get up and shake -myself." And indeed he only had to lie down, to fall asleep like a -stone, and he only had to shake himself, to be ready without a -moment's delay for some work, just as children are ready to play -directly they awake. He could do everything, not very well but not -badly. He baked, cooked, sewed, planed, and mended boots. He was -always busy, and only at night allowed himself conversation--of -which he was fond--and songs. He did not sing like a trained singer -who knows he is listened to, but like the birds, evidently giving vent -to the sounds in the same way that one stretches oneself or walks -about to get rid of stiffness, and the sounds were always -high-pitched, mournful, delicate, and almost feminine, and his face at -such times was very serious. - -Having been taken prisoner and allowed his beard to grow, he -seemed to have thrown off all that had been forced upon him- -everything military and alien to himself--and had returned to his -former peasant habits. - -"A soldier on leave--a shirt outside breeches," he would say. - -He did not like talking about his life as a soldier, though he did -not complain, and often mentioned that he had not been flogged once -during the whole of his army service. When he related anything it -was generally some old and evidently precious memory of his -"Christian" life, as he called his peasant existence. The proverbs, of -which his talk was full, were for the most part not the coarse and -indecent saws soldiers employ, but those folk sayings which taken -without a context seem so insignificant, but when used appositely -suddenly acquire a significance of profound wisdom. - -He would often say the exact opposite of what he had said on a -previous occasion, yet both would be right. He liked to talk and he -talked well, adorning his speech with terms of endearment and with -folk sayings which Pierre thought he invented himself, but the chief -charm of his talk lay in the fact that the commonest events--sometimes -just such as Pierre had witnessed without taking notice of them- -assumed in Karataev's a character of solemn fitness. He liked to -hear the folk tales one of the soldiers used to tell of an evening -(they were always the same), but most of all he liked to hear -stories of real life. He would smile joyfully when listening to such -stories, now and then putting in a word or asking a question to make -the moral beauty of what he was told clear to himself. Karataev had no -attachments, friendships, or love, as Pierre understood them, but -loved and lived affectionately with everything life brought him in -contact with, particularly with man--not any particular man, but those -with whom he happened to be. He loved his dog, his comrades, the -French, and Pierre who was his neighbor, but Pierre felt that in spite -of Karataev's affectionate tenderness for him (by which he -unconsciously gave Pierre's spiritual life its due) he would not -have grieved for a moment at parting from him. And Pierre began to -feel in the same way toward Karataev. - -To all the other prisoners Platon Karataev seemed a most ordinary -soldier. They called him "little falcon" or "Platosha," chaffed him -good-naturedly, and sent him on errands. But to Pierre he always -remained what he had seemed that first night: an unfathomable, -rounded, eternal personification of the spirit of simplicity and -truth. - -Platon Karataev knew nothing by heart except his prayers. When he -began to speak he seemed not to know how he would conclude. - -Sometimes Pierre, struck by the meaning of his words, would ask -him to repeat them, but Platon could never recall what he had said a -moment before, just as he never could repeat to Pierre the words of -his favorite song: native and birch tree and my heart is sick occurred -in it, but when spoken and not sung, no meaning could be got out of -it. He did not, and could not, understand the meaning of words apart -from their context. Every word and action of his was the manifestation -of an activity unknown to him, which was his life. But his life, as he -regarded it, had no meaning as a separate thing. It had meaning only -as part of a whole of which he was always conscious. His words and -actions flowed from him as evenly, inevitably, and spontaneously as -fragrance exhales from a flower. He could not understand the value -or significance of any word or deed taken separately. - - - - - -CHAPTER XIV - - -When Princess Mary heard from Nicholas that her brother was with the -Rostovs at Yaroslavl she at once prepared to go there, in spite of her -aunt's efforts to dissuade her--and not merely to go herself but to -take her nephew with her. Whether it were difficult or easy, -possible or impossible, she did not ask and did not want to know: it -was her duty not only herself to be near her brother who was perhaps -dying, but to do everything possible to take his son to him, and so -she prepared to set off. That she had not heard from Prince Andrew -himself, Princess Mary attributed to his being too weak to write or to -his considering the long journey too hard and too dangerous for her -and his son. - -In a few days Princess Mary was ready to start. Her equipages were -the huge family coach in which she had traveled to Voronezh, a -semiopen trap, and a baggage cart. With her traveled Mademoiselle -Bourienne, little Nicholas and his tutor, her old nurse, three -maids, Tikhon, and a young footman and courier her aunt had sent to -accompany her. - -The usual route through Moscow could not be thought of, and the -roundabout way Princess Mary was obliged to take through Lipetsk, -Ryazan, Vladimir, and Shuya was very long and, as post horses were not -everywhere obtainable, very difficult, and near Ryazan where the -French were said to have shown themselves was even dangerous. - -During this difficult journey Mademoiselle Bourienne, Dessalles, and -Princess Mary's servants were astonished at her energy and firmness of -spirit. She went to bed later and rose earlier than any of them, and -no difficulties daunted her. Thanks to her activity and energy, -which infected her fellow travelers, they approached Yaroslavl by -the end of the second week. - -The last days of her stay in Voronezh had been the happiest of her -life. Her love for Rostov no longer tormented or agitated her. It -filled her whole soul, had become an integral part of herself, and she -no longer struggled against it. Latterly she had become convinced that -she loved and was beloved, though she never said this definitely to -herself in words. She had become convinced of it at her last interview -with Nicholas, when he had come to tell her that her brother was -with the Rostovs. Not by a single word had Nicholas alluded to the -fact that Prince Andrew's relations with Natasha might, if he -recovered, be renewed, but Princess Mary saw by his face that he -knew and thought of this. - -Yet in spite of that, his relation to her--considerate, delicate, -and loving--not only remained unchanged, but it sometimes seemed to -Princess Mary that he was even glad that the family connection between -them allowed him to express his friendship more freely. She knew -that she loved for the first and only time in her life and felt that -she was beloved, and was happy in regard to it. - -But this happiness on one side of her spiritual nature did not -prevent her feeling grief for her brother with full force; on the -contrary, that spiritual tranquility on the one side made it the -more possible for her to give full play to her feeling for her -brother. That feeling was so strong at the moment of leaving -Voronezh that those who saw her off, as they looked at her careworn, -despairing face, felt sure she would fall ill on the journey. But -the very difficulties and preoccupations of the journey, which she -took so actively in hand, saved her for a while from her grief and -gave her strength. - -As always happens when traveling, Princess Mary thought only of -the journey itself, forgetting its object. But as she approached -Yaroslavl the thought of what might await her there--not after many -days, but that very evening--again presented itself to her and her -agitation increased to its utmost limit. - -The courier who had been sent on in advance to find out where the -Rostovs were staying in Yaroslavl, and in what condition Prince Andrew -was, when he met the big coach just entering the town gates was -appalled by the terrible pallor of the princess' face that looked -out at him from the window. - -"I have found out everything, your excellency: the Rostovs are -staying at the merchant Bronnikov's house, in the Square not far -from here, right above the Volga," said the courier. - -Princess Mary looked at him with frightened inquiry, not -understanding why he did not reply to what she chiefly wanted to know: -how was her brother? Mademoiselle Bourienne put that question for her. - -"How is the prince?" she asked. - -"His excellency is staying in the same house with them." - -"Then he is alive," thought Princess Mary, and asked in a low voice: -"How is he?" - -"The servants say he is still the same." - -What "still the same" might mean Princess Mary did not ask, but with -an unnoticed glance at little seven-year-old Nicholas, who was sitting -in front of her looking with pleasure at the town, she bowed her -head and did not raise it again till the heavy coach, rumbling, -shaking and swaying, came to a stop. The carriage steps clattered as -they were let down. - -The carriage door was opened. On the left there was water--a great -river--and on the right a porch. There were people at the entrance: -servants, and a rosy girl with a large plait of black hair, smiling as -it seemed to Princess Mary in an unpleasantly affected way. (This -was Sonya.) Princess Mary ran up the steps. "This way, this way!" said -the girl, with the same artificial smile, and the princess found -herself in the hall facing an elderly woman of Oriental type, who came -rapidly to meet her with a look of emotion. This was the countess. She -embraced Princess Mary and kissed her. - -"Mon enfant!" she muttered, "je vous aime et vous connais depuis -longtemps."* - - -*"My child! I love you and have known you a long time." - - Despite her excitement, Princess Mary realized that this was the -countess and that it was necessary to say something to her. Hardly -knowing how she did it, she contrived to utter a few polite phrases in -French in the same tone as those that had been addressed to her, and -asked: "How is he?" - -"The doctor says that he is not in danger," said the countess, but -as she spoke she raised her eyes with a sigh, and her gesture conveyed -a contradiction of her words. - -"Where is he? Can I see him--can I?" asked the princess. - -"One moment, Princess, one moment, my dear! Is this his son?" said -the countess, turning to little Nicholas who was coming in with -Dessalles. "There will be room for everybody, this is a big house. Oh, -what a lovely boy!" - -The countess took Princess Mary into the drawing room, where Sonya -was talking to Mademoiselle Bourienne. The countess caressed the -boy, and the old count came in and welcomed the princess. He had -changed very much since Princess Mary had last seen him. Then he had -been a brisk, cheerful, self-assured old man; now he seemed a pitiful, -bewildered person. While talking to Princess Mary he continually -looked round as if asking everyone whether he was doing the right -thing. After the destruction of Moscow and of his property, thrown out -of his accustomed groove he seemed to have lost the sense of his own -significance and to feel that there was no longer a place for him in -life. - -In spite of her one desire to see her brother as soon as possible, -and her vexation that at the moment when all she wanted was to see him -they should be trying to entertain her and pretending to admire her -nephew, the princess noticed all that was going on around her and felt -the necessity of submitting, for a time, to this new order of things -which she had entered. She knew it to be necessary, and though it -was hard for her she was not vexed with these people. - -"This is my niece," said the count, introducing Sonya--"You don't -know her, Princess?" - -Princess Mary turned to Sonya and, trying to stifle the hostile -feeling that arose in her toward the girl, she kissed her. But she -felt oppressed by the fact that the mood of everyone around her was so -far from what was in her own heart. - -"Where is he?" she asked again, addressing them all. - -"He is downstairs. Natasha is with him," answered Sonya, flushing. -"We have sent to ask. I think you must be tired, Princess." - -Tears of vexation showed themselves in Princess Mary's eyes. She -turned away and was about to ask the countess again how to go to -him, when light, impetuous, and seemingly buoyant steps were heard -at the door. The princess looked round and saw Natasha coming in, -almost running--that Natasha whom she had liked so little at their -meeting in Moscow long since. - -But hardly had the princess looked at Natasha's face before she -realized that here was a real comrade in her grief, and consequently a -friend. She ran to meet her, embraced her, and began to cry on her -shoulder. - -As soon as Natasha, sitting at the head of Prince Andrew's bed, -heard of Princess Mary's arrival, she softly left his room and -hastened to her with those swift steps that had sounded buoyant to -Princess Mary. - -There was only one expression on her agitated face when she ran into -the drawing room--that of love--boundless love for him, for her, and -for all that was near to the man she loved; and of pity, suffering for -others, and passionate desire to give herself entirely to helping -them. It was plain that at that moment there was in Natasha's heart no -thought of herself or of her own relations with Prince Andrew. - -Princess Mary, with her acute sensibility, understood all this at -the first glance at Natasha's face, and wept on her shoulder with -sorrowful pleasure. - -"Come, come to him, Mary," said Natasha, leading her into the -other room. - -Princess Mary raised her head, dried her eyes, and turned to -Natasha. She felt that from her she would be able to understand and -learn everything. - -"How..." she began her question but stopped short. - -She felt that it was impossible to ask, or to answer, in words. -Natasha's face eyes would have to tell her all more clearly -and profoundly. - -Natasha was gazing at her, but seemed afraid and in doubt whether to -say all she knew or not; she seemed to feel that before those luminous -eyes which penetrated into the very depths of her heart, it was -impossible not to tell the whole truth which she saw. And suddenly, -Natasha's lips twitched, ugly wrinkles gathered round her mouth, and -covering her face with her hands she burst into sobs. - -Princess Mary understood. - -But she still hoped, and asked, in words she herself did not trust: - -"But how is his wound? What is his general condition?" - -"You, you... will see," was all Natasha could say. - -They sat a little while downstairs near his room till they had -left off crying and were able to go to him with calm faces. - -"How has his whole illness gone? Is it long since he grew worse? -When did this happen?" Princess Mary inquired. - -Natasha told her that at first there had been danger from his -feverish condition and the pain he suffered, but at Troitsa that had -passed and the doctor had only been afraid of gangrene. That danger -had also passed. When they reached Yaroslavl the wound had begun to -fester (Natasha knew all about such things as festering) and the -doctor had said that the festering might take a normal course. Then -fever set in, but the doctor had said the fever was not very serious. - -"But two days ago this suddenly happened," said Natasha, -struggling with her sobs. "I don't know why, but you will see what -he is like." - -"Is he weaker? Thinner?" asked the princess. - -"No, it's not that, but worse. You will see. O, Mary, he is too -good, he cannot, cannot live, because..." - - - - - -CHAPTER XV - - -When Natasha opened Prince Andrew's door with a familiar movement -and let Princess Mary pass into the room before her, the princess felt -the sobs in her throat. Hard as she had tried to prepare herself, -and now tried to remain tranquil, she knew that she would be unable to -look at him without tears. - -The princess understood what Natasha had meant by the words: "two -days ago this suddenly happened." She understood those words to mean -that he had suddenly softened and that this softening and gentleness -were signs of approaching death. As she stepped to the door she -already saw in imagination Andrew's face as she remembered it in -childhood, a gentle, mild, sympathetic face which he had rarely shown, -and which therefore affected her very strongly. She was sure he -would speak soft, tender words to her such as her father had uttered -before his death, and that she would not be able to bear it and -would burst into sobs in his presence. Yet sooner or later it had to -be, and she went in. The sobs rose higher and higher in her throat -as she more and more clearly distinguished his form and her -shortsighted eyes tried to make out his features, and then she saw his -face and met his gaze. - -He was lying in a squirrel-fur dressing gown on a divan, -surrounded by pillows. He was thin and pale. In one thin, -translucently white hand he held a handkerchief, while with the -other he stroked the delicate mustache he had grown, moving his -fingers slowly. His eyes gazed at them as they entered. - -On seeing his face and meeting his eyes Princess Mary's pace -suddenly slackened, she felt her tears dry up and her sobs ceased. She -suddenly felt guilty and grew timid on catching the expression of -his face and eyes. - -"But in what am I to blame?" she asked herself. And his cold, -stern look replied: "Because you are alive and thinking of the living, -while I..." - -In the deep gaze that seemed to look not outwards but -inwards there was an almost hostile expression as he slowly regarded -his sister and Natasha. - -He kissed his sister, holding her hand in his as was their wont. - -"How are you, Mary? How did you manage to get here?" said he in a -voice as calm and aloof as his look. - -Had he screamed in agony, that scream would not have struck such -horror into Princess Mary's heart as the tone of his voice. - -"And have you brought little Nicholas?" he asked in the same slow, -quiet manner and with an obvious effort to remember. - -"How are you now?" said Princess Mary, herself surprised at what she -was saying. - -"That, my dear, you must ask the doctor," he replied, and again -making an evident effort to be affectionate, he said with his lips -only (his words clearly did not correspond to his thoughts): - -"Merci, chere amie, d'etre venue."* - - -*"Thank you for coming, my dear." - - -Princess Mary pressed his hand. The pressure made him wince just -perceptibly. He was silent, and she did not know what to say. She -now understood what had happened to him two days before. In his words, -his tone, and especially in that calm, almost antagonistic look -could be felt an estrangement from everything belonging to this world, -terrible in one who is alive. Evidently only with an effort did he -understand anything living; but it was obvious that he failed to -understand, not because he lacked the power to do so but because he -understood something else--something the living did not and could -not understand--and which wholly occupied his mind. - -"There, you see how strangely fate has brought us together," said -he, breaking the silence and pointing to Natasha. "She looks after -me all the time." - -Princess Mary heard him and did not understand how he could say such -a thing. He, the sensitive, tender Prince Andrew, how could he say -that, before her whom he loved and who loved him? Had he expected to -live he could not have said those words in that offensively cold tone. -If he had not known that he was dying, how could he have failed to -pity her and how could he speak like that in her presence? The only -explanation was that he was indifferent, because something else, -much more important, had been revealed to him. - -The conversation was cold and disconnected and continually broke -off. - -"Mary came by way of Ryazan," said Natasha. - -Prince Andrew did not notice that she called his sister Mary, and -only after calling her so in his presence did Natasha notice it -herself. - -"Really?" he asked. - -"They told her that all Moscow has been burned down, and that..." - -Natasha stopped. It was impossible to talk. It was plain that he was -making an effort to listen, but could not do so. - -"Yes, they say it's burned," he said. "It's a great pity," and he -gazed straight before him, absently stroking his mustache with his -fingers. - -"And so you have met Count Nicholas, Mary?" Prince Andrew suddenly -said, evidently wishing to speak pleasantly to them. "He wrote here -that he took a great liking to you," he went on simply and calmly, -evidently unable to understand all the complex significance his -words had for living people. "If you liked him too, it would be a good -thing for you to get married," he added rather more quickly, as if -pleased at having found words he had long been seeking. - -Princess Mary heard his words but they had no meaning for her, -except as a proof of how far away he now was from everything living. - -"Why talk of me?" she said quietly and glanced at Natasha. - -Natasha, who felt her glance, did not look at her. All three were -again silent. - -"Andrew, would you like..." Princess Mary suddenly said in a -trembling voice, "would you like to see little Nicholas? He is -always talking about you!" - -Prince Andrew smiled just perceptibly and for the first time, but -Princess Mary, who knew his face so well, saw with horror that he -did not smile with pleasure or affection for his son, but with -quiet, gentle irony because he thought she was trying what she -believed to be the last means of arousing him. - -"Yes, I shall be very glad to see him. Is he quite well?" - -When little Nicholas was brought into Prince Andrew's room he looked -at his father with frightened eyes, but did not cry, because no one -else was crying. Prince Andrew kissed him and evidently did not know -what to say to him. - -When Nicholas had been led away, Princess Mary again went up to -her brother, kissed him, and unable to restrain her tears any longer -began to cry. - -He looked at her attentively. - -"Is it about Nicholas?" he asked. - -Princess Mary nodded her head, weeping. - -"Mary, you know the Gosp..." but he broke off. - -"What did you say?" - -"Nothing. You mustn't cry here," he said, looking at her with the -same cold expression. - - -When Princess Mary began to cry, he understood that she was crying -at the thought that little Nicholas would be left without a father. -With a great effort he tried to return to life and to see things -from their point of view. - -"Yes, to them it must seem sad!" he thought. "But how simple it is. - -"The fowls of the air sow not, neither do they reap, yet your Father -feedeth them," he said to himself and wished to say to Princess -Mary; "but no, they will take it their own way, they won't understand! -They can't understand that all those feelings they prize so--all our -feelings, all those ideas that seem so important to us, are -unnecessary. We cannot understand one another," and he remained -silent. - - -Prince Andrew's little son was seven. He could scarcely read, and -knew nothing. After that day he lived through many things, gaining -knowledge, observation, and experience, but had he possessed all the -faculties he afterwards acquired, he could not have had a better or -more profound understanding of the meaning of the scene he had -witnessed between his father, Mary, and Natasha, than he had then. -He understood it completely, and, leaving the room without crying, -went silently up to Natasha who had come out with him and looked shyly -at her with his beautiful, thoughtful eyes, then his uplifted, rosy -upper lip trembled and leaning his head against her he began to cry. - -After that he avoided Dessalles and the countess who caressed him -and either sat alone or came timidly to Princess Mary, or to Natasha -of whom he seemed even fonder than of his aunt, and clung to them -quietly and shyly. - -When Princess Mary had left Prince Andrew she fully understood -what Natasha's face had told her. She did not speak any more to -Natasha of hopes of saving his life. She took turns with her beside -his sofa, and did not cry any more, but prayed continually, turning in -soul to that Eternal and Unfathomable, whose presence above the -dying man was now so evident. - - - - - -CHAPTER XVI - - -Not only did Prince Andrew know he would die, but he felt that he -was dying and was already half dead. He was conscious of an -aloofness from everything earthly and a strange and joyous lightness -of existence. Without haste or agitation he awaited what was coming. -That inexorable, eternal, distant, and unknown the presence of which -he had felt continually all his life--was now near to him and, by -the strange lightness he experienced, almost comprehensible and -palpable... - - -Formerly he had feared the end. He had twice experienced that -terribly tormenting fear of death--the end--but now he no longer -understood that fear. - - He had felt it for the first time when the shell spun like a top -before him, and he looked at the fallow field, the bushes, and the -sky, and knew that he was face to face with death. When he came to -himself after being wounded and the flower of eternal, unfettered love -had instantly unfolded itself in his soul as if freed from the bondage -of life that had restrained it, he no longer feared death and ceased -to think about it. - -During the hours of solitude, suffering, and partial delirium he -spent after he was wounded, the more deeply he penetrated into the new -principle of eternal love revealed to him, the more he unconsciously -detached himself from earthly life. To love everything and everybody -and always to sacrifice oneself for love meant not to love anyone, not -to live this earthly life. And the more imbued he became with that -principle of love, the more he renounced life and the more -completely he destroyed that dreadful barrier which--in the absence of -such love--stands between life and death. When during those first days -he remembered that he would have to die, he said to himself: "Well, -what of it? So much the better!" - -But after the night in Mytishchi when, half delirious, he had seen -her for whom he longed appear before him and, having pressed her -hand to his lips, had shed gentle, happy tears, love for a -particular woman again crept unobserved into his heart and once more -bound him to life. And joyful and agitating thoughts began to occupy -his mind. Recalling the moment at the ambulance station when he had -seen Kuragin, he could not now regain the feeling he then had, but was -tormented by the question whether Kuragin was alive. And he dared -not inquire. - -His illness pursued its normal physical course, but what Natasha -referred to when she said: "This suddenly happened," had occurred -two days before Princess Mary arrived. It was the last spiritual -struggle between life and death, in which death gained the victory. It -was the unexpected realization of the fact that he still valued life -as presented to him in the form of his love for Natasha, and a last, -though ultimately vanquished, attack of terror before the unknown. - -It was evening. As usual after dinner he was slightly feverish, -and his thoughts were preternaturally clear. Sonya was sitting by -the table. He began to doze. Suddenly a feeling of happiness seized -him. - -"Ah, she has come!" thought he. - -And so it was: in Sonya's place sat Natasha who had just come in -noiselessly. - -Since she had begun looking after him, he had always experienced -this physical consciousness of her nearness. She was sitting in an -armchair placed sideways, screening the light of the candle from -him, and was knitting a stocking. She had learned to knit stockings -since Prince Andrew had casually mentioned that no one nursed the sick -so well as old nurses who knit stockings, and that there is -something soothing in the knitting of stockings. The needles clicked -lightly in her slender, rapidly moving hands, and he could clearly see -the thoughtful profile of her drooping face. She moved, and the ball -rolled off her knees. She started, glanced round at him, and screening -the candle with her hand stooped carefully with a supple and exact -movement, picked up the ball, and regained her former position. - -He looked at her without moving and saw that she wanted to draw a -deep breath after stooping, but refrained from doing so and breathed -cautiously. - -At the Troitsa monastery they had spoken of the past, and he had -told her that if he lived he would always thank God for his wound -which had brought them together again, but after that they never spoke -of the future. - -"Can it or can it not be?" he now thought as he looked at her and -listened to the light click of the steel needles. "Can fate have -brought me to her so strangely only for me to die?... Is it possible -that the truth of life has been revealed to me only to show me that -I have spent my life in falsity? I love her more than anything in -the world! But what am I to do if I love her?" he thought, and he -involuntarily groaned, from a habit acquired during his sufferings. - -On hearing that sound Natasha put down the stocking, leaned nearer -to him, and suddenly, noticing his shining eyes, stepped lightly up to -him and bent over him. - -"You are not asleep?" - -"No, I have been looking at you a long time. I felt you come in. -No one else gives me that sense of soft tranquillity that you do... -that light. I want to weep for joy." - -Natasha drew closer to him. Her face shone with rapturous joy. - -"Natasha, I love you too much! More than anything in the world." - -"And I!"--She turned away for an instant. "Why too much?" she asked. - -"Why too much?... Well, what do you, what do you feel in your -soul, your whole soul--shall I live? What do you think?" - -"I am sure of it, sure!" Natasha almost shouted, taking hold of both -his hands with a passionate movement. - -He remained silent awhile. - -"How good it would be!" and taking her hand he kissed it. - -Natasha felt happy and agitated, but at once remembered that this -would not do and that he had to be quiet. - -"But you have not slept," she said, repressing her joy. "Try to -sleep... please!" - -He pressed her hand and released it, and she went back to the candle -and sat down again in her former position. Twice she turned and looked -at him, and her eyes met his beaming at her. She set herself a task on -her stocking and resolved not to turn round till it was finished. - -Soon he really shut his eyes and fell asleep. He did not sleep -long and suddenly awoke with a start and in a cold perspiration. - -As he fell asleep he had still been thinking of the subject that now -always occupied his mind--about life and death, and chiefly about -death. He felt himself nearer to it. - -"Love? What is love?" he thought. - -"Love hinders death. Love is life. All, everything that I -understand, I understand only because I love. Everything is, -everything exists, only because I love. Everything is united by it -alone. Love is God, and to die means that I, a particle of love, shall -return to the general and eternal source." These thoughts seemed to -him comforting. But they were only thoughts. Something was lacking -in them, they were not clear, they were too one-sidedly personal and -brain-spun. And there was the former agitation and obscurity. He -fell asleep. - -He dreamed that he was lying in the room he really was in, but -that he was quite well and unwounded. Many various, indifferent, and -insignificant people appeared before him. He talked to them and -discussed something trivial. They were preparing to go away somewhere. -Prince Andrew dimly realized that all this was trivial and that he had -more important cares, but he continued to speak, surprising them by -empty witticisms. Gradually, unnoticed, all these persons began to -disappear and a single question, that of the closed door, superseded -all else. He rose and went to the door to bolt and lock it. Everything -depended on whether he was, or was not, in time to lock it. He went, -and tried to hurry, but his legs refused to move and he knew he -would not be in time to lock the door though he painfully strained all -his powers. He was seized by an agonizing fear. And that fear was -the fear of death. It stood behind the door. But just when he was -clumsily creeping toward the door, that dreadful something on the -other side was already pressing against it and forcing its way in. -Something not human--death--was breaking in through that door, and had -to be kept out. He seized the door, making a final effort to hold it -back--to lock it was no longer possible--but his efforts were weak and -clumsy and the door, pushed from behind by that terror, opened and -closed again. - -Once again it pushed from outside. His last superhuman efforts -were vain and both halves of the door noiselessly opened. It -entered, and it was death, and Prince Andrew died. - -But at the instant he died, Prince Andrew remembered that he was -asleep, and at the very instant he died, having made an effort, he -awoke. - -"Yes, it was death! I died--and woke up. Yes, death is an -awakening!" And all at once it grew light in his soul and the veil -that had till then concealed the unknown was lifted from his spiritual -vision. He felt as if powers till then confined within him had been -liberated, and that strange lightness did not again leave him. - -When, waking in a cold perspiration, he moved on the divan, -Natasha went up and asked him what was the matter. He did not answer -and looked at her strangely, not understanding. - -That was what had happened to him two days before Princess Mary's -arrival. From that day, as the doctor expressed it, the wasting -fever assumed a malignant character, but what the doctor said did -not interest Natasha, she saw the terrible moral symptoms which to her -were more convincing. - -From that day an awakening from life came to Prince Andrew -together with his awakening from sleep. And compared to the duration -of life it did not seem to him slower than an awakening from sleep -compared to the duration of a dream. - -There was nothing terrible or violent in this comparatively slow -awakening. - -His last days and hours passed in an ordinary and simple way. Both -Princess Mary and Natasha, who did not leave him, felt this. They -did not weep or shudder and during these last days they themselves -felt that they were not attending on him (he was no longer there, he -had left them) but on what reminded them most closely of him--his -body. Both felt this so strongly that the outward and terrible side of -death did not affect them and they did not feel it necessary to foment -their grief. Neither in his presence nor out of it did they weep, -nor did they ever talk to one another about him. They felt that they -could not express in words what they understood. - -They both saw that he was sinking slowly and quietly, deeper and -deeper, away from them, and they both knew that this had to be so -and that it was right. - -He confessed, and received communion: everyone came to take leave of -him. When they brought his son to him, he pressed his lips to the -boy's and turned away, not because he felt it hard and sad (Princess -Mary and Natasha understood that) but simply because he thought it was -all that was required of him, but when they told him to bless the boy, -he did what was demanded and looked round as if asking whether there -was anything else he should do. - -When the last convulsions of the body, which the spirit was leaving, -occurred, Princess Mary and Natasha were present. - -"Is it over?" said Princess Mary when his body had for a few minutes -lain motionless, growing cold before them. Natasha went up, looked -at the dead eyes, and hastened to close them. She closed them but -did not kiss them, but clung to that which reminded her most nearly of -him--his body. - -"Where has he gone? Where is he now?..." - -When the body, washed and dressed, lay in the coffin on a table, -everyone came to take leave of him and they all wept. - -Little Nicholas cried because his heart was rent by painful -perplexity. The countess and Sonya cried from pity for Natasha and -because he was no more. The old count cried because he felt that -before long, he, too, must take the same terrible step. - -Natasha and Princess Mary also wept now, but not because of their -own personal grief; they wept with a reverent and softening emotion -which had taken possession of their souls at the consciousness of -the simple and solemn mystery of death that had been accomplished in -their presence. - - - - - -BOOK THIRTEEN: 1812 - - - - - -CHAPTER I - - -Man's mind cannot grasp the causes of events in their -completeness, but the desire to find those causes is implanted in -man's soul. And without considering the multiplicity and complexity of -the conditions any one of which taken separately may seem to be the -cause, he snatches at the first approximation to a cause that seems to -him intelligible and says: "This is the cause!" In historical events -(where the actions of men are the subject of observation) the first -and most primitive approximation to present itself was the will of the -gods and, after that, the will of those who stood in the most -prominent position--the heroes of history. But we need only -penetrate to the essence of any historic event--which lies in the -activity of the general mass of men who take part in it--to be -convinced that the will of the historic hero does not control the -actions of the mass but is itself continually controlled. It may -seem to be a matter of indifference whether we understand the -meaning of historical events this way or that; yet there is the same -difference between a man who says that the people of the West moved on -the East because Napoleon wished it and a man who says that this -happened because it had to happen, as there is between those who -declared that the earth was stationary and that the planets moved -round it and those who admitted that they did not know what upheld the -earth, but knew there were laws directing its movement and that of the -other planets. There is, and can be, no cause of an historical event -except the one cause of all causes. But there are laws directing -events, and some of these laws are known to us while we are -conscious of others we cannot comprehend. The discovery of these -laws is only possible when we have quite abandoned the -attempt to find the cause in the will of some one man, just as the -discovery of the laws of the motion of the planets was possible only -when men abandoned the conception of the fixity of the earth. - -The historians consider that, next to the battle of Borodino and the -occupation of Moscow by the enemy and its destruction by fire, the -most important episode of the war of 1812 was the movement of the -Russian army from the Ryazana to the Kaluga road and to the Tarutino -camp--the so-called flank march across the Krasnaya Pakhra River. They -ascribe the glory of that achievement of genius to different men and -dispute as to whom the honor is due. Even foreign historians, -including the French, acknowledge the genius of the Russian commanders -when they speak of that flank march. But it is hard to understand -why military writers, and following them others, consider this flank -march to be the profound conception of some one man who saved Russia -and destroyed Napoleon. In the first place it is hard to understand -where the profundity and genius of this movement lay, for not much -mental effort was needed to see that the best position for an army -when it is not being attacked is where there are most provisions; -and even a dull boy of thirteen could have guessed that the best -position for an army after its retreat from Moscow in 1812 was on -the Kaluga road. So it is impossible to understand by what reasoning -the historians reach the conclusion that this maneuver was a -profound one. And it is even more difficult to understand just why -they think that this maneuver was calculated to save Russia and -destroy the French; for this flank march, had it been preceded, -accompanied, or followed by other circumstances, might have proved -ruinous to the Russians and salutary for the French. If the position -of the Russian army really began to improve from the time of that -march, it does not at all follow that the march was the cause of it. - -That flank march might not only have failed to give any advantage to -the Russian army, but might in other circumstances have led to its -destruction. What would have happened had Moscow not burned down? If -Murat had not lost sight of the Russians? If Napoleon had not remained -inactive? If the Russian army at Krasnaya Pakhra had given battle as -Bennigsen and Barclay advised? What would have happened had the French -attacked the Russians while they were marching beyond the Pakhra? What -would have happened if on approaching Tarutino, Napoleon had -attacked the Russians with but a tenth of the energy he had shown when -he attacked them at Smolensk? What would have happened had the -French moved on Petersburg?... In any of these eventualities the flank -march that brought salvation might have proved disastrous. - -The third and most incomprehensible thing is that people studying -history deliberately avoid seeing that this flank march cannot be -attributed to any one man, that no one ever foresaw it, and that in -reality, like the retreat from Fili, it did not suggest itself to -anyone in its entirety, but resulted--moment by moment, step by -step, event by event--from an endless number of most diverse -circumstances and was only seen in its entirety when it had been -accomplished and belonged to the past. - -At the council at Fili the prevailing thought in the minds of the -Russian commanders was the one naturally suggesting itself, namely, -a direct retreat by the Nizhni road. In proof of this there is the -fact that the majority of the council voted for such a retreat, and -above all there is the well-known conversation after the council, -between the commander in chief and Lanskoy, who was in charge of the -commissariat department. Lanskoy informed the commander in chief -that the army supplies were for the most part stored along the Oka -in the Tula and Ryazan provinces, and that if they retreated on Nizhni -the army would be separated from its supplies by the broad river -Oka, which cannot be crossed early in winter. This was the first -indication of the necessity of deviating from what had previously -seemed the most natural course--a direct retreat on Nizhni-Novgorod. -The army turned more to the south, along the Ryazan road and nearer to -its supplies. Subsequently the inactivity of the French (who even -lost sight of the Russian army), concern for the safety of the arsenal -at Tula, and especially the advantages of drawing nearer to its -supplies caused the army to turn still further south to the Tula road. -Having crossed over, by a forced march, to the Tula road beyond the -Pakhra, the Russian commanders intended to remain at Podolsk and had -no thought of the Tarutino position; but innumerable circumstances and -the reappearance of French troops who had for a time lost touch with -the Russians, and projects of giving battle, and above all the -abundance of provisions in Kaluga province, obliged our army to turn -still more to the south and to cross from the Tula to the Kaluga -road and go to Tarutino, which was between the roads along which those -supplies lay. Just as it is impossible to say when it was decided to -abandon Moscow, so it is impossible to say precisely when, or by whom, -it was decided to move to Tarutino. Only when the army had got -there, as the result of innumerable and varying forces, did people -begin to assure themselves that they had desired this movement and -long ago foreseen its result. - - - - - -CHAPTER II - - -The famous flank movement merely consisted in this: after the -advance of the French had ceased, the Russian army, which had been -continually retreating straight back from the invaders, deviated -from that direct course and, not finding itself pursued, was naturally -drawn toward the district where supplies were abundant. - -If instead of imagining to ourselves commanders of genius leading -the Russian army, we picture that army without any leaders, it could -not have done anything but make a return movement toward Moscow, -describing an arc in the direction where most provisions were to be -found and where the country was richest. - -That movement from the Nizhni to the Ryazan, Tula, and Kaluga -roads was so natural that even the Russian marauders moved in that -direction, and demands were sent from Petersburg for Kutuzov to take -his army that way. At Tarutino Kutuzov received what was almost a -reprimand from the Emperor for having moved his army along the -Ryazan road, and the Emperor's letter indicated to him the very -position he had already occupied near Kaluga. - -Having rolled like a ball in the direction of the impetus given by -the whole campaign and by the battle of Borodino, the Russian army- -when the strength of that impetus was exhausted and no fresh push -was received--assumed the position natural to it. - -Kutuzov's merit lay, not in any strategic maneuver of genius, as -it is called, but in the fact that he alone understood the -significance of what had happened. He alone then understood the -meaning of the French army's inactivity, he alone continued to -assert that the battle of Borodino had been a victory, he alone--who -as commander in chief might have been expected to be eager to -attack--employed his whole strength to restrain the Russian army -from useless engagements. - -The beast wounded at Borodino was lying where the fleeing hunter had -left him; but whether he was still alive, whether he was strong and -merely lying low, the hunter did not know. Suddenly the beast was -heard to moan. - -The moan of that wounded beast (the French army) which betrayed -its calamitous condition was the sending of Lauriston to Kutuzov's -camp with overtures for peace. - -Napoleon, with his usual assurance that whatever entered his head -was right, wrote to Kutuzov the first words that occurred to him, -though they were meaningless. - - -MONSIEUR LE PRINCE KOUTOUZOV: I am sending one of my -adjutants-general to discuss several interesting questions with you. I -beg your Highness to credit what he says to you, especially when he -expresses the sentiment of esteem and special regard I have long -entertained for your person. This letter having no other object, I -pray God, monsieur le Prince Koutouzov, to keep you in His holy and -gracious protection! - -NAPOLEON - -MOSCOW, OCTOBER 30, 1812 - - -Kutuzov replied: "I should be cursed by posterity were I looked on -as the initiator of a settlement of any sort. Such is the present -spirit of my nation." But he continued to exert all his powers to -restrain his troops from attacking. - -During the month that the French troops were pillaging in Moscow and -the Russian troops were quietly encamped at Tarutino, a change had -taken place in the relative strength of the two armies--both in spirit -and in number--as a result of which the superiority had passed to -the Russian side. Though the condition and numbers of the French -army were unknown to the Russians, as soon as that change occurred the -need of attacking at once showed itself by countless signs. These -signs were: Lauriston's mission; the abundance of provisions at -Tarutino; the reports coming in from all sides of the inactivity and -disorder of the French; the flow of recruits to our regiments; the -fine weather; the long rest the Russian soldiers had enjoyed, and -the impatience to do what they had been assembled for, which usually -shows itself in an army that has been resting; curiosity as to what -the French army, so long lost sight of, was doing; the boldness with -which our outposts now scouted close up to the French stationed at -Tarutino; the news of easy successes gained by peasants and -guerrilla troops over the French, the envy aroused by this; the desire -for revenge that lay in the heart of every Russian as long as the -French were in Moscow, and (above all) a dim consciousness in every -soldier's mind that the relative strength of the armies had changed -and that the advantage was now on our side. There was a substantial -change in the relative strength, and an advance had become inevitable. -And at once, as a clock begins to strike and chime as soon as the -minute hand has completed a full circle, this change was shown by an -increased activity, whirring, and chiming in the higher spheres. - - - - - -CHAPTER III - - -The Russian army was commanded by Kutuzov and his staff, and also by -the Emperor from Petersburg. Before the news of the abandonment of -Moscow had been received in Petersburg, a detailed plan of the whole -campaign had been drawn up and sent to Kutuzov for his guidance. -Though this plan had been drawn up on the supposition that Moscow -was still in our hands, it was approved by the staff and accepted as a -basis for action. Kutuzov only replied that movements arranged from -a distance were always difficult to execute. So fresh instructions -were sent for the solution of difficulties that might be -encountered, as well as fresh people who were to watch Kutuzov's -actions and report upon them. - -Besides this, the whole staff of the Russian army was now -reorganized. The posts left vacant by Bagration, who had been -killed, and by Barclay, who had gone away in dudgeon, had to be -filled. Very serious consideration was given to the question whether -it would be better to put A in B's place and B in D's, or on the -contrary to put D in A's place, and so on--as if anything more than -A's or B's satisfaction depended on this. - -As a result of the hostility between Kutuzov and Bennigsen, his -Chief of Staff, the presence of confidential representatives of the -Emperor, and these transfers, a more than usually complicated play -of parties was going on among the staff of the army. A was undermining -B, D was undermining C, and so on in all possible combinations and -permutations. In all these plottings the subject of intrigue was -generally the conduct of the war, which all these men believed they -were directing; but this affair of the war went on independently of -them, as it had to go: that is, never in the way people devised, but -flowing always from the essential attitude of the masses. Only in -the highest spheres did all these schemes, crossings, and -interminglings appear to be a true reflection of what had to happen. - - -Prince Michael Ilarionovich! (wrote the Emperor on the second of -October in a letter that reached Kutuzov after the battle at Tarutino) -Since September 2 Moscow has been in the hands of the enemy. Your last -reports were written on the twentieth, and during all this time not -only has no action been taken against the enemy or for the relief of -the ancient capital, but according to your last report you have even -retreated farther. Serpukhov is already occupied by an enemy -detachment and Tula with its famous arsenal so indispensable to the -army, is in danger. From General Wintzingerode's reports, I see that -an enemy corps of ten thousand men is moving on the Petersburg road. -Another corps of several thousand men is moving on Dmitrov. A third -has advanced along the Vladimir road, and a fourth, rather -considerable detachment is stationed between Ruza and Mozhaysk. -Napoleon himself was in Moscow as late as the twenty-fifth. In view of -all this information, when the enemy has scattered his forces in large -detachments, and with Napoleon and his Guards in Moscow, is it -possible that the enemy's forces confronting you are so considerable -as not to allow of your taking the offensive? On the contrary, he is -probably pursuing you with detachments, or at most with an army -corps much weaker than the army entrusted to you. It would seem -that, availing yourself of these circumstances, you might -advantageously attack a weaker one and annihilate him, or at least -oblige him to retreat, retaining in our hands an important part of the -provinces now occupied by the enemy, and thereby averting danger -from Tula and other towns in the interior. You will be responsible -if the enemy is able to direct a force of any size against -Petersburg to threaten this capital in which it has not been -possible to retain many troops; for with the army entrusted to you, -and acting with resolution and energy, you have ample means to avert -this fresh calamity. Remember that you have still to answer to our -offended country for the loss of Moscow. You have experienced my -readiness to reward you. That readiness will not weaken in me, but I -and Russia have a right to expect from you all the zeal, firmness, and -success which your intellect, military talent, and the courage of -the troops you command justify us in expecting. - - -But by the time this letter, which proved that the real relation -of the forces had already made itself felt in Petersburg, was -dispatched, Kutuzov had found himself unable any longer to restrain -the army he commanded from attacking and a battle had taken place. - -On the second of October a Cossack, Shapovalov, who was out -scouting, killed one hare and wounded another. Following the wounded -hare he made his way far into the forest and came upon the left -flank of Murat's army, encamped there without any precautions. The -Cossack laughingly told his comrades how he had almost fallen into the -hands of the French. A cornet, hearing the story, informed his -commander. - -The Cossack was sent for and questioned. The Cossack officers wished -to take advantage of this chance to capture some horses, but one of -the superior officers, who was acquainted with the higher authorities, -reported the incident to a general on the staff. The state of -things on the staff had of late been exceedingly strained. Ermolov had -been to see Bennigsen a few days previously and had entreated him to -use his influence with the commander in chief to induce him to take -the offensive. - -"If I did not know you I should think you did not want what you -are asking for. I need only advise anything and his Highness is sure -to do the opposite," replied Bennigsen. - -The Cossack's report, confirmed by horse patrols who were sent -out, was the final proof that events had matured. The tightly coiled -spring was released, the clock began to whirr and the chimes to -play. Despite all his supposed power, his intellect, his experience, -and his knowledge of men, Kutuzov--having taken into consideration the -Cossack's report, a note from Bennigsen who sent personal reports to -the Emperor, the wishes he supposed the Emperor to hold, and the -fact that all the generals expressed the same wish--could no longer -check the inevitable movement, and gave the order to do what he -regarded as useless and harmful--gave his approval, that is, to the -accomplished fact. - - - - - -CHAPTER IV - - -Bennigsen's note and the Cossack's information that the left flank -of the French was unguarded were merely final indications that it -was necessary to order an attack, and it was fixed for the fifth of -October. - -On the morning of the fourth of October Kutuzov signed the -dispositions. Toll read them to Ermolov, asking him to attend to the -further arrangements. - -"All right--all right. I haven't time just now," replied Ermolov, -and left the hut. - -The dispositions drawn up by Toll were very good. As in the -Austerlitz dispositions, it was written--though not in German this -time: - -"The First Column will march here and here," "the Second Column will -march there and there," and so on; and on paper, all these columns -arrived at their places at the appointed time and destroyed the enemy. -Everything had been admirably thought out as is usual in dispositions, -and as is always the case, not a single column reached its place at -the appointed time. - -When the necessary number of copies of the dispositions had been -prepared, an officer was summoned and sent to deliver them to -Ermolov to deal with. A young officer of the Horse Guards, Kutuzov's -orderly, pleased at the importance of the mission entrusted to him, -went to Ermolov's quarters. - -"Gone away," said Ermolov's orderly. - -The officer of the Horse Guards went to a general with whom -Ermolov was often to be found. - -"No, and the general's out too." - -The officer, mounting his horse, rode off to someone else. - -"No, he's gone out." - -"If only they don't make me responsible for this delay! What a -nuisance it is!" thought the officer, and he rode round the whole -camp. One man said he had seen Ermolov ride past with some other -generals, others said he must have returned home. The officer searched -till six o'clock in the evening without even stopping to eat. -Ermolov was nowhere to be found and no one knew where he was. The -officer snatched a little food at a comrade's, and rode again to the -vanguard to find Miloradovich. Miloradovich too was away, but here -he was told that he had gone to a ball at General Kikin's and that -Ermolov was probably there too. - -"But where is it?" - -"Why, there, over at Echkino," said a Cossack officer, pointing to a -country house in the far distance. - -"What, outside our line?" - -"They've put two regiments as outposts, and they're having such a -spree there, it's awful! Two bands and three sets of singers!" - -The officer rode out beyond our lines to Echkino. While still at a -distance he heard as he rode the merry sounds of a soldier's dance -song proceeding from the house. - -"In the meadows... in the meadows!" he heard, accompanied by -whistling and the sound of a torban, drowned every now and then by -shouts. These sounds made his spirits rise, but at the same time he -was afraid that he would be blamed for not having executed sooner -the important order entrusted to him. It was already past eight -o'clock. He dismounted and went up into the porch of a large country -house which had remained intact between the Russian and French forces. -In the refreshment room and the hall, footmen were bustling about with -wine and viands. Groups of singers stood outside the windows. The -officer was admitted and immediately saw all the chief generals of the -army together, and among them Ermolov's big imposing figure. They -all had their coats unbuttoned and were standing in a semicircle -with flushed and animated faces, laughing loudly. In the middle of the -room a short handsome general with a red face was dancing the trepak -with much spirit and agility. - -"Ha, ha, ha! Bravo, Nicholas Ivanych! Ha, ha, ha!" - -The officer felt that by arriving with important orders at such a -moment he was doubly to blame, and he would have preferred to wait; -but one of the generals espied him and, hearing what he had come -about, informed Ermolov. - -Ermolov came forward with a frown on his face and, hearing what -the officer had to say, took the papers from him without a word. - - -"You think he went off just by chance?" said a comrade, who was on -the staff that evening, to the officer of the Horse Guards, -referring to Ermolov. "It was a trick. It was done on purpose to get -Konovnitsyn into trouble. You'll see what a mess there'll be -tomorrow." - - - - - -CHAPTER V - - -Next day the decrepit Kutuzov, having given orders to be called -early, said his prayers, dressed, and, with an unpleasant -consciousness of having to direct a battle he did not approve of, -got into his caleche and drove from Letashovka (a village three and -a half miles from Tarutino) to the place where the attacking columns -were to meet. He sat in the caleche, dozing and waking up by turns, -and listening for any sound of firing on the right as an indication -that the action had begun. But all was still quiet. A damp dull autumn -morning was just dawning. On approaching Tarutino Kutuzov noticed -cavalrymen leading their horses to water across the road along which -he was driving. Kutuzov looked at them searchingly, stopped his -carriage, and inquired what regiment they belonged to. They belonged -to a column that should have been far in front and in ambush long -before then. "It may be a mistake," thought the old commander in -chief. But a little further on he saw infantry regiments with their -arms piled and the soldiers, only partly dressed, eating their rye -porridge and carrying fuel. He sent for an officer. The officer -reported that no order to advance had been received. - -"How! Not rec..." Kutuzov began, but checked himself immediately and -sent for a senior officer. Getting out of his caleche, he waited -with drooping head and breathing heavily, pacing silently up and down. -When Eykhen, the officer of the general staff whom he had summoned, -appeared, Kutuzov went purple in the face, not because that officer -was to blame for the mistake, but because he was an object of -sufficient importance for him to vent his wrath on. Trembling and -panting the old man fell into that state of fury in which he sometimes -used to roll on the ground, and he fell upon Eykhen, threatening him -with his hands, shouting and loading him with gross abuse. Another -man, Captain Brozin, who happened to turn up and who was not at all to -blame, suffered the same fate. - -"What sort of another blackguard are you? I'll have you shot! -Scoundrels!" yelled Kutuzov in a hoarse voice, waving his arms and -reeling. - -He was suffering physically. He, the commander in chief, a Serene -Highness who everybody said possessed powers such as no man had ever -had in Russia, to be placed in this position--made the laughingstock -of the whole army! "I needn't have been in such a hurry to pray -about today, or have kept awake thinking everything over all night," -thought he to himself. "When I was a chit of an officer no one would -have dared to mock me so... and now!" He was in a state of physical -suffering as if from corporal punishment, and could not avoid -expressing it by cries of anger and distress. But his strength soon -began to fail him, and looking about him, conscious of having said -much that was amiss, he again got into his caleche and drove back in -silence. - -His wrath, once expended, did not return, and blinking feebly he -listened to excuses and self-justifications (Ermolov did not come to -see him till the next day) and to the insistence of Bennigsen, -Konovnitsyn, and Toll that the movement that had miscarried should -be executed next day. And once more Kutuzov had to consent. - - - - - -CHAPTER VI - - -Next day the troops assembled in their appointed places in the -evening and advanced during the night. It was an autumn night with -dark purple clouds, but no rain. The ground was damp but not muddy, -and the troops advanced noiselessly, only occasionally a jingling of -the artillery could be faintly heard. The men were forbidden to talk -out loud, to smoke their pipes, or to strike a light, and they tried -to prevent their horses neighing. The secrecy of the undertaking -heightened its charm and they marched gaily. Some columns, -supposing they had reached their destination, halted, piled arms, and -settled down on the cold ground, but the majority marched all night -and arrived at places where they evidently should not have been. - -Only Count Orlov-Denisov with his Cossacks (the least important -detachment of all) got to his appointed place at the right time. -This detachment halted at the outskirts of a forest, on the path -leading from the village of Stromilova to Dmitrovsk. - -Toward dawn, Count Orlov-Denisov, who had dozed off, was awakened by -a deserter from the French army being brought to him. This was a -Polish sergeant of Poniatowski's corps, who explained in Polish that -he had come over because he had been slighted in the service: that -he ought long ago to have been made an officer, that he was braver -than any of them, and so he had left them and wished to pay them -out. He said that Murat was spending the night less than a mile from -where they were, and that if they would let him have a convoy of a -hundred men he would capture him alive. Count Orlov-Denisov -consulted his fellow officers. - -The offer was too tempting to be refused. Everyone volunteered to go -and everybody advised making the attempt. After much disputing and -arguing, Major-General Grekov with two Cossack regiments decided to go -with the Polish sergeant. - -"Now, remember," said Count Orlov-Denisov to the sergeant at -parting, "if you have been lying I'll have you hanged like a dog; -but if it's true you shall have a hundred gold pieces!" - -Without replying, the sergeant, with a resolute air, mounted and -rode away with Grekov whose men had quickly assembled. They -disappeared into the forest, and Count Orlov-Denisov, having seen -Grekov off, returned, shivering from the freshness of the early dawn -and excited by what he had undertaken on his own responsibility, and -began looking at the enemy camp, now just visible in the deceptive -light of dawn and the dying campfires. Our columns ought to have begun -to appear on an open declivity to his right. He looked in that -direction, but though the columns would have been visible quite far -off, they were not to be seen. It seemed to the count that things were -beginning to stir in the French camp, and his keen-sighted adjutant -confirmed this. - -"Oh, it is really too late," said Count Orlov, looking at the camp. - -As often happens when someone we have trusted is no longer before -our eyes, it suddenly seemed quite clear and obvious to him that the -sergeant was an impostor, that he had lied, and that the whole Russian -attack would be ruined by the absence of those two regiments, which he -would lead away heaven only knew where. How could one capture a -commander in chief from among such a mass of troops! - -"I am sure that rascal was lying," said the count. - -"They can still be called back," said one of his suite, who like -Count Orlov felt distrustful of the adventure when he looked at the -enemy's camp. - -"Eh? Really... what do you think? Should we let them go on or not?" - -"Will you have them fetched back?" - -"Fetch them back, fetch them back!" said Count Orlov with sudden -determination, looking at his watch. "It will be too late. It is quite -light." - -And the adjutant galloped through the forest after Grekov. When -Grekov returned, Count Orlov-Denisov, excited both by the abandoned -attempt and by vainly awaiting the infantry columns that still did not -appear, as well as by the proximity of the enemy, resolved to advance. -All his men felt the same excitement. - -"Mount!" he commanded in a whisper. The men took their places and -crossed themselves.... "Forward, with God's aid!" - -"Hurrah-ah-ah!" reverberated in the forest, and the Cossack -companies, trailing their lances and advancing one after another as if -poured out of a sack, dashed gaily across the brook toward the camp. - -One desperate, frightened yell from the first French soldier who saw -the Cossacks, and all who were in the camp, undressed and only just -waking up, ran off in all directions, abandoning cannons, muskets, and -horses. - -Had the Cossacks pursued the French, without heeding what was behind -and around them, they would have captured Murat and everything -there. That was what the officers desired. But it was impossible to -make the Cossacks budge when once they had got booty and prisoners. -None of them listened to orders. Fifteen hundred prisoners and -thirty-eight guns were taken on the spot, besides standards and -(what seemed most important to the Cossacks) horses, saddles, -horsecloths, and the like. All this had to be dealt with, the -prisoners and guns secured, the booty divided--not without some -shouting and even a little themselves--and it was on this that the -Cossacks all busied themselves. - -The French, not being farther pursued, began to recover -themselves: they formed into detachments and began firing. -Orlov-Denisov, still waiting for the other columns to arrive, advanced -no further. - -Meantime, according to the dispositions which said that "the First -Column will march" and so on, the infantry of the belated columns, -commanded by Bennigsen and directed by Toll, had started in due -order and, as always happens, had got somewhere, but not to their -appointed places. As always happens the men, starting cheerfully, -began to halt; murmurs were heard, there was a sense of confusion, and -finally a backward movement. Adjutants and generals galloped about, -shouted, grew angry, quarreled, said they had come quite wrong and -were late, gave vent to a little abuse, and at last gave it all up and -went forward, simply to get somewhere. "We shall get somewhere or -other!" And they did indeed get somewhere, though not to their right -places; a few eventually even got to their right place, but too late -to be of any use and only in time to be fired at. Toll, who in this -battle played the part of Weyrother at Austerlitz, galloped -assiduously from place to place, finding everything upside down -everywhere. Thus he stumbled on Bagovut's corps in a wood when it -was already broad daylight, though the corps should long before have -joined Orlov-Denisov. Excited and vexed by the failure and supposing -that someone must be responsible for it, Toll galloped up to the -commander of the corps and began upbraiding him severely, saying -that he ought to be shot. General Bagovut, a fighting old soldier of -placid temperament, being also upset by all the delay, confusion, -and cross-purposes, fell into a rage to everybody's surprise and quite -contrary to his usual character and said disagreeable things to Toll. - -"I prefer not to take lessons from anyone, but I can die with my men -as well as anybody," he said, and advanced with a single division. - -Coming out onto a field under the enemy's fire, this brave general -went straight ahead, leading his men under fire, without considering -in his agitation whether going into action now, with a single -division, would be of any use or no. Danger, cannon balls, and bullets -were just what he needed in his angry mood. One of the first bullets -killed him, and other bullets killed many of his men. And his division -remained under fire for some time quite uselessly. - - - - - -CHAPTER VII - - -Meanwhile another column was to have attacked the French from the -front, but Kutuzov accompanied that column. He well knew that -nothing but confusion would come of this battle undertaken against his -will, and as far as was in his power held the troops back. He did -not advance. - -He rode silently on his small gray horse, indolently answering -suggestions that they should attack. - -"The word attack is always on your tongue, but you don't see that we -are unable to execute complicated maneuvers," said he to -Miloradovich who asked permission to advance. - -"We couldn't take Murat prisoner this morning or get to the place in -time, and nothing can be done now!" he replied to someone else. - -When Kutuzov was informed that at the French rear--where according -to the reports of the Cossacks there had previously been nobody--there -were now two battalions of Poles, he gave a sidelong glance at Ermolov -who was behind him and to whom he had not spoken since the previous -day. - -"You see! They are asking to attack and making plans of all kinds, -but as soon as one gets to business nothing is ready, and the enemy, -forewarned, takes measures accordingly." - -Ermolov screwed up his eyes and smiled faintly on hearing these -words. He understood that for him the storm had blown over, and that -Kutuzov would content himself with that hint. - -"He's having a little fun at my expense," said Ermolov softly, -nudging with his knee Raevski who was at his side. - -Soon after this, Ermolov moved up to Kutuzov and respectfully -remarked: - -"It is not too late yet, your Highness--the enemy has not gone away- -if you were to order an attack! If not, the Guards will not so much as -see a little smoke." - -Kutuzov did not reply, but when they reported to him that Murat's -troops were in retreat he ordered an advance, though at every -hundred paces he halted for three quarters of an hour. - -The whole battle consisted in what Orlov-Denisov's Cossacks had -done: the rest of the army merely lost some hundreds of men uselessly. - -In consequence of this battle Kutuzov received a diamond decoration, -and Bennigsen some diamonds and a hundred thousand rubles, others also -received pleasant recognitions corresponding to their various -grades, and following the battle fresh changes were made in the staff. - -"That's how everything is done with us, all topsy-turvy!" said the -Russian officers and generals after the Tarutino battle, letting it be -understood that some fool there is doing things all wrong but that -we ourselves should not have done so, just as people speak today. -But people who talk like that either do not know what they are talking -about or deliberately deceive themselves. No battle--Tarutino, -Borodino, or Austerlitz--takes place as those who planned it -anticipated. That is an essential condition. - -A countless number of free forces (for nowhere is man freer than -during a battle, where it is a question of life and death) influence -the course taken by the fight, and that course never can be known in -advance and never coincides with the direction of any one force. - -If many simultaneously and variously directed forces act on a -given body, the direction of its motion cannot coincide with any one -of those forces, but will always be a mean--what in mechanics is -represented by the diagonal of a parallelogram of forces. - -If in the descriptions given by historians, especially French -ones, we find their wars and battles carried out in accordance with -previously formed plans, the only conclusion to be drawn is that those -descriptions are false. - -The battle of Tarutino obviously did not attain the aim Toll had -in view--to lead the troops into action in the order prescribed by the -dispositions; nor that which Count Orlov-Denisov may have had in view- -to take Murat prisoner; nor the result of immediately destroying the -whole corps, which Bennigsen and others may have had in view; nor -the aim of the officer who wished to go into action to distinguish -himself; nor that of the Cossack who wanted more booty than he got, -and so on. But if the aim of the battle was what actually resulted and -what all the Russians of that day desired--to drive the French out -of Russia and destroy their army--it is quite clear that the battle of -Tarutino, just because of its incongruities, was exactly what was -wanted at that stage of the campaign. It would be difficult and even -impossible to imagine any result more opportune than the actual -outcome of this battle. With a minimum of effort and insignificant -losses, despite the greatest confusion, the most important results -of the whole campaign were attained: the transition from retreat to -advance, an exposure of the weakness of the French, and the -administration of that shock which Napoleon's army had only awaited to -begin its flight. - - - - - -CHAPTER VIII - - -Napoleon enters Moscow after the brilliant victory de la Moskowa; -there can be no doubt about the victory for the battlefield remains in -the hands of the French. The Russians retreat and abandon their -ancient capital. Moscow, abounding in provisions, arms, munitions, and -incalculable wealth, is in Napoleon's hands. The Russian army, only -half the strength of the French, does not make a single attempt to -attack for a whole month. Napoleon's position is most brilliant. He -can either fall on the Russian army with double its strength and -destroy it; negotiate an advantageous peace, or in case of a refusal -make a menacing move on Petersburg, or even, in the case of a reverse, -return to Smolensk or Vilna; or remain in Moscow; in short, no special -genius would seem to be required to retain the brilliant position -the French held at that time. For that, only very simple and easy -steps were necessary: not to allow the troops to loot, to prepare -winter clothing--of which there was sufficient in Moscow for the whole -army--and methodically to collect the provisions, of which -(according to the French historians) there were enough in Moscow to -supply the whole army for six months. Yet Napoleon, that greatest of -all geniuses, who the historians declare had control of the army, took -none of these steps. - -He not merely did nothing of the kind, but on the contrary he used -his power to select the most foolish and ruinous of all the courses -open to him. Of all that Napoleon might have done: wintering in -Moscow, advancing on Petersburg or on Nizhni-Novgorod, or retiring -by a more northerly or more southerly route (say by the road Kutuzov -afterwards took), nothing more stupid or disastrous can be imagined -than what he actually did. He remained in Moscow till October, letting -the troops plunder the city; then, hesitating whether to leave a -garrison behind him, he quitted Moscow, approached Kutuzov without -joining battle, turned to the right and reached Malo-Yaroslavets, -again without attempting to break through and take the road Kutuzov -took, but retiring instead to Mozhaysk along the devastated Smolensk -road. Nothing more stupid than that could have been devised, or more -disastrous for the army, as the sequel showed. Had Napoleon's aim been -to destroy his army, the most skillful strategist could hardly have -devised any series of actions that would so completely have -accomplished that purpose, independently of anything the Russian -army might do. - - -Napoleon, the man of genius, did this! But to say that he -destroyed his army because he wished to, or because he was very -stupid, would be as unjust as to say that he had brought his troops to -Moscow because he wished to and because he was very clever and a -genius. - -In both cases his personal activity, having no more force than the -personal activity of any soldier, merely coincided with the laws -that guided the event. - -The historians quite falsely represent Napoleon's faculties as -having weakened in Moscow, and do so only because the results did -not justify his actions. He employed all his ability and strength to -do the best he could for himself and his army, as he had done -previously and as he did subsequently in 1813. His activity at that -time was no less astounding than it was in Egypt, in Italy, in -Austria, and in Prussia. We do not know for certain in how far his -genius was genuine in Egypt--where forty centuries looked down upon -his grandeur--for his great exploits there are all told us by -Frenchmen. We cannot accurately estimate his genius in Austria or -Prussia, for we have to draw our information from French or German -sources, and the incomprehensible surrender of whole corps without -fighting and of fortresses without a siege must incline Germans to -recognize his genius as the only explanation of the war carried on -in Germany. But we, thank God, have no need to recognize his genius in -order to hide our shame. We have paid for the right to look at the -matter plainly and simply, and we will not abandon that right. - -His activity in Moscow was as amazing and as full of genius as -elsewhere. Order after order order and plan after plan were issued -by him from the time he entered Moscow till the time he left it. The -absence of citizens and of a deputation, and even the burning of -Moscow, did not disconcert him. He did not lose sight either of the -welfare of his army or of the doings of the enemy, or of the welfare -of the people of Russia, or of the direction of affairs in Paris, or -of diplomatic considerations concerning the terms of the anticipated -peace. - - - - - -CHAPTER IX - - -With regard to military matters, Napoleon immediately on his entry -into Moscow gave General Sabastiani strict orders to observe the -movements of the Russian army, sent army corps out along the different -roads, and charged Murat to find Kutuzov. Then he gave careful -directions about the fortification of the Kremlin, and drew up a -brilliant plan for a future campaign over the whole map of Russia. - -With regard to diplomatic questions, Napoleon summoned Captain -Yakovlev, who had been robbed and was in rags and did not know how -to get out of Moscow, minutely explained to him his whole policy and -his magnanimity, and having written a letter to the Emperor -Alexander in which he considered it his duty to inform his Friend -and Brother that Rostopchin had managed affairs badly in Moscow, he -dispatched Yakovlev to Petersburg. - -Having similarly explained his views and his magnanimity to -Tutolmin, he dispatched that old man also to Petersburg to negotiate. - -With regard to legal matters, immediately after the fires he gave -orders to find and execute the incendiaries. And the scoundrel -Rostopchin was punished by an order to burn down his houses. - -With regard to administrative matters, Moscow was granted a -constitution. A municipality was established and the following -announcement issued: - - -INHABITANTS OF MOSCOW! - -Your misfortunes are cruel, but His Majesty the Emperor and King -desires to arrest their course. Terrible examples have taught you -how he punishes disobedience and crime. Strict measures have been -taken to put an end to disorder and to re-establish public security. A -paternal administration, chosen from among yourselves, will form -your municipality or city government. It will take care of you, of -your needs, and of your welfare. Its members will be distinguished -by a red ribbon worn across the shoulder, and the mayor of the city -will wear a white belt as well. But when not on duty they will only -wear a red ribbon round the left arm. - -The city police is established on its former footing, and better -order already prevails in consequence of its activity. The -government has appointed two commissaries general, or chiefs of -police, and twenty commissaries or captains of wards have been -appointed to the different wards of the city. You will recognize -them by the white ribbon they will wear on the left arm. Several -churches of different denominations are open, and divine service is -performed in them unhindered. Your fellow citizens are returning every -day to their homes. and orders have been given that they should find -in them the help and protection due to their misfortunes. These are -the measures the government has adopted to re-establish order and -relieve your condition. But to achieve this aim it is necessary that -you should add your efforts and should, if possible, forget the -misfortunes you have suffered, should entertain the hope of a less -cruel fate, should be certain that inevitable and ignominious death -awaits those who make any attempt on your persons or on what remains -of your property, and finally that you should not doubt that these -will be safeguarded, since such is the will of the greatest and most -just of monarchs. Soldiers and citizens, of whatever nation you may -be, re-establish public confidence, the source of the welfare of a -state, live like brothers, render mutual aid and protection one to -another, unite to defeat the intentions of the evil-minded, obey the -military and civil authorities, and your tears will soon cease to -flow! - - -With regard to supplies for the army, Napoleon decreed that all -the troops in turn should enter Moscow a la maraude* to obtain -provisions for themselves, so that the army might have its future -provided for. - - -*As looters. - - -With regard to religion, Napoleon ordered the priests to be -brought back and services to be again performed in the churches. - -With regard to commerce and to provisioning the army, the -following was placarded everywhere: - - -PROCLAMATION! - -You, peaceful inhabitants of Moscow, artisans and workmen whom -misfortune has driven from the city, and you scattered tillers of -the soil, still kept out in the fields by groundless fear, listen! -Tranquillity is returning to this capital and order is being -restored in it. Your fellow countrymen are emerging boldly from -their hiding places on finding that they are respected. Any violence -to them or to their property is promptly punished. His Majesty the -Emperor and King protects them, and considers no one among you his -enemy except those who disobey his orders. He desires to end your -misfortunes and restore you to your homes and families. Respond, -therefore, to his benevolent intentions and come to us without fear. -Inhabitants, return with confidence to your abodes! You will soon find -means of satisfying your needs. Craftsmen and industrious artisans, -return to your work, your houses, your shops, where the protection -of guards awaits you! You shall receive proper pay for your work. -And lastly you too, peasants, come from the forests where you are -hiding in terror, return to your huts without fear, in full -assurance that you will find protection! Markets are established in -the city where peasants can bring their surplus supplies and the -products of the soil. The government has taken the following steps -to ensure freedom of sale for them: (1) From today, peasants, -husbandmen, and those living in the neighborhood of Moscow may without -any danger bring their supplies of all kinds to two appointed markets, -of which one is on the Mokhovaya Street and the other at the Provision -Market. (2) Such supplies will be bought from them at such prices as -seller and buyer may agree on, and if a seller is unable to obtain a -fair price he will be free to take his goods back to his village and -no one may hinder him under any pretense. (3) Sunday and Wednesday -of each week are appointed as the chief market days and to that end -a sufficient number of troops will be stationed along the highroads on -Tuesdays and Saturdays at such distances from the town as to protect -the carts. (4) Similar measures will be taken that peasants with their -carts and horses may meet with no hindrance on their return journey. -(5) Steps will immediately be taken to re-establish ordinary trading. - -Inhabitants of the city and villages, and you, workingmen and -artisans, to whatever nation you belong, you are called on to carry -out the paternal intentions of His Majesty the Emperor and King and to -co-operate with him for the public welfare! Lay your respect and -confidence at his feet and do not delay to unite with us! - - -With the object of raising the spirits of the troops and of the -people, reviews were constantly held and rewards distributed. The -Emperor rode through the streets to comfort the inhabitants, and, -despite his preoccupation with state affairs, himself visited the -theaters that were established by his order. - -In regard to philanthropy, the greatest virtue of crowned heads, -Napoleon also did all in his power. He caused the words Maison de ma -Mere to be inscribed on the charitable institutions, thereby combining -tender filial affection with the majestic benevolence of a monarch. He -visited the Foundling Hospital and, allowing the orphans saved by -him to kiss his white hands, graciously conversed with Tutolmin. Then, -as Thiers eloquently recounts, he ordered his soldiers to be paid in -forged Russian money which he had prepared: "Raising the use of -these means by an act worthy of himself and of the French army, he let -relief be distributed to those who had been burned out. But as food -was too precious to be given to foreigners, who were for the most part -enemies, Napoleon preferred to supply them with money with which to -purchase food from outside, and had paper rubles distributed to them." - -With reference to army discipline, orders were continually being -issued to inflict severe punishment for the nonperformance of military -duties and to suppress robbery. - - - - - -CHAPTER X - - -But strange to say, all these measures, efforts, and plans--which -were not at all worse than others issued in similar circumstances--did -not affect the essence of the matter but, like the hands of a clock -detached from the mechanism, swung about in an arbitrary and aimless -way without engaging the cogwheels. - -With reference to the military side--the plan of campaign--that work -of genius of which Thiers remarks that, "His genius never devised -anything more profound, more skillful, or more admirable," and -enters into a polemic with M. Fain to prove that this work of genius -must be referred not to the fourth but to the fifteenth of October- -that plan never was or could be executed, for it was quite out of -touch with the facts of the case. The fortifying of the Kremlin, for -which la Mosquee (as Napoleon termed the church of Basil the -Beatified) was to have been razed to the ground, proved quite useless. -The mining of the Kremlin only helped toward fulfilling Napoleon's -wish that it should be blown up when he left Moscow--as a child -wants the floor on which he has hurt himself to be beaten. The pursuit -of the Russian army, about which Napoleon was so concerned, produced -an unheard-of result. The French generals lost touch with the -Russian army of sixty thousand men, and according to Thiers it was -only eventually found, like a lost pin, by the skill--and apparently -the genius--of Murat. - -With reference to diplomacy, all Napoleon's arguments as to his -magnanimity and justice, both to Tutolmin and to Yakovlev (whose chief -concern was to obtain a greatcoat and a conveyance), proved useless; -Alexander did not receive these envoys and did not reply to their -embassage. - -With regard to legal matters, after the execution of the supposed -incendiaries the rest of Moscow burned down. - -With regard to administrative matters, the establishment of a -municipality did not stop the robberies and was only of use to certain -people who formed part of that municipality and under pretext of -preserving order looted Moscow or saved their own property from -being looted. - -With regard to religion, as to which in Egypt matters had so -easily been settled by Napoleon's visit to a mosque, no results were -achieved. Two or three priests who were found in Moscow did try to -carry out Napoleon's wish, but one of them was slapped in the face -by a French soldier while conducting service, and a French official -reported of another that: "The priest whom I found and invited to -say Mass cleaned and locked up the church. That night the doors were -again broken open, the padlocks smashed, the books mutilated, and -other disorders perpetrated." - -With reference to commerce, the proclamation to industrious -workmen and to peasants evoked no response. There were no -industrious workmen, and the peasants caught the commissaries who -ventured too far out of town with the proclamation and killed them. - -As to the theaters for the entertainment of the people and the -troops, these did not meet with success either. The theaters set up in -the Kremlin and in Posnyakov's house were closed again at once because -the actors and actresses were robbed. - -Even philanthropy did not have the desired effect. The genuine as -well as the false paper money which flooded Moscow lost its value. The -French, collecting booty, cared only for gold. Not only was the -paper money valueless which Napoleon so graciously distributed to -the unfortunate, but even silver lost its value in relation to gold. - -But the most amazing example of the ineffectiveness of the orders -given by the authorities at that time was Napoleon's attempt to stop -the looting and re-establish discipline. - -This is what the army authorities were reporting: - -"Looting continues in the city despite the decrees against it. Order -is not yet restored and not a single merchant is carrying on trade -in a lawful manner. The sutlers alone venture to trade, and they -sell stolen goods." - -"The neighborhood of my ward continues to be pillaged by soldiers of -the 3rd Corps who, not satisfied with taking from the unfortunate -inhabitants hiding in the cellars the little they have left, even have -the ferocity to wound them with their sabers, as I have repeatedly -witnessed." - -"Nothing new, except that the soldiers are robbing and pillaging- -October 9." - -"Robbery and pillaging continue. There is a band of thieves in our -district who ought to be arrested by a strong force--October 11." - -"The Emperor is extremely displeased that despite the strict -orders to stop pillage, parties of marauding Guards are continually -seen returning to the Kremlin. Among the Old Guard disorder and -pillage were renewed more violently than ever yesterday evening, -last night, and today. The Emperor sees with regret that the picked -soldiers appointed to guard his person, who should set an example of -discipline, carry disobedience to such a point that they break into -the cellars and stores containing army supplies. Others have disgraced -themselves to the extent of disobeying sentinels and officers, and -have abused and beaten them." - -"The Grand Marshal of the palace," wrote the governor, "complains -bitterly that in spite of repeated orders, the soldiers continue to -commit nuisances in all the courtyards and even under the very windows -of the Emperor." - -That army, like a herd of cattle run wild and trampling underfoot -the provender which might have saved it from starvation, disintegrated -and perished with each additional day it remained in Moscow. But it -did not go away. - -It began to run away only when suddenly seized by a panic caused -by the capture of transport trains on the Smolensk road, and by the -battle of Tarutino. The news of that battle of Tarutino, -unexpectedly received by Napoleon at a review, evoked in him a -desire to punish the Russians (Thiers says), and he issued the order -for departure which the whole army was demanding. - -Fleeing from Moscow the soldiers took with them everything they -had stolen. Napoleon, too, carried away his own personal tresor, but -on seeing the baggage trains that impeded the army, he was (Thiers -says) horror-struck. And yet with his experience of war he did not -order all the superfluous vehicles to be burned, as he had done with -those of a certain marshal when approaching Moscow. He gazed at the -caleches and carriages in which soldiers were riding and remarked that -it was a very good thing, as those vehicles could be used to carry -provisions, the sick, and the wounded. - -The plight of the whole army resembled that of a wounded animal -which feels it is perishing and does not know what it is doing. To -study the skillful tactics and aims of Napoleon and his army from -the time it entered Moscow till it was destroyed is like studying -the dying leaps and shudders of a mortally wounded animal. Very -often a wounded animal, hearing a rustle, rushes straight at the -hunter's gun, runs forward and back again, and hastens its own end. -Napoleon, under pressure from his whole army, did the same thing. -The rustle of the battle of Tarutino frightened the beast, and it -rushed forward onto the hunter's gun, reached him, turned back, and -finally--like any wild beast--ran back along the most -disadvantageous and dangerous path, where the old scent was familiar. - -During the whole of that period Napoleon, who seems to us to have -been the leader of all these movements--as the figurehead of a ship -may seem to a savage to guide the vessel--acted like a child who, -holding a couple of strings inside a carriage, thinks he is driving -it. - - - - - -CHAPTER XI - - -Early in the morning of the sixth of October Pierre went out of -the shed, and on returning stopped by the door to play with a little -blue-gray dog, with a long body and short bandy legs, that jumped -about him. This little dog lived in their shed, sleeping beside -Karataev at night; it sometimes made excursions into the town but -always returned again. Probably it had never had an owner, and it -still belonged to nobody and had no name. The French called it Azor; -the soldier who told stories called it Femgalka; Karataev and others -called it Gray, or sometimes Flabby. Its lack of a master, a name, -or even of a breed or any definite color did not seem to trouble the -blue-gray dog in the least. Its furry tail stood up firm and round -as a plume, its bandy legs served it so well that it would often -gracefully lift a hind leg and run very easily and quickly on three -legs, as if disdaining to use all four. Everything pleased it. Now -it would roll on its back, yelping with delight, now bask in the sun -with a thoughtful air of importance, and now frolic about playing with -a chip of wood or a straw. - -Pierre's attire by now consisted of a dirty torn shirt (the only -remnant of his former clothing), a pair of soldier's trousers which by -Karataev's advice he tied with string round the ankles for warmth, and -a peasant coat and cap. Physically he had changed much during this -time. He no longer seemed stout, though he still had the appearance of -solidity and strength hereditary in his family. A beard and mustache -covered the lower part of his face, and a tangle of hair, infested -with lice, curled round his head like a cap. The look of his eyes -was resolute, calm, and animatedly alert, as never before. The -former slackness which had shown itself even in his eyes was now -replaced by an energetic readiness for action and resistance. His feet -were bare. - -Pierre first looked down the field across which vehicles and -horsemen were passing that morning, then into the distance across -the river, then at the dog who was pretending to be in earnest about -biting him, and then at his bare feet which he placed with pleasure in -various positions, moving his dirty thick big toes. Every time he -looked at his bare feet a smile of animated self-satisfaction -flitted across his face. The sight of them reminded him of all he -had experienced and learned during these weeks and this recollection -was pleasant to him. - -For some days the weather had been calm and clear with slight frosts -in the mornings--what is called an "old wives' summer." - -In the sunshine the air was warm, and that warmth was particularly -pleasant with the invigorating freshness of the morning frost still in -the air. - -On everything--far and near--lay the magic crystal glitter seen only -at that time autumn. The Sparrow Hills were visible in the distance, -with the village, the church, and the large white house. The bare -trees, the sand, the bricks and roofs of the houses, the green -church spire, and the corners of the white house in the distance, -all stood out in the transparent air in most delicate outline and with -unnatural clearness. Near by could be seen the familiar ruins of a -half-burned mansion occupied by the French, with lilac bushes still -showing dark green beside the fence. And even that ruined and befouled -house--which in dull weather was repulsively ugly--seemed quietly -beautiful now, in the clear, motionless brilliance. - -A French corporal, with coat unbuttoned in a homely way, a -skullcap on his head, and a short pipe in his mouth, came from -behind a corner of the shed and approached Pierre with a friendly -wink. - -"What sunshine, Monsieur Kiril!" (Their name for Pierre.) "Eh? -Just like spring!" - -And the corporal leaned against the door and offered Pierre his -pipe, though whenever he offered it Pierre always declined it. - -"To be on the march in such weather..." he began. - -Pierre inquired what was being said about leaving, and the -corporal told him that nearly all the troops were starting and there -ought to be an order about the prisoners that day. Sokolov, one of the -soldiers in the shed with Pierre, was dying, and Pierre told the -corporal that something should be done about him. The corporal replied -that Pierre need not worry about that as they had an ambulance and a -permanent hospital and arrangements would be made for the sick, and -that in general everything that could happen had been foreseen by -the authorities. - -"Besides, Monsieur Kiril, you have only to say a word to the -captain, you know. He is a man who never forgets anything. Speak to -the captain when he makes his round, he will do anything for you." - -(The captain of whom the corporal spoke often had long chats with -Pierre and showed him all sorts of favors.) - -"'You see, St. Thomas,' he said to me the other day. 'Monsieur Kiril -is a man of education, who speaks French. He is a Russian seigneur who -has had misfortunes, but he is a man. He knows what's what.... If he -wants anything and asks me, he won't get a refusal. When one has -studied, you see, one likes education and well-bred people.' It is for -your sake I mention it, Monsieur Kiril. The other day if it had not -been for you that affair would have ended ill." - -And after chatting a while longer, the corporal went away. (The -affair he had alluded to had happened a few days before--a fight -between the prisoners and the French soldiers, in which Pierre had -succeeded in pacifying his comrades.) Some of the prisoners who had -heard Pierre talking to the corporal immediately asked what the -Frenchman had said. While Pierre was repeating what he had been told -about the army leaving Moscow, a thin, sallow, tattered French soldier -came up to the door of the shed. Rapidly and timidly raising his -fingers to his forehead by way of greeting, he asked Pierre whether -the soldier Platoche to whom he had given a shirt to sew was in that -shed. - -A week before the French had had boot leather and linen issued to -them, which they had given out to the prisoners to make up into -boots and shirts for them. - -"Ready, ready, dear fellow!" said Karataev, coming out with a neatly -folded shirt. - -Karataev, on account of the warm weather and for convenience at -work, was wearing only trousers and a tattered shirt as black as soot. -His hair was bound round, workman fashion, with a wisp of lime-tree -bast, and his round face seemed rounder and pleasanter than ever. - -"A promise is own brother to performance! I said Friday and here -it is, ready," said Platon, smiling and unfolding the shirt he had -sewn. - -The Frenchman glanced around uneasily and then, as if overcoming his -hesitation, rapidly threw off his uniform and put on the shirt. He had -a long, greasy, flowered silk waistcoat next to his sallow, thin -bare body, but no shirt. He was evidently afraid the prisoners looking -on would laugh at him, and thrust his head into the shirt hurriedly. -None of the prisoners said a word. - -"See, it fits well!" Platon kept repeating, pulling the shirt -straight. - -The Frenchman, having pushed his head and hands through, without -raising his eyes, looked down at the shirt and examined the seams. - -"You see, dear man, this is not a sewing shop, and I had no proper -tools; and, as they say, one needs a tool even to kill a louse," -said Platon with one of his round smiles, obviously pleased with his -work. - -"It's good, quite good, thank you," said the Frenchman, in French, -"but there must be some linen left over. - -"It will fit better still when it sets to your body," said Karataev, -still admiring his handiwork. "You'll be nice and comfortable...." - -"Thanks, thanks, old fellow.... But the bits left over?" said the -Frenchman again and smiled. He took out an assignation ruble note -and gave it to Karataev. "But give me the pieces that are over." - -Pierre saw that Platon did not want to understand what the Frenchman -was saying, and he looked on without interfering. Karataev thanked the -Frenchman for the money and went on admiring his own work. The -Frenchman insisted on having the pieces returned that were left over -and asked Pierre to translate what he said. - -"What does he want the bits for?" said Karataev. "They'd make fine -leg bands for us. Well, never mind." - -And Karataev, with a suddenly changed and saddened expression, -took a small bundle of scraps from inside his shirt and gave it to the -Frenchman without looking at him. "Oh dear!" muttered Karataev and -went away. The Frenchman looked at the linen, considered for a moment, -then looked inquiringly at Pierre and, as if Pierre's look had told -him something, suddenly blushed and shouted in a squeaky voice: - -"Platoche! Eh, Platoche! Keep them yourself!" And handing back the -odd bits he turned and went out. - -"There, look at that," said Karataev, swaying his head. "People said -they were not Christians, but they too have souls. It's what the old -folk used to say: 'A sweating hand's an open hand, a dry hand's -close.' He's naked, but yet he's given it back." - -Karataev smiled thoughtfully and was silent awhile looking at the -pieces. - -"But they'll make grand leg bands, dear friend," he said, and went -back into the shed. - - - - - -CHAPTER XII - - -Four weeks had passed since Pierre had been taken prisoner and -though the French had offered to move him from the men's to the -officers' shed, he had stayed in the shed where he was first put. - -In burned and devastated Moscow Pierre experienced almost the -extreme limits of privation a man can endure; but thanks to his -physical strength and health, of which he had till then been -unconscious, and thanks especially to the fact that the privations -came so gradually that it was impossible to say when they began, he -endured his position not only lightly but joyfully. And just at this -time he obtained the tranquillity and ease of mind he had formerly -striven in vain to reach. He had long sought in different ways that -tranquillity of mind, that inner harmony which had so impressed him in -the soldiers at the battle of Borodino. He had sought it in -philanthropy, in Freemasonry, in the dissipations of town life, in -wine, in heroic feats of self-sacrifice, and in romantic love for -Natasha; he had sought it by reasoning--and all these quests and -experiments had failed him. And now without thinking about it he had -found that peace and inner harmony only through the horror of death, -through privation, and through what he recognized in Karataev. - -Those dreadful moments he had lived through at the executions had as -it were forever washed away from his imagination and memory the -agitating thoughts and feelings that had formerly seemed so important. -It did not now occur to him to think of Russia, or the war, or -politics, or Napoleon. It was plain to him that all these things -were no business of his, and that he was not called on to judge -concerning them and therefore could not do so. "Russia and summer -weather are not bound together," he thought, repeating words of -Karataev's which he found strangely consoling. His intention of -killing Napoleon and his calculations of the cabalistic number of -the beast of the Apocalypse now seemed to him meaningless and even -ridiculous. His anger with his wife and anxiety that his name should -not be smirched now seemed not merely trivial but even amusing. What -concern was it of his that somewhere or other that woman was leading -the life she preferred? What did it matter to anybody, and -especially to him, whether or not they found out that their prisoner's -name was Count Bezukhov? - -He now often remembered his conversation with Prince Andrew and -quite agreed with him, though he understood Prince Andrew's thoughts -somewhat differently. Prince Andrew had thought and said that -happiness could only be negative, but had said it with a shade of -bitterness and irony as though he was really saying that all desire -for positive happiness is implanted in us merely to torment us and -never be satisfied. But Pierre believed it without any mental -reservation. The absence of suffering, the satisfaction of one's needs -and consequent freedom in the choice of one's occupation, that is, -of one's way of life, now seemed to Pierre to be indubitably man's -highest happiness. Here and now for the first time he fully -appreciated the enjoyment of eating when he wanted to eat, drinking -when he wanted to drink, sleeping when he wanted to sleep, of warmth -when he was cold, of talking to a fellow man when he wished to talk -and to hear a human voice. The satisfaction of one's needs--good food, -cleanliness, and freedom--now that he was deprived of all this, seemed -to Pierre to constitute perfect happiness; and the choice of -occupation, that is, of his way of life--now that that was so -restricted--seemed to him such an easy matter that he forgot that a -superfluity of the comforts of life destroys all joy in satisfying -one's needs, while great freedom in the choice of occupation--such -freedom as his wealth, his education, and his social position had -given him in his own life--is just what makes the choice of occupation -insolubly difficult and destroys the desire and possibility of -having an occupation. - -All Pierre's daydreams now turned on the time when he would be free. -Yet subsequently, and for the rest of his life, he thought and spoke -with enthusiasm of that month of captivity, of those irrecoverable, -strong, joyful sensations, and chiefly of the complete peace of mind -and inner freedom which he experienced only during those weeks. - -When on the first day he got up early, went out of the shed at dawn, -and saw the cupolas and crosses of the New Convent of the Virgin still -dark at first, the hoarfrost on the dusty grass, the Sparrow Hills, -and the wooded banks above the winding river vanishing in the purple -distance, when he felt the contact of the fresh air and heard the -noise of the crows flying from Moscow across the field, and when -afterwards light gleamed from the east and the sun's rim appeared -solemnly from behind a cloud, and the cupolas and crosses, the -hoarfrost, the distance and the river, all began to sparkle in the -glad light--Pierre felt a new joy and strength in life such as he -had never before known. And this not only stayed with him during the -whole of his imprisonment, but even grew in strength as the -hardships of his position increased. - -That feeling of alertness and of readiness for anything was still -further strengthened in him by the high opinion his fellow prisoners -formed of him soon after his arrival at the shed. With his knowledge -of languages, the respect shown him by the French, his simplicity, his -readiness to give anything asked of him (he received the allowance -of three rubles a week made to officers); with his strength, which -he showed to the soldiers by pressing nails into the walls of the hut; -his gentleness to his companions, and his capacity for sitting still -and thinking without doing anything (which seemed to them -incomprehensible), he appeared to them a rather mysterious and -superior being. The very qualities that had been a hindrance, if not -actually harmful, to him in the world he had lived in--his strength, -his disdain for the comforts of life, his absent-mindedness and -simplicity--here among these people gave him almost the status of a -hero. And Pierre felt that their opinion placed responsibilities -upon him. - - - - -CHAPTER XIII - - -The French evacuation began on the night between the sixth and -seventh of October: kitchens and sheds were dismantled, carts -loaded, and troops and baggage trains started. - -At seven in the morning a French convoy in marching trim, wearing -shakos and carrying muskets, knapsacks, and enormous sacks, stood in -front of the sheds, and animated French talk mingled with curses -sounded all along the lines. - -In the shed everyone was ready, dressed, belted, shod, and only -awaited the order to start. The sick soldier, Sokolov, pale and thin -with dark shadows round his eyes, alone sat in his place barefoot -and not dressed. His eyes, prominent from the emaciation of his -face, gazed inquiringly at his comrades who were paying no attention -to him, and he moaned regularly and quietly. It was evidently not so -much his sufferings that caused him to moan (he had dysentery) as -his fear and grief at being left alone. - -Pierre, girt with a rope round his waist and wearing shoes -Karataev had made for him from some leather a French soldier had -torn off a tea chest and brought to have his boots mended with, went -up to the sick man and squatted down beside him. - -"You know, Sokolov, they are not all going away! They have a -hospital here. You may be better off than we others," said Pierre. - -"O Lord! Oh, it will be the death of me! O Lord!" moaned the man -in a louder voice. - -"I'll go and ask them again directly," said Pierre, rising and going -to the door of the shed. - -Just as Pierre reached the door, the corporal who had offered him -a pipe the day before came up to it with two soldiers. The corporal -and soldiers were in marching kit with knapsacks and shakos that had -metal straps, and these changed their familiar faces. - -The corporal came, according to orders, to shut the door. The -prisoners had to be counted before being let out. - -"Corporal, what will they do with the sick man?..." Pierre began. - -But even as he spoke he began to doubt whether this was the corporal -he knew or a stranger, so unlike himself did the corporal seem at that -moment. Moreover, just as Pierre was speaking a sharp rattle of -drums was suddenly heard from both sides. The corporal frowned at -Pierre's words and, uttering some meaningless oaths, slammed the door. -The shed became semidark, and the sharp rattle of the drums on two -sides drowned the sick man's groans. - -"There it is!... It again!..." said Pierre to himself, and an -involuntary shudder ran down his spine. In the corporal's changed -face, in the sound of his voice, in the stirring and deafening noise -of the drums, he recognized that mysterious, callous force which -compelled people against their will to kill their fellow men--that -force the effect of which he had witnessed during the executions. To -fear or to try to escape that force, to address entreaties or -exhortations to those who served as its tools, was useless. Pierre -knew this now. One had to wait and endure. He did not again go to -the sick man, nor turn to look at him, but stood frowning by the -door of the hut. - -When that door was opened and the prisoners, crowding against one -another like a flock of sheep, squeezed into the exit, Pierre pushed -his way forward and approached that very captain who as the corporal -had assured him was ready to do anything for him. The captain was also -in marching kit, and on his cold face appeared that same it which -Pierre had recognized in the corporal's words and in the roll of the -drums. - -"Pass on, pass on!" the captain reiterated, frowning sternly, and -looking at the prisoners who thronged past him. - -Pierre went up to him, though he knew his attempt would be vain. - -"What now?" the officer asked with a cold look as if not recognizing -Pierre. - -Pierre told him about the sick man. - -"He'll manage to walk, devil take him!" said the captain. "Pass -on, pass on!" he continued without looking at Pierre. - -"But he is dying," Pierre again began. - -"Be so good..." shouted the captain, frowning angrily. - -"Dram-da-da-dam, dam-dam..." rattled the drums, and Pierre -understood that this mysterious force completely controlled these -men and that it was now useless to say any more. - -The officer prisoners were separated from the soldiers and told to -march in front. There were about thirty officers, with Pierre among -them, and about three hundred men. - -The officers, who had come from the other sheds, were all -strangers to Pierre and much better dressed than he. They looked at -him and at his shoes mistrustfully, as at an alien. Not far from him -walked a fat major with a sallow, bloated, angry face, who was wearing -a Kazan dressing grown tied round with a towel, and who evidently -enjoyed the respect of his fellow prisoners. He kept one hand, in -which he clasped his tobacco pouch, inside the bosom of his dressing -gown and held the stem of his pipe firmly with the other. Panting -and puffing, the major grumbled and growled at everybody because he -thought he was being pushed and that they were all hurrying when -they had nowhere to hurry to and were all surprised at something -when there was nothing to be surprised at. Another, a thin little -officer, was speaking to everyone, conjecturing where they were now -being taken and how far they would get that day. An official in felt -boots and wearing a commissariat uniform ran round from side to side -and gazed at the ruins of Moscow, loudly announcing his observations -as to what had been burned down and what this or that part of the city -was that they could see. A third officer, who by his accent was a -Pole, disputed with the commissariat officer, arguing that he was -mistaken in his identification of the different wards of Moscow. - -"What are you disputing about?" said the major angrily. "What does -it matter whether it is St. Nicholas or St. Blasius? You see it's -burned down, and there's an end of it.... What are you pushing for? -Isn't the road wide enough?" said he, turning to a man behind him -who was not pushing him at all. - -"Oh, oh, oh! What have they done?" the prisoners on one side and -another were heard saying as they gazed on the charred ruins. "All -beyond the river, and Zubova, and in the Kremlin.... Just look! -There's not half of it left. Yes, I told you--the whole quarter beyond -the river, and so it is." - -"Well, you know it's burned, so what's the use of talking?" said the -major. - -As they passed near a church in the Khamovniki (one of the few -unburned quarters of Moscow) the whole mass of prisoners suddenly -started to one side and exclamations of horror and disgust were heard. - -"Ah, the villains! What heathens! Yes; dead, dead, so he is... And -smeared with something!" - -Pierre too drew near the church where the thing was that evoked -these exclamations, and dimly made out something leaning against the -palings surrounding the church. From the words of his comrades who saw -better than he did, he found that this was the body of a man, set -upright against the palings with its face smeared with soot. - -"Go on! What the devil... Go on! Thirty thousand devils!..." the -convoy guards began cursing and the French soldiers, with fresh -virulence, drove away with their swords the crowd of prisoners who -were gazing at the dead man. - - - - - -CHAPTER XIV - - -Through the cross streets of the Khamovniki quarter the prisoners -marched, followed only by their escort and the vehicles and wagons -belonging to that escort, but when they reached the supply stores they -came among a huge and closely packed train of artillery mingled with -private vehicles. - -At the bridge they all halted, waiting for those in front to get -across. From the bridge they had a view of endless lines of moving -baggage trains before and behind them. To the right, where the -Kaluga road turns near Neskuchny, endless rows of troops and carts -stretched away into the distance. These were troops of Beauharnais' -corps which had started before any of the others. Behind, along the -riverside and across the Stone Bridge, were Ney's troops and -transport. - -Davout's troops, in whose charge were the prisoners, were crossing -the Crimean bridge and some were already debouching into the Kaluga -road. But the baggage trains stretched out so that the last of -Beauharnais' train had not yet got out of Moscow and reached the -Kaluga road when the vanguard of Ney's army was already emerging -from the Great Ordynka Street. - -When they had crossed the Crimean bridge the prisoners moved a few -steps forward, halted, and again moved on, and from all sides vehicles -and men crowded closer and closer together. They advanced the few -hundred paces that separated the bridge from the Kaluga road, taking -more than an hour to do so, and came out upon the square where the -streets of the Transmoskva ward and the Kaluga road converge, and -the prisoners jammed close together had to stand for some hours at -that crossway. From all sides, like the roar of the sea, were heard -the rattle of wheels, the tramp of feet, and incessant shouts of anger -and abuse. Pierre stood pressed against the wall of a charred house, -listening to that noise which mingled in his imagination with the roll -of the drums. - -To get a better view, several officer prisoners climbed onto the -wall of the half-burned house against which Pierre was leaning. - -"What crowds! Just look at the crowds!... They've loaded goods -even on the cannon! Look there, those are furs!" they exclaimed. "Just -see what the blackguards have looted.... There! See what that one -has behind in the cart.... Why, those are settings taken from some -icons, by heaven!... Oh, the rascals!... See how that fellow has -loaded himself up, he can hardly walk! Good lord, they've even grabbed -those chaises!... See that fellow there sitting on the trunks.... -Heavens! They're fighting." - -"That's right, hit him on the snout--on his snout! Like this, we -shan't get away before evening. Look, look there.... Why, that must be -Napoleon's own. See what horses! And the monograms with a crown! -It's like a portable house.... That fellow's dropped his sack and -doesn't see it. Fighting again... A woman with a baby, and not -bad-looking either! Yes, I dare say, that's the way they'll let you -pass... Just look, there's no end to it. Russian wenches, by heaven, -so they are! In carriages--see how comfortably they've settled -themselves!" - -Again, as at the church in Khamovniki, a wave of general curiosity -bore all the prisoners forward onto the road, and Pierre, thanks to -his stature, saw over the heads of the others what so attracted -their curiosity. In three carriages involved among the munition carts, -closely squeezed together, sat women with rouged faces, dressed in -glaring colors, who were shouting something in shrill voices. - -From the moment Pierre had recognized the appearance of the -mysterious force nothing had seemed to him strange or dreadful: -neither the corpse smeared with soot for fun nor these women -hurrying away nor the burned ruins of Moscow. All that he now -witnessed scarcely made an impression on him--as if his soul, making -ready for a hard struggle, refused to receive impressions that might -weaken it. - -The women's vehicles drove by. Behind them came more carts, -soldiers, wagons, soldiers, gun carriages, carriages, soldiers, -ammunition carts, more soldiers, and now and then women. - -Pierre did not see the people as individuals but saw their movement. - -All these people and horses seemed driven forward by some -invisible power. During the hour Pierre watched them they all came -flowing from the different streets with one and the same desire to get -on quickly; they all jostled one another, began to grow angry and to -fight, white teeth gleamed, brows frowned, ever the same words of -abuse flew from side to side, and all the faces bore the same -swaggeringly resolute and coldly cruel expression that had struck -Pierre that morning on the corporal's face when the drums were -beating. - -It was not till nearly evening that the officer commanding the -escort collected his men and with shouts and quarrels forced his way -in among the baggage trains, and the prisoners, hemmed in on all -sides, emerged onto the Kaluga road. - -They marched very quickly, without resting, and halted only when the -sun began to set. The baggage carts drew up close together and the men -began to prepare for their night's rest. They all appeared angry and -dissatisfied. For a long time, oaths, angry shouts, and fighting could -be heard from all sides. A carriage that followed the escort ran -into one of the carts and knocked a hole in it with its pole. -Several soldiers ran toward the cart from different sides: some beat -the carriage horses on their heads, turning them aside, others -fought among themselves, and Pierre saw that one German was badly -wounded on the head by a sword. - -It seemed that all these men, now that they had stopped amid -fields in the chill dusk of the autumn evening, experienced one and -the same feeling of unpleasant awakening from the hurry and -eagerness to push on that had seized them at the start. Once at a -standstill they all seemed to understand that they did not yet know -where they were going, and that much that was painful and difficult -awaited them on this journey. - -During this halt the escort treated the prisoners even worse than -they had done at the start. It was here that the prisoners for the -first time received horseflesh for their meat ration. - -From the officer down to the lowest soldier they showed what -seemed like personal spite against each of the prisoners, in -unexpected contrast to their former friendly relations. - -This spite increased still more when, on calling over the roll of -prisoners, it was found that in the bustle of leaving Moscow one -Russian soldier, who had pretended to suffer from colic, had -escaped. Pierre saw a Frenchman beat a Russian soldier cruelly for -straying too far from the road, and heard his friend the captain -reprimand and threaten to court-martial a noncommissioned officer on -account of the escape of the Russian. To the noncommissioned officer's -excuse that the prisoner was ill and could not walk, the officer -replied that the order was to shoot those who lagged behind. Pierre -felt that that fatal force which had crushed him during the -executions, but which he had not felt during his imprisonment, now -again controlled his existence. It was terrible, but he felt that in -proportion to the efforts of that fatal force to crush him, there grew -and strengthened in his soul a power of life independent of it. - -He ate his supper of buckwheat soup with horseflesh and chatted with -his comrades. - -Neither Pierre nor any of the others spoke of what they had seen -in Moscow, or of the roughness of their treatment by the French, or of -the order to shoot them which had been announced to them. As if in -reaction against the worsening of their position they were all -particularly animated and gay. They spoke of personal reminiscences, -of amusing scenes they had witnessed during the campaign, and -avoided all talk of their present situation. - -The sun had set long since. Bright stars shone out here and there in -the sky. A red glow as of a conflagration spread above the horizon -from the rising full moon, and that vast red ball swayed strangely -in the gray haze. It grew light. The evening was ending, but the night -had not yet come. Pierre got up and left his new companions, -crossing between the campfires to the other side of the road where -he had been told the common soldier prisoners were stationed. He -wanted to talk to them. On the road he was stopped by a French -sentinel who ordered him back. - -Pierre turned back, not to his companions by the campfire, but to an -unharnessed cart where there was nobody. Tucking his legs under him -and dropping his head he sat down on the cold ground by the wheel of -the cart and remained motionless a long while sunk in thought. -Suddenly he burst out into a fit of his broad, good-natured -laughter, so loud that men from various sides turned with surprise -to see what this strange and evidently solitary laughter could mean. - -"Ha-ha-ha!" laughed Pierre. And he said aloud to himself: "The -soldier did not let me pass. They took me and shut me up. They hold me -captive. What, me? Me? My immortal soul? Ha-ha-ha! Ha-ha-ha!..." and -he laughed till tears started to his eyes. - -A man got up and came to see what this queer big fellow was laughing -at all by himself. Pierre stopped laughing, got up, went farther -away from the inquisitive man, and looked around him. - -The huge, endless bivouac that had previously resounded with the -crackling of campfires and the voices of many men had grown quiet, the -red campfires were growing paler and dying down. High up in the -light sky hung the full moon. Forests and fields beyond the camp, -unseen before, were now visible in the distance. And farther still, -beyond those forests and fields, the bright, oscillating, limitless -distance lured one to itself. Pierre glanced up at the sky and the -twinkling stars in its faraway depths. "And all that is me, all that -is within me, and it is all I!" thought Pierre. "And they caught all -that and put it into a shed boarded up with planks!" He smiled, and -went and lay down to sleep beside his companions. - - - - - -CHAPTER XV - - -In the early days of October another envoy came to Kutuzov with a -letter from Napoleon proposing peace and falsely dated from Moscow, -though Napoleon was already not far from Kutuzov on the old Kaluga -road. Kutuzov replied to this letter as he had done to the one -formerly brought by Lauriston, saying that there could be no -question of peace. - -Soon after that a report was received from Dorokhov's guerrilla -detachment operating to the left of Tarutino that troops of -Broussier's division had been seen at Forminsk and that being -separated from the rest of the French army they might easily be -destroyed. The soldiers and officers again demanded action. Generals -on the staff, excited by the memory of the easy victory at Tarutino, -urged Kutuzov to carry out Dorokhov's suggestion. Kutuzov did not -consider any offensive necessary. The result was a compromise which -was inevitable: a small detachment was sent to Forminsk to attack -Broussier. - -By a strange coincidence, this task, which turned out to be a most -difficult and important one, was entrusted to Dokhturov--that same -modest little Dokhturov whom no one had described to us as drawing -up plans of battles, dashing about in front of regiments, showering -crosses on batteries, and so on, and who was thought to be and was -spoken of as undecided and undiscerning--but whom we find commanding -wherever the position was most difficult all through the -Russo-French wars from Austerlitz to the year 1813. At Austerlitz he -remained last at the Augezd dam, rallying the regiments, saving what -was possible when all were flying and perishing and not a single -general was left in the rear guard. Ill with fever he went to Smolensk -with twenty thousand men to defend the town against Napoleon's whole -army. In Smolensk, at the Malakhov Gate, he had hardly dozed off in -a paroxysm of fever before he was awakened by the bombardment of the -town--and Smolensk held out all day long. At the battle of Borodino, -when Bagration was killed and nine tenths of the men of our left flank -had fallen and the full force of the French artillery fire was -directed against it, the man sent there was this same irresolute and -undiscerning Dokhturov--Kutuzov hastening to rectify a mistake he -had made by sending someone else there first. And the quiet little -Dokhturov rode thither, and Borodino became the greatest glory of -the Russian army. Many heroes have been described to us in verse and -prose, but of Dokhturov scarcely a word has been said. - -It was Dokhturov again whom they sent to Forminsk and from there -to Malo-Yaroslavets, the place where the last battle with the French -was fought and where the obvious disintegration of the French army -began; and we are told of many geniuses and heroes of that period of -the campaign, but of Dokhturov nothing or very little is said and that -dubiously. And this silence about Dokhturov is the clearest -testimony to his merit. - -It is natural for a man who does not understand the workings of a -machine to imagine that a shaving that has fallen into it by chance -and is interfering with its action and tossing about in it is its most -important part. The man who does not understand the construction of -the machine cannot conceive that the small connecting cogwheel which -revolves quietly is one of the most essential parts of the machine, -and not the shaving which merely harms and hinders the working. - -On the tenth of October when Dokhturov had gone halfway to -Forminsk and stopped at the village of Aristovo, preparing -faithfully to execute the orders he had received, the whole French -army having, in its convulsive movement, reached Murat's position -apparently in order to give battle--suddenly without any reason turned -off to the left onto the new Kaluga road and began to enter -Forminsk, where only Broussier had been till then. At that time -Dokhturov had under his command, besides Dorokhov's detachment, the -two small guerrilla detachments of Figner and Seslavin. - -On the evening of October 11 Seslavin came to the Aristovo -headquarters with a French guardsman he had captured. The prisoner -said that the troops that had entered Forminsk that day were the -vanguard of the whole army, that Napoleon was there and the whole army -had left Moscow four days previously. That same evening a house serf -who had come from Borovsk said he had seen an immense army entering -the town. Some Cossacks of Dokhturov's detachment reported having -sighted the French Guards marching along the road to Borovsk. From all -these reports it was evident that where they had expected to meet a -single division there was now the whole French army marching from -Moscow in an unexpected direction--along the Kaluga road. Dokhturov -was unwilling to undertake any action, as it was not clear to him -now what he ought to do. He had been ordered to attack Forminsk. But -only Broussier had been there at that time and now the whole French -army was there. Ermolov wished to act on his own judgment, but -Dokhturov insisted that he must have Kutuzov's instructions. So it was -decided to send a dispatch to the staff. - -For this purpose a capable officer, Bolkhovitinov, was chosen, who -was to explain the whole affair by word of mouth, besides delivering a -written report. Toward midnight Bolkhovitinov, having received the -dispatch and verbal instructions, galloped off to the General Staff -accompanied by a Cossack with spare horses. - - - - - -CHAPTER XVI - - -It was a warm, dark, autumn night. It had been raining for four -days. Having changed horses twice and galloped twenty miles in an hour -and a half over a sticky, muddy road, Bolkhovitinov reached Litashevka -after one o'clock at night. Dismounting at a cottage on whose wattle -fence hung a signboard, GENERAL STAFF, and throwing down his reins, he -entered a dark passage. - -"The general on duty, quick! It's very important!" said he to -someone who had risen and was sniffing in the dark passage. - -"He has been very unwell since the evening and this is the third -night he has not slept," said the orderly pleadingly in a whisper. -"You should wake the captain first." - -"But this is very important, from General Dokhturov," said -Bolkhovitinov, entering the open door which he had found by feeling in -the dark. - -The orderly had gone in before him and began waking somebody. - -"Your honor, your honor! A courier." - -"What? What's that? From whom?" came a sleepy voice. - -"From Dokhturov and from Alexey Petrovich. Napoleon is at Forminsk," -said Bolkhovitinov, unable to see in the dark who was speaking but -guessing by the voice that it was not Konovnitsyn. - -The man who had wakened yawned and stretched himself. - -"I don't like waking him," he said, fumbling for something. "He is -very ill. Perhaps this is only a rumor." - -"Here is the dispatch," said Bolkhovitinov. "My orders are to give -it at once to the general on duty." - -"Wait a moment, I'll light a candle. You damned rascal, where do you -always hide it?" said the voice of the man who was stretching himself, -to the orderly. (This was Shcherbinin, Konovnitsyn's adjutant.) -"I've found it, I've found it!" he added. - -The orderly was striking a light and Shcherbinin was fumbling for -something on the candlestick. - -"Oh, the nasty beasts!" said he with disgust. - -By the light of the sparks Bolkhovitinov saw Shcherbinin's -youthful face as he held the candle, and the face of another man who -was still asleep. This was Konovnitsyn. - -When the flame of the sulphur splinters kindled by the tinder burned -up, first blue and then red, Shcherbinin lit the tallow candle, from -the candlestick of which the cockroaches that had been gnawing it were -running away, and looked at the messenger. Bolkhovitinov was -bespattered all over with mud and had smeared his face by wiping it -with his sleeve. - -"Who gave the report?" inquired Shcherbinin, taking the envelope. - -"The news is reliable," said Bolkhovitinov. "Prisoners, Cossacks, -and the scouts all say the same thing." - -"There's nothing to be done, we'll have to wake him," said -Shcherbinin, rising and going up to the man in the nightcap who lay -covered by a greatcoat. "Peter Petrovich!" said he. (Konovnitsyn did -not stir.) "To the General Staff!" he said with a smile, knowing -that those words would be sure to arouse him. - -And in fact the head in the nightcap was lifted at once. On -Konovnitsyn's handsome, resolute face with cheeks flushed by fever, -there still remained for an instant a faraway dreamy expression remote -from present affairs, but then he suddenly started and his face -assumed its habitual calm and firm appearance. - -"Well, what is it? From whom?" he asked immediately but without -hurry, blinking at the light. - -While listening to the officer's report Konovnitsyn broke the seal -and read the dispatch. Hardly had he done so before he lowered his -legs in their woolen stockings to the earthen floor and began -putting on his boots. Then he took off his nightcap, combed his hair -over his temples, and donned his cap. - -"Did you get here quickly? Let us go to his Highness." - -Konovnitsyn had understood at once that the news brought was of -great importance and that no time must be lost. He did not consider or -ask himself whether the news was good or bad. That did not interest -him. He regarded the whole business of the war not with his -intelligence or his reason but by something else. There was within him -a deep unexpressed conviction that all would be well, but that one -must not trust to this and still less speak about it, but must only -attend to one's own work. And he did his work, giving his whole -strength to the task. - -Peter Petrovich Konovnitsyn, like Dokhturov, seems to have been -included merely for propriety's sake in the list of the so-called -heroes of 1812--the Barclays, Raevskis, Ermolovs, Platovs, and -Miloradoviches. Like Dokhturov he had the reputation of being a man of -very limited capacity and information, and like Dokhturov he never -made plans of battle but was always found where the situation was most -difficult. Since his appointment as general on duty he had always -slept with his door open, giving orders that every messenger should be -allowed to wake him up. In battle he was always under fire, so that -Kutuzov reproved him for it and feared to send him to the front, and -like Dokhturov he was one of those unnoticed cogwheels that, without -clatter or noise, constitute the most essential part of the machine. - -Coming out of the hut into the damp, dark night Konovnitsyn frowned- -partly from an increased pain in his head and partly at the unpleasant -thought that occurred to him, of how all that nest of influential -men on the staff would be stirred up by this news, especially -Bennigsen, who ever since Tarutino had been at daggers drawn with -Kutuzov; and how they would make suggestions, quarrel, issue orders, -and rescind them. And this premonition was disagreeable to him -though he knew it could not be helped. - -And in fact Toll, to whom he went to communicate the news, -immediately began to expound his plans to a general sharing his -quarters, until Konovnitsyn, who listened in weary silence, reminded -him that they must go to see his Highness. - - - - - -CHAPTER XVII - - -Kutuzov like all old people did not sleep much at night. He often -fell asleep unexpectedly in the daytime, but at night, lying on his -bed without undressing, he generally remained awake thinking. - -So he lay now on his bed, supporting his large, heavy, scarred -head on his plump hand, with his one eye open, meditating and -peering into the darkness. - -Since Bennigsen, who corresponded with the Emperor and had more -influence than anyone else on the staff, had begun to avoid him, -Kutuzov was more at ease as to the possibility of himself and his -troops being obliged to take part in useless aggressive movements. The -lesson of the Tarutino battle and of the day before it, which -Kutuzov remembered with pain, must, he thought, have some effect on -others too. - -"They must understand that we can only lose by taking the offensive. -Patience and time are my warriors, my champions," thought Kutuzov. -He knew that an apple should not be plucked while it is green. It will -fall of itself when ripe, but if picked unripe the apple is spoiled, -the tree is harmed, and your teeth are set on edge. Like an -experienced sportsman he knew that the beast was wounded, and -wounded as only the whole strength of Russia could have wounded it, -but whether it was mortally wounded or not was still an undecided -question. Now by the fact of Lauriston and Barthelemi having been -sent, and by the reports of the guerrillas, Kutuzov was almost sure -that the wound was mortal. But he needed further proofs and it was -necessary to wait. - -"They want to run to see how they have wounded it. Wait and we shall -see! Continual maneuvers, continual advances!" thought he. "What -for? Only to distinguish themselves! As if fighting were fun. They are -like children from whom one can't get any sensible account of what has -happened because they all want to show how well they can fight. But -that's not what is needed now. - -"And what ingenious maneuvers they all propose to me! It seems to -them that when they have thought of two or three contingencies" (he -remembered the general plan sent him from Petersburg) "they have -foreseen everything. But the contingencies are endless." - -The undecided question as to whether the wound inflicted at Borodino -was mortal or not had hung over Kutuzov's head for a whole month. On -the one hand the French had occupied Moscow. On the other Kutuzov felt -assured with all his being that the terrible blow into which he and -all the Russians had put their whole strength must have been mortal. -But in any case proofs were needed; he had waited a whole month for -them and grew more impatient the longer he waited. Lying on his bed -during those sleepless nights he did just what he reproached those -younger generals for doing. He imagined all sorts of possible -contingencies, just like the younger men, but with this difference, -that he saw thousands of contingencies instead of two or three and -based nothing on them. The longer he thought the more contingencies -presented themselves. He imagined all sorts of movements of the -Napoleonic army as a whole or in sections--against Petersburg, or -against him, or to outflank him. He thought too of the possibility -(which he feared most of all) that Napoleon might fight him with his -own weapon and remain in Moscow awaiting him. Kutuzov even imagined -that Napoleon's army might turn back through Medyn and Yukhnov, but -the one thing he could not foresee was what happened--the insane, -convulsive stampede of Napoleon's army during its first eleven days -after leaving Moscow: a stampede which made possible what Kutuzov -had not yet even dared to think of--the complete extermination of -the French. Dorokhov's report about Broussier's division, the -guerrillas' reports of distress in Napoleon's army, rumors of -preparations for leaving Moscow, all confirmed the supposition that -the French army was beaten and preparing for flight. But these were -only suppositions, which seemed important to the younger men but not -to Kutuzov. With his sixty years' experience he knew what value to -attach to rumors, knew how apt people who desire anything are to group -all news so that it appears to confirm what they desire, and he knew -how readily in such cases they omit all that makes for the contrary. -And the more he desired it the less he allowed himself to believe -it. This question absorbed all his mental powers. All else was to -him only life's customary routine. To such customary routine -belonged his conversations with the staff, the letters he wrote from -Tarutino to Madame de Stael, the reading of novels, the distribution -of awards, his correspondence with Petersburg, and so on. But the -destruction of the French, which he alone foresaw, was his heart's one -desire. - -On the night of the eleventh of October he lay leaning on his arm -and thinking of that. - -There was a stir in the next room and he heard the steps of Toll, -Konovnitsyn, and Bolkhovitinov. - -"Eh, who's there? Come in, come in! What news?" the field marshal -called out to them. - -While a footman was lighting a candle, Toll communicated the -substance of the news. - -"Who brought it?" asked Kutuzov with a look which, when the candle -was lit, struck Toll by its cold severity. - -"There can be no doubt about it, your Highness." - -"Call him in, call him here." - -Kutuzov sat up with one leg hanging down from the bed and his big -paunch resting against the other which was doubled under him. He -screwed up his seeing eye to scrutinize the messenger more -carefully, as if wishing to read in his face what preoccupied his -own mind. - -"Tell me, tell me, friend," said he to Bolkhovitinov in his low, -aged voice, as he pulled together the shirt which gaped open on his -chest, "come nearer--nearer. What news have you brought me? Eh? That -Napoleon has left Moscow? Are you sure? Eh?" - -Bolkhovitinov gave a detailed account from the beginning of all he -had been told to report. - -"Speak quicker, quicker! Don't torture me!" Kutuzov interrupted him. - -Bolkhovitinov told him everything and was then silent, awaiting -instructions. Toll was beginning to say something but Kutuzov -checked him. He tried to say something, but his face suddenly puckered -and wrinkled; he waved his arm at Toll and turned to the opposite side -of the room, to the corner darkened by the icons that hung there. - -"O Lord, my Creator, Thou has heard our prayer..." said he in a -tremulous voice with folded hands. "Russia is saved. I thank Thee, O -Lord!" and he wept. - - - - - -CHAPTER XVIII - - -From the time he received this news to the end of the campaign all -Kutuzov's activity was directed toward restraining his troops, by -authority, by guile, and by entreaty, from useless attacks, maneuvers, -or encounters with the perishing enemy. Dokhturov went to -Malo-Yaroslavets, but Kutuzov lingered with the main army and gave -orders for the evacuation of Kaluga--a retreat beyond which town -seemed to him quite possible. - -Everywhere Kutuzov retreated, but the enemy without waiting for -his retreat fled in the opposite direction. - -Napoleon's historians describe to us his skilled maneuvers at -Tarutino and Malo-Yaroslavets, and make conjectures as to what would -have happened had Napoleon been in time to penetrate into the rich -southern provinces. - -But not to speak of the fact that nothing prevented him from -advancing into those southern provinces (for the Russian army did -not bar his way), the historians forget that nothing could have -saved his army, for then already it bore within itself the germs of -inevitable ruin. How could that army--which had found abundant -supplies in Moscow and had trampled them underfoot instead of -keeping them, and on arriving at Smolensk had looted provisions -instead of storing them--how could that army recuperate in Kaluga -province, which was inhabited by Russians such as those who lived in -Moscow, and where fire had the same property of consuming what was set -ablaze? - -That army could not recover anywhere. Since the battle of Borodino -and the pillage of Moscow it had borne within itself, as it were, -the chemical elements of dissolution. - -The members of what had once been an army--Napoleon himself and -all his soldiers fled--without knowing whither, each concerned only to -make his escape as quickly as possible from this position, of the -hopelessness of which they were all more or less vaguely conscious. - -So it came about that at the council at Malo-Yaroslavets, when the -generals pretending to confer together expressed various opinions, all -mouths were closed by the opinion uttered by the simple-minded soldier -Mouton who, speaking last, said what they all felt: that the one thing -needful was to get away as quickly as possible; and no one, not even -Napoleon, could say anything against that truth which they all -recognized. - -But though they all realized that it was necessary to get away, -there still remained a feeling of shame at admitting that they must -flee. An external shock was needed to overcome that shame, and this -shock came in due time. It was what the French called "le hourra de -l'Empereur." - -The day after the council at Malo-Yaroslavets Napoleon rode out -early in the morning amid the lines of his army with his suite of -marshals and an escort, on the pretext of inspecting the army and -the scene of the previous and of the impending battle. Some Cossacks -on the prowl for booty fell in with the Emperor and very nearly -captured him. If the Cossacks did not capture Napoleon then, what -saved him was the very thing that was destroying the French army, -the booty on which the Cossacks fell. Here as at Tarutino they went -after plunder, leaving the men. Disregarding Napoleon they rushed -after the plunder and Napoleon managed to escape. - -When les enfants du Don might so easily have taken the Emperor -himself in the midst of his army, it was clear that there was -nothing for it but to fly as fast as possible along the nearest, -familiar road. Napoleon with his forty-year-old stomach understood -that hint, not feeling his former agility and boldness, and under -the influence of the fright the Cossacks had given him he at once -agreed with Mouton and issued orders--as the historians tell us--to -retreat by the Smolensk road. - -That Napoleon agreed with Mouton, and that the army retreated, -does not prove that Napoleon caused it to retreat, but that the forces -which influenced the whole army and directed it along the Mozhaysk -(that is, the Smolensk) road acted simultaneously on him also. - - - - - -CHAPTER XIX - - -A man in motion always devises an aim for that motion. To be able to -go a thousand miles he must imagine that something good awaits him -at the end of those thousand miles. One must have the prospect of a -promised land to have the strength to move. - -The promised land for the French during their advance had been -Moscow, during their retreat it was their native land. But that native -land was too far off, and for a man going a thousand miles it is -absolutely necessary to set aside his final goal and to say to -himself: "Today I shall get to a place twenty-five miles off where I -shall rest and spend the night," and during the first day's journey -that resting place eclipses his ultimate goal and attracts all his -hopes and desires. And the impulses felt by a single person are always -magnified in a crowd. - -For the French retreating along the old Smolensk road, the final -goal--their native land--was too remote, and their immediate goal -was Smolensk, toward which all their desires and hopes, enormously -intensified in the mass, urged them on. It was not that they knew that -much food and fresh troops awaited them in Smolensk, nor that they -were told so (on the contrary their superior officers, and Napoleon -himself, knew that provisions were scarce there), but because this -alone could give them strength to move on and endure their present -privations. So both those who knew and those who did not know deceived -themselves, and pushed on to Smolensk as to a promised land. - -Coming out onto the highroad the French fled with surprising -energy and unheard-of rapidity toward the goal they had fixed on. -Besides the common impulse which bound the whole crowd of French -into one mass and supplied them with a certain energy, there was -another cause binding them together--their great numbers. As with -the physical law of gravity, their enormous mass drew the individual -human atoms to itself. In their hundreds of thousands they moved -like a whole nation. - -Each of them desired nothing more than to give himself up as a -prisoner to escape from all this horror and misery; but on the one -hand the force of this common attraction to Smolensk, their goal, drew -each of them in the same direction; on the other hand an army corps -could not surrender to a company, and though the French availed -themselves of every convenient opportunity to detach themselves and to -surrender on the slightest decent pretext, such pretexts did not -always occur. Their very numbers and their crowded and swift -movement deprived them of that possibility and rendered it not only -difficult but impossible for the Russians to stop this movement, to -which the French were directing all their energies. Beyond a certain -limit no mechanical disruption of the body could hasten the process of -decomposition. - -A lump of snow cannot be melted instantaneously. There is a -certain limit of time in less than which no amount of heat can melt -the snow. On the contrary the greater the heat the more solidified the -remaining snow becomes. - -Of the Russian commanders Kutuzov alone understood this. When the -flight of the French army along the Smolensk road became well defined, -what Konovnitsyn had foreseen on the night of the eleventh of -October began to occur. The superior officers all wanted to -distinguish themselves, to cut off, to seize, to capture, and to -overthrow the French, and all clamored for action. - -Kutuzov alone used all his power (and such power is very limited -in the case of any commander in chief) to prevent an attack. - -He could not tell them what we say now: "Why fight, why block the -road, losing our own men and inhumanly slaughtering unfortunate -wretches? What is the use of that, when a third of their army has -melted away on the road from Moscow to Vyazma without any battle?" But -drawing from his aged wisdom what they could understand, he told -them of the golden bridge, and they laughed at and slandered him, -flinging themselves on, rending and exulting over the dying beast. - -Ermolov, Miloradovich, Platov, and others in proximity to the French -near Vyazma could not resist their desire to cut off and break up -two French corps, and by way of reporting their intention to Kutuzov -they sent him a blank sheet of paper in an envelope. - -And try as Kutuzov might to restrain the troops, our men attacked, -trying to bar the road. Infantry regiments, we are told, advanced to -the attack with music and with drums beating, and killed and lost -thousands of men. - -But they did not cut off or overthrow anybody and the French army, -closing up more firmly at the danger, continued, while steadily -melting away, to pursue its fatal path to Smolensk. - - - - - - -BOOK FOURTEEN: 1812 - - - - - -CHAPTER I - - -The Battle of Borodino, with the occupation of Moscow that -followed it and the flight of the French without further conflicts, is -one of the most instructive phenomena in history. - -All historians agree that the external activity of states and -nations in their conflicts with one another is expressed in wars, -and that as a direct result of greater or less success in war the -political strength of states and nations increases or decreases. - -Strange as may be the historical account of how some king or -emperor, having quarreled with another, collects an army, fights his -enemy's army, gains a victory by killing three, five, or ten -thousand men, and subjugates a kingdom and an entire nation of several -millions, all the facts of history (as far as we know it) confirm -the truth of the statement that the greater or lesser success of one -army against another is the cause, or at least an essential -indication, of an increase or decrease in the strength of the -nation--even though it is unintelligible why the defeat of an army- -a hundredth part of a nation--should oblige that whole nation to -submit. An army gains a victory, and at once the rights of the -conquering nation have increased to the detriment of the defeated. -An army has suffered defeat, and at once a people loses its rights -in proportion to the severity of the reverse, and if its army -suffers a complete defeat the nation is quite subjugated. - -So according to history it has been found from the most ancient -times, and so it is to our own day. All Napoleon's wars serve to -confirm this rule. In proportion to the defeat of the Austrian army -Austria loses its rights, and the rights and the strength of France -increase. The victories of the French at Jena and Auerstadt destroy -the independent existence of Prussia. - -But then, in 1812, the French gain a victory near Moscow. Moscow -is taken and after that, with no further battles, it is not Russia -that ceases to exist, but the French army of six hundred thousand, and -then Napoleonic France itself. To strain the facts to fit the rules of -history: to say that the field of battle at Borodino remained in the -hands of the Russians, or that after Moscow there were other battles -that destroyed Napoleon's army, is impossible. - -After the French victory at Borodino there was no general engagement -nor any that were at all serious, yet the French army ceased to exist. -What does this mean? If it were an example taken from the history of -China, we might say that it was not an historic phenomenon (which is -the historians' usual expedient when anything does not fit their -standards); if the matter concerned some brief conflict in which -only a small number of troops took part, we might treat it as an -exception; but this event occurred before our fathers' eyes, and for -them it was a question of the life or death of their fatherland, and -it happened in the greatest of all known wars. - -The period of the campaign of 1812 from the battle of Borodino to -the expulsion of the French proved that the winning of a battle does -not produce a conquest and is not even an invariable indication of -conquest; it proved that the force which decides the fate of peoples -lies not in the conquerors, nor even in armies and battles, but in -something else. - -The French historians, describing the condition of the French army -before it left Moscow, affirm that all was in order in the Grand Army, -except the cavalry, the artillery, and the transport--there was no -forage for the horses or the cattle. That was a misfortune no one -could remedy, for the peasants of the district burned their hay rather -than let the French have it. - -The victory gained did not bring the usual results because the -peasants Karp and Vlas (who after the French had evacuated Moscow -drove in their carts to pillage the town, and in general personally -failed to manifest any heroic feelings), and the whole innumerable -multitude of such peasants, did not bring their hay to Moscow for -the high price offered them, but burned it instead. - -Let us imagine two men who have come out to fight a duel with -rapiers according to all the rules of the art of fencing. The -fencing has gone on for some time; suddenly one of the combatants, -feeling himself wounded and understanding that the matter is no joke -but concerns his life, throws down his rapier, and seizing the first -cudgel that comes to hand begins to brandish it. Then let us imagine -that the combatant who so sensibly employed the best and simplest -means to attain his end was at the same time influenced by -traditions of chivalry and, desiring to conceal the facts of the case, -insisted that he had gained his victory with the rapier according to -all the rules of art. One can imagine what confusion and obscurity -would result from such an account of the duel. - -The fencer who demanded a contest according to the rules of -fencing was the French army; his opponent who threw away the rapier -and snatched up the cudgel was the Russian people; those who try to -explain the matter according to the rules of fencing are the -historians who have described the event. - -After the burning of Smolensk a war began which did not follow any -previous traditions of war. The burning of towns and villages, the -retreats after battles, the blow dealt at Borodino and the renewed -retreat, the burning of Moscow, the capture of marauders, the -seizure of transports, and the guerrilla war were all departures -from the rules. - -Napoleon felt this, and from the time he took up the correct fencing -attitude in Moscow and instead of his opponent's rapier saw a cudgel -raised above his head, he did not cease to complain to Kutuzov and -to the Emperor Alexander that the war was being carried on contrary to -all the rules--as if there were any rules for killing people. In spite -of the complaints of the French as to the nonobservance of the -rules, in spite of the fact that to some highly placed Russians it -seemed rather disgraceful to fight with a cudgel and they wanted to -assume a pose en quarte or en tierce according to all the rules, and -to make an adroit thrust en prime, and so on--the cudgel of the -people's war was lifted with all its menacing and majestic strength, -and without consulting anyone's tastes or rules and regardless of -anything else, it rose and fell with stupid simplicity, but -consistently, and belabored the French till the whole invasion had -perished. - -And it is well for a people who do not--as the French did in 1813- -salute according to all the rules of art, and, presenting the hilt -of their rapier gracefully and politely, hand it to their -magnanimous conqueror, but at the moment of trial, without asking what -rules others have adopted in similar cases, simply and easily pick -up the first cudgel that comes to hand and strike with it till the -feeling of resentment and revenge in their soul yields to a feeling of -contempt and compassion. - - - - - -CHAPTER II - - -One of the most obvious and advantageous departures from the -so-called laws of war is the action of scattered groups against men -pressed together in a mass. Such action always occurs in wars that -take on a national character. In such actions, instead of two crowds -opposing each other, the men disperse, attack singly, run away when -attacked by stronger forces, but again attack when opportunity offers. -This was done by the guerrillas in Spain, by the mountain tribes in -the Caucasus, and by the Russians in 1812. - -People have called this kind of war "guerrilla warfare" and assume -that by so calling it they have explained its meaning. But such a -war does not fit in under any rule and is directly opposed to a -well-known rule of tactics which is accepted as infallible. That -rule says that an attacker should concentrate his forces in order to -be stronger than his opponent at the moment of conflict. - -Guerrilla war (always successful, as history shows) directly -infringes that rule. - -This contradiction arises from the fact that military science -assumes the strength of an army to be identical with its numbers. -Military science says that the more troops the greater the strength. -Les gros bataillons ont toujours raison.* - - -*Large battalions are always victorious. - - -For military science to say this is like defining momentum in -mechanics by reference to the mass only: stating that momenta are -equal or unequal to each other simply because the masses involved -are equal or unequal. - -Momentum (quantity of motion) is the product of mass and velocity. - -In military affairs the strength of an army is the product of its -mass and some unknown x. - -Military science, seeing in history innumerable instances of the -fact that the size of any army does not coincide with its strength and -that small detachments defeat larger ones, obscurely admits the -existence of this unknown factor and tries to discover it--now in a -geometric formation, now in the equipment employed, now, and most -usually, in the genius of the commanders. But the assignment of -these various meanings to the factor does not yield results which -accord with the historic facts. - -Yet it is only necessary to abandon the false view (adopted to -gratify the "heroes") of the efficacy of the directions issued in -wartime by commanders, in order to find this unknown quantity. - -That unknown quantity is the spirit of the army, that is to say, the -greater or lesser readiness to fight and face danger felt by all the -men composing an army, quite independently of whether they are, or are -not, fighting under the command of a genius, in two--or three-line -formation, with cudgels or with rifles that repeat thirty times a -minute. Men who want to fight will always put themselves in the most -advantageous conditions for fighting. - -The spirit of an army is the factor which multiplied by the mass -gives the resulting force. To define and express the significance of -this unknown factor--the spirit of an army--is a problem for science. - -This problem is only solvable if we cease arbitrarily to -substitute for the unknown x itself the conditions under which that -force becomes apparent--such as the commands of the general, the -equipment employed, and so on--mistaking these for the real -significance of the factor, and if we recognize this unknown -quantity in its entirety as being the greater or lesser desire to -fight and to face danger. Only then, expressing known historic facts -by equations and comparing the relative significance of this factor, -can we hope to define the unknown. - -Ten men, battalions, or divisions, fighting fifteen men, battalions, -or divisions, conquer--that is, kill or take captive--all the -others, while themselves losing four, so that on the one side four and -on the other fifteen were lost. Consequently the four were equal to -the fifteen, and therefore 4x = 15y. Consequently x/y = 15/4. This -equation does not give us the value of the unknown factor but gives us -a ratio between two unknowns. And by bringing variously selected -historic units (battles, campaigns, periods of war) into such -equations, a series of numbers could be obtained in which certain laws -should exist and might be discovered. - -The tactical rule that an army should act in masses when -attacking, and in smaller groups in retreat, unconsciously confirms -the truth that the strength of an army depends on its spirit. To -lead men forward under fire more discipline (obtainable only by -movement in masses) is needed than is needed to resist attacks. But -this rule which leaves out of account the spirit of the army -continually proves incorrect and is in particularly striking -contrast to the facts when some strong rise or fall in the spirit of -the troops occurs, as in all national wars. - -The French, retreating in 1812--though according to tactics they -should have separated into detachments to defend themselves- -congregated into a mass because the spirit of the army had so fallen -that only the mass held the army together. The Russians, on the -contrary, ought according to tactics to have attacked in mass, but -in fact they split up into small units, because their spirit had so -risen that separate individuals, without orders, dealt blows at the -French without needing any compulsion to induce them to expose -themselves to hardships and dangers. - - - - - -CHAPTER III - - -The so-called partisan war began with the entry of the French into -Smolensk. - -Before partisan warfare had been officially recognized by the -government, thousands of enemy stragglers, marauders, and foragers had -been destroyed by the Cossacks and the peasants, who killed them off -as instinctively as dogs worry a stray mad dog to death. Denis -Davydov, with his Russian instinct, was the first to recognize the -value of this terrible cudgel which regardless of the rules of -military science destroyed the French, and to him belongs the credit -for taking the first step toward regularizing this method of warfare. - -On August 24 Davydov's first partisan detachment was formed and then -others were recognized. The further the campaign progressed the more -numerous these detachments became. - -The irregulars destroyed the great army piecemeal. They gathered the -fallen leaves that dropped of themselves from that withered tree- -the French army--and sometimes shook that tree itself. By October, -when the French were fleeing toward Smolensk, there were hundreds of -such companies, of various sizes and characters. There were some -that adopted all the army methods and had infantry, artillery, staffs, -and the comforts of life. Others consisted solely of Cossack -cavalry. There were also small scratch groups of foot and horse, and -groups of peasants and landowners that remained unknown. A sacristan -commanded one party which captured several hundred prisoners in the -course of a month; and there was Vasilisa, the wife of a village -elder, who slew hundreds of the French. - -The partisan warfare flamed up most fiercely in the latter days of -October. Its first period had passed: when the partisans themselves, -amazed at their own boldness, feared every minute to be surrounded and -captured by the French, and hid in the forests without unsaddling, -hardly daring to dismount and always expecting to be pursued. By the -end of October this kind of warfare had taken definite shape: it had -become clear to all what could be ventured against the French and what -could not. Now only the commanders of detachments with staffs, and -moving according to rules at a distance from the French, still -regarded many things as impossible. The small bands that had started -their activities long before and had already observed the French -closely considered things possible which the commanders of the big -detachments did not dare to contemplate. The Cossacks and peasants who -crept in among the French now considered everything possible. - -On October 22, Denisov (who was one of the irregulars) was with -his group at the height of the guerrilla enthusiasm. Since early -morning he and his party had been on the move. All day long he had -been watching from the forest that skirted the highroad a large French -convoy of cavalry baggage and Russian prisoners separated from the -rest of the army, which--as was learned from spies and prisoners- -was moving under a strong escort to Smolensk. Besides Denisov and -Dolokhov (who also led a small party and moved in Denisov's vicinity), -the commanders of some large divisions with staffs also knew of this -convoy and, as Denisov expressed it, were sharpening their teeth for -it. Two of the commanders of large parties--one a Pole and the other a -German--sent invitations to Denisov almost simultaneously, -requesting him to join up with their divisions to attack the convoy. - -"No, bwother, I have gwown mustaches myself," said Denisov on -reading these documents, and he wrote to the German that, despite -his heartfelt desire to serve under so valiant and renowned a general, -he had to forgo that pleasure because he was already under the command -of the Polish general. To the Polish general he replied to the same -effect, informing him that he was already under the command of the -German. - -Having arranged matters thus, Denisov and Dolokhov intended, without -reporting matters to the higher command, to attack and seize that -convoy with their own small forces. On October 22 it was moving from -the village of Mikulino to that of Shamshevo. To the left of the -road between Mikulino and Shamshevo there were large forests, -extending in some places up to the road itself though in others a mile -or more back from it. Through these forests Denisov and his party rode -all day, sometimes keeping well back in them and sometimes coming to -the very edge, but never losing sight of the moving French. That -morning, Cossacks of Denisov's party had seized and carried off into -the forest two wagons loaded with cavalry saddles, which had stuck -in the mud not far from Mikulino where the forest ran close to the -road. Since then, and until evening, the party had the movements of -the French without attacking. It was necessary to let the French reach -Shamshevo quietly without alarming them and then, after joining -Dolokhov who was to come that evening to a consultation at a -watchman's hut in the forest less than a mile from Shamshevo, to -surprise the French at dawn, falling like an avalanche on their -heads from two sides, and rout and capture them all at one blow. - -In their rear, more than a mile from Mikulino where the forest -came right up to the road, six Cossacks were posted to report if any -fresh columns of French should show themselves. - -Beyond Shamshevo, Dolokhov was to observe the road in the same -way, to find out at what distance there were other French troops. They -reckoned that the convoy had fifteen hundred men. Denisov had two -hundred, and Dolokhov might have as many more, but the disparity of -numbers did not deter Denisov. All that he now wanted to know was what -troops these were and to learn that he had to capture a "tongue"--that -is, a man from the enemy column. That morning's attack on the wagons -had been made so hastily that the Frenchmen with the wagons had all -been killed; only a little drummer boy had been taken alive, and as he -was a straggler he could tell them nothing definite about the troops -in that column. - -Denisov considered it dangerous to make a second attack for fear -of putting the whole column on the alert, so he sent Tikhon -Shcherbaty, a peasant of his party, to Shamshevo to try and seize at -least one of the French quartermasters who had been sent on in -advance. - - - - -CHAPTER IV - - -It was a warm rainy autumn day. The sky and the horizon were both -the color of muddy water. At times a sort of mist descended, and -then suddenly heavy slanting rain came down. - -Denisov in a felt cloak and a sheepskin cap from which the rain -ran down was riding a thin thoroughbred horse with sunken sides. -Like his horse, which turned its head and laid its ears back, he -shrank from the driving rain and gazed anxiously before him. His -thin face with its short, thick black beard looked angry. - -Beside Denisov rode an esaul,* Denisov's fellow worker, also in felt -cloak and sheepskin cap, and riding a large sleek Don horse. - - -*A captain of Cossacks. - - -Esaul Lovayski the Third was a tall man as straight as an arrow, -pale-faced, fair-haired, with narrow light eyes and with calm -self-satisfaction in his face and bearing. Though it was impossible to -say in what the peculiarity of the horse and rider lay, yet at first -glance at the esaul and Denisov one saw that the latter was wet and -uncomfortable and was a man mounted on a horse, while looking at the -esaul one saw that he was as comfortable and as much at ease as always -and that he was not a man who had mounted a horse, but a man who was -one with his horse, a being consequently possessed of twofold -strength. - -A little ahead of them walked a peasant guide, wet to the skin and -wearing a gray peasant coat and a white knitted cap. - -A little behind, on a poor, small, lean Kirghiz mount with an -enormous tail and mane and a bleeding mouth, rode a young officer in a -blue French overcoat. - -Beside him rode an hussar, with a boy in a tattered French uniform -and blue cap behind him on the crupper of his horse. The boy held on -to the hussar with cold, red hands, and raising his eyebrows gazed -about him with surprise. This was the French drummer boy captured that -morning. - -Behind them along the narrow, sodden, cutup forest road came hussars -in threes and fours, and then Cossacks: some in felt cloaks, some in -French greatcoats, and some with horsecloths over their heads. The -horses, being drenched by the rain, all looked black whether -chestnut or bay. Their necks, with their wet, close-clinging manes, -looked strangely thin. Steam rose from them. Clothes, saddles, -reins, were all wet, slippery, and sodden, like the ground and the -fallen leaves that strewed the road. The men sat huddled up trying not -to stir, so as to warm the water that had trickled to their bodies and -not admit the fresh cold water that was leaking in under their -seats, their knees, and at the back of their necks. In the midst of -the outspread line of Cossacks two wagons, drawn by French horses -and by saddled Cossack horses that had been hitched on in front, -rumbled over the tree stumps and branches and splashed through the -water that lay in the ruts. - -Denisov's horse swerved aside to avoid a pool in the track and -bumped his rider's knee against a tree. - -"Oh, the devil!" exclaimed Denisov angrily, and showing his teeth he -struck his horse three times with his whip, splashing himself and -his comrades with mud. - -Denisov was out of sorts both because of the rain and also from -hunger (none of them had eaten anything since morning), and yet more -because he still had no news from Dolokhov and the man sent to capture -a "tongue" had not returned. - -"There'll hardly be another such chance to fall on a transport as -today. It's too risky to attack them by oneself, and if we put it -off till another day one of the big guerrilla detachments will -snatch the prey from under our noses," thought Denisov, continually -peering forward, hoping to see a messenger from Dolokhov. - -On coming to a path in the forest along which he could see far to -the right, Denisov stopped. - -"There's someone coming," said he. - -The esaul looked in the direction Denisov indicated. - -"There are two, an officer and a Cossack. But it is not -presupposable that it is the lieutenant colonel himself," said the -esaul, who was fond of using words the Cossacks did not know. - -The approaching riders having descended a decline were no longer -visible, but they reappeared a few minutes later. In front, at a weary -gallop and using his leather whip, rode an officer, disheveled and -drenched, whose trousers had worked up to above his knees. Behind him, -standing in the stirrups, trotted a Cossack. The officer, a very young -lad with a broad rosy face and keen merry eyes, galloped up to Denisov -and handed him a sodden envelope. - -"From the general," said the officer. "Please excuse its not being -quite dry." - -Denisov, frowning, took the envelope and opened it. - -"There, they kept telling us: 'It's dangerous, it's dangerous,'" -said the officer, addressing the esaul while Denisov was reading the -dispatch. "But Komarov and I"--he pointed to the Cossack--"were -prepared. We have each of us two pistols.... But what's this?" he -asked, noticing the French drummer boy. "A prisoner? You've already -been in action? May I speak to him?" - -"Wostov! Petya!" exclaimed Denisov, having run through the dispatch. -"Why didn't you say who you were?" and turning with a smile he held -out his hand to the lad. - -The officer was Petya Rostov. - -All the way Petya had been preparing himself to behave with -Denisov as befitted a grownup man and an officer--without hinting at -their previous acquaintance. But as soon as Denisov smiled at him -Petya brightened up, blushed with pleasure, forgot the official manner -he had been rehearsing, and began telling him how he had already -been in a battle near Vyazma and how a certain hussar had -distinguished himself there. - -"Well, I am glad to see you," Denisov interrupted him, and his -face again assumed its anxious expression. - -"Michael Feoklitych," said he to the esaul, "this is again fwom that -German, you know. He"--he indicated Petya--"is serving under him." - -And Denisov told the esaul that the dispatch just delivered was a -repetition of the German general's demand that he should join forces -with him for an attack on the transport. - -"If we don't take it tomowwow, he'll snatch it fwom under our -noses," he added. - -While Denisov was talking to the esaul, Petya--abashed by -Denisov's cold tone and supposing that it was due to the condition -of his trousers--furtively tried to pull them down under his greatcoat -so that no one should notice it, while maintaining as martial an air -as possible. - -"Will there be any orders, your honor?" he asked Denisov, holding -his hand at the salute and resuming the game of adjutant and general -for which he had prepared himself, "or shall I remain with your -honor?" - -"Orders?" Denisov repeated thoughtfully. "But can you stay till -tomowwow?" - -"Oh, please... May I stay with you?" cried Petya. - -"But, just what did the genewal tell you? To weturn at once?" -asked Denisov. - -Petya blushed. - -"He gave me no instructions. I think I could?" he returned, -inquiringly. - -"Well, all wight," said Denisov. - -And turning to his men he directed a party to go on to the halting -place arranged near the watchman's hut in the forest, and told the -officer on the Kirghiz horse (who performed the duties of an adjutant) -to go and find out where Dolokhov was and whether he would come that -evening. Denisov himself intended going with the esaul and Petya to -the edge of the forest where it reached out to Shamshevo, to have a -look at the part of the French bivouac they were to attack next day. - -"Well, old fellow," said he to the peasant guide, "lead us to -Shamshevo." - -Denisov, Petya, and the esaul, accompanied by some Cossacks and -the hussar who had the prisoner, rode to the left across a ravine to -the edge of the forest. - - - - - -CHAPTER V - - -The rain had stopped, and only the mist was falling and drops from -the trees. Denisov, the esaul, and Petya rode silently, following -the peasant in the knitted cap who, stepping lightly with outturned -toes and moving noiselessly in his bast shoes over the roots and wet -leaves, silently led them to the edge of the forest. - -He ascended an incline, stopped, looked about him, and advanced to -where the screen of trees was less dense. On reaching a large oak tree -that had not yet shed its leaves, he stopped and beckoned mysteriously -to them with his hand. - -Denisov and Petya rode up to him. From the spot where the peasant -was standing they could see the French. Immediately beyond the forest, -on a downward slope, lay a field of spring rye. To the right, beyond a -steep ravine, was a small village and a landowner's house with a -broken roof. In the village, in the house, in the garden, by the well, -by the pond, over all the rising ground, and all along the road uphill -from the bridge leading to the village, not more than five hundred -yards away, crowds of men could be seen through the shimmering mist. -Their un-Russian shouting at their horses which were straining -uphill with the carts, and their calls to one another, could be -clearly heard. - -"Bwing the prisoner here," said Denisov in a low voice, not taking -his eyes off the French. - -A Cossack dismounted, lifted the boy down, and took him to -Denisov. Pointing to the French troops, Denisov asked him what these -and those of them were. The boy, thrusting his cold hands into his -pockets and lifting his eyebrows, looked at Denisov in affright, but -in spite of an evident desire to say all he knew gave confused -answers, merely assenting to everything Denisov asked him. Denisov -turned away from him frowning and addressed the esaul, conveying his -own conjectures to him. - -Petya, rapidly turning his head, looked now at the drummer boy, -now at Denisov, now at the esaul, and now at the French in the village -and along the road, trying not to miss anything of importance. - -"Whether Dolokhov comes or not, we must seize it, eh?" said -Denisov with a merry sparkle in his eyes. - -"It is a very suitable spot," said the esaul. - -"We'll send the infantwy down by the swamps," Denisov continued. -"They'll cweep up to the garden; you'll wide up fwom there with the -Cossacks"--he pointed to a spot in the forest beyond the village--"and -I with my hussars fwom here. And at the signal shot..." - -"The hollow is impassable--there's a swamp there," said the esaul. -"The horses would sink. We must ride round more to the left...." - -While they were talking in undertones the crack of a shot sounded -from the low ground by the pond, a puff of white smoke appeared, -then another, and the sound of hundreds of seemingly merry French -voices shouting together came up from the slope. For a moment -Denisov and the esaul drew back. They were so near that they thought -they were the cause of the firing and shouting. But the firing and -shouting did not relate to them. Down below, a man wearing something -red was running through the marsh. The French were evidently firing -and shouting at him. - -"Why, that's our Tikhon," said the esaul. - -"So it is! It is!" - -"The wascal!" said Denisov. - -"He'll get away!" said the esaul, screwing up his eyes. - -The man whom they called Tikhon, having run to the stream, plunged -in so that the water splashed in the air, and, having disappeared -for an instant, scrambled out on all fours, all black with the wet, -and ran on. The French who had been pursuing him stopped. - -"Smart, that!" said the esaul. - -"What a beast!" said Denisov with his former look of vexation. "What -has he been doing all this time?" - -"Who is he?" asked Petya. - -"He's our plastun. I sent him to capture a 'tongue.'" - -"Oh, yes," said Petya, nodding at the first words Denisov uttered as -if he understood it all, though he really did not understand -anything of it. - -Tikhon Shcherbaty was one of the most indispensable men in their -band. He was a peasant from Pokrovsk, near the river Gzhat. When -Denisov had come to Pokrovsk at the beginning of his operations and -had as usual summoned the village elder and asked him what he knew -about the French, the elder, as though shielding himself, had replied, -as all village elders did, that he had neither seen nor heard anything -of them. But when Denisov explained that his purpose was to kill the -French, and asked if no French had strayed that way, the elder replied -that some "more-orderers" had really been at their village, but that -Tikhon Shcherbaty was the only man who dealt with such matters. -Denisov had Tikhon called and, having praised him for his activity, -said a few words in the elder's presence about loyalty to the Tsar and -the country and the hatred of the French that all sons of the -fatherland should cherish. - -"We don't do the French any harm," said Tikhon, evidently frightened -by Denisov's words. "We only fooled about with the lads for fun, you -know! We killed a score or so of 'more-orderers,' but we did no harm -else..." - -Next day when Denisov had left Pokrovsk, having quite forgotten -about this peasant, it was reported to him that Tikhon had attached -himself to their party and asked to be allowed to remain with it. -Denisov gave orders to let him do so. - -Tikhon, who at first did rough work, laying campfires, fetching -water, flaying dead horses, and so on, soon showed a great liking -and aptitude for partisan warfare. At night he would go out for -booty and always brought back French clothing and weapons, and when -told to would bring in French captives also. Denisov then relieved him -from drudgery and began taking him with him when he went out on -expeditions and had him enrolled among the Cossacks. - -Tikhon did not like riding, and always went on foot, never lagging -behind the cavalry. He was armed with a musketoon (which he carried -rather as a joke), a pike and an ax, which latter he used as a wolf -uses its teeth, with equal case picking fleas out of its fur or -crunching thick bones. Tikhon with equal accuracy would split logs -with blows at arm's length, or holding the head of the ax would cut -thin little pegs or carve spoons. In Denisov's party he held a -peculiar and exceptional position. When anything particularly -difficult or nasty had to be done--to push a cart out of the mud -with one's shoulders, pull a horse out of a swamp by its tail, skin -it, slink in among the French, or walk more than thirty miles in a -day--everybody pointed laughingly at Tikhon. - -"It won't hurt that devil--he's as strong as a horse!" they said -of him. - -Once a Frenchman Tikhon was trying to capture fired a pistol at -him and shot him in the fleshy part of the back. That wound (which -Tikhon treated only with internal and external applications of -vodka) was the subject of the liveliest jokes by the whole detachment- -jokes in which Tikhon readily joined. - -"Hallo, mate! Never again? Gave you a twist?" the Cossacks would -banter him. And Tikhon, purposely writhing and making faces, pretended -to be angry and swore at the French with the funniest curses. The only -effect of this incident on Tikhon was that after being wounded he -seldom brought in prisoners. - -He was the bravest and most useful man in the party. No one found -more opportunities for attacking, no one captured or killed more -Frenchmen, and consequently he was made the buffoon of all the -Cossacks and hussars and willingly accepted that role. Now he had been -sent by Denisov overnight to Shamshevo to capture a "tongue." But -whether because he had not been content to take only one Frenchman -or because he had slept through the night, he had crept by day into -some bushes right among the French and, as Denisov had witnessed -from above, had been detected by them. - - - - - -CHAPTER VI - - -After talking for some time with the esaul about next day's -attack, which now, seeing how near they were to the French, he -seemed to have definitely decided on, Denisov turned his horse and -rode back. - -"Now, my lad, we'll go and get dwy," he said to Petya. - -As they approached the watchhouse Denisov stopped, peering into -the forest. Among the trees a man with long legs and long, swinging -arms, wearing a short jacket, bast shoes, and a Kazan hat, was -approaching with long, light steps. He had a musketoon over his -shoulder and an ax stuck in his girdle. When he espied Denisov he -hastily threw something into the bushes, removed his sodden hat by its -floppy brim, and approached his commander. It was Tikhon. His wrinkled -and pockmarked face and narrow little eyes beamed with -self-satisfied merriment. He lifted his head high and gazed at Denisov -as if repressing a laugh. - -"Well, where did you disappear to?" inquired Denisov. - -"Where did I disappear to? I went to get Frenchmen," answered Tikhon -boldly and hurriedly, in a husky but melodious bass voice. - -"Why did you push yourself in there by daylight? You ass! Well, -why haven't you taken one?" - -"Oh, I took one all right," said Tikhon. - -"Where is he?" - -"You see, I took him first thing at dawn," Tikhon continued, -spreading out his flat feet with outturned toes in their bast shoes. -"I took him into the forest. Then I see he's no good and think I'll go -and fetch a likelier one." - -"You see?... What a wogue--it's just as I thought," said Denisov -to the esaul. "Why didn't you bwing that one?" - -"What was the good of bringing him?" Tikhon interrupted hastily -and angrily--"that one wouldn't have done for you. As if I don't -know what sort you want!" - -"What a bwute you are!... Well?" - -"I went for another one," Tikhon continued, "and I crept like this -through the wood and lay down." (He suddenly lay down on his stomach -with a supple movement to show how he had done it.) "One turned up and -I grabbed him, like this." (He jumped up quickly and lightly.) -"'Come along to the colonel,' I said. He starts yelling, and -suddenly there were four of them. They rushed at me with their -little swords. So I went for them with my ax, this way: 'What are -you up to?' says I. 'Christ be with you!'" shouted Tikhon, waving -his arms with an angry scowl and throwing out his chest. - -"Yes, we saw from the hill how you took to your heels through the -puddles!" said the esaul, screwing up his glittering eyes. - -Petya badly wanted to laugh, but noticed that they all refrained -from laughing. He turned his eyes rapidly from Tikhon's face to the -esaul's and Denisov's, unable to make out what it all meant. - -"Don't play the fool!" said Denisov, coughing angrily. "Why didn't -you bwing the first one?" - -Tikhon scratched his back with one hand and his head with the other, -then suddenly his whole face expanded into a beaming, foolish grin, -disclosing a gap where he had lost a tooth (that was why he was called -Shcherbaty--the gap-toothed). Denisov smiled, and Petya burst into a -peal of merry laughter in which Tikhon himself joined. - -"Oh, but he was a regular good-for-nothing," said Tikhon. "The -clothes on him--poor stuff! How could I bring him? And so rude, your -honor! Why, he says: 'I'm a general's son myself, I won't go!' he -says." - -"You are a bwute!" said Denisov. "I wanted to question..." - -"But I questioned him," said Tikhon. "He said he didn't know much. -'There are a lot of us,' he says, 'but all poor stuff--only soldiers -in name,' he says. 'Shout loud at them,' he says, 'and you'll take -them all,'" Tikhon concluded, looking cheerfully and resolutely into -Denisov's eyes. - -"I'll give you a hundwed sharp lashes--that'll teach you to play the -fool!" said Denisov severely. - -"But why are you angry?" remonstrated Tikhon, "just as if I'd -never seen your Frenchmen! Only wait till it gets dark and I'll -fetch you any of them you want--three if you like." - -"Well, let's go," said Denisov, and rode all the way to the -watchhouse in silence and frowning angrily. - -Tikhon followed behind and Petya heard the Cossacks laughing with -him and at him, about some pair of boots he had thrown into the -bushes. - -When the fit of laughter that had seized him at Tikhon's words and -smile had passed and Petya realized for a moment that this Tikhon -had killed a man, he felt uneasy. He looked round at the captive -drummer boy and felt a pang in his heart. But this uneasiness lasted -only a moment. He felt it necessary to hold his head higher, to -brace himself, and to question the esaul with an air of importance -about tomorrow's undertaking, that he might not be unworthy of the -company in which he found himself. - -The officer who had been sent to inquire met Denisov on the way with -the news that Dolokhov was soon coming and that all was well with him. - -Denisov at once cheered up and, calling Petya to him, said: "Well, -tell me about yourself." - - - - - -CHAPTER VII - - -Petya, having left his people after their departure from Moscow, -joined his regiment and was soon taken as orderly by a general -commanding a large guerrilla detachment. From the time he received his -commission, and especially since he had joined the active army and -taken part in the battle of Vyazma, Petya had been in a constant state -of blissful excitement at being grown-up and in a perpetual ecstatic -hurry not to miss any chance to do something really heroic. He was -highly delighted with what he saw and experienced in the army, but -at the same time it always seemed to him that the really heroic -exploits were being performed just where he did not happen to be. -And he was always in a hurry to get where he was not. - -When on the twenty-first of October his general expressed a wish -to send somebody to Denisov's detachment, Petya begged so piteously to -be sent that the general could not refuse. But when dispatching him he -recalled Petya's mad action at the battle of Vyazma, where instead -of riding by the road to the place to which he had been sent, he had -galloped to the advanced line under the fire of the French and had -there twice fired his pistol. So now the general explicitly forbade -his taking part in any action whatever of Denisov's. That was why -Petya had blushed and grown confused when Denisov asked him whether he -could stay. Before they had ridden to the outskirts of the forest -Petya had considered he must carry out his instructions strictly and -return at once. But when he saw the French and saw Tikhon and -learned that there would certainly be an attack that night, he -decided, with the rapidity with which young people change their views, -that the general, whom he had greatly respected till then, was a -rubbishy German, that Denisov was a hero, the esaul a hero, and Tikhon -a hero too, and that it would be shameful for him to leave them at a -moment of difficulty. - -It was already growing dusk when Denisov, Petya, and the esaul -rode up to the watchhouse. In the twilight saddled horses could be -seen, and Cossacks and hussars who had rigged up rough shelters in the -glade and were kindling glowing fires in a hollow of the forest -where the French could not see the smoke. In the passage of the -small watchhouse a Cossack with sleeves rolled up was chopping some -mutton. In the room three officers of Denisov's band were converting a -door into a tabletop. Petya took off his wet clothes, gave them to -be dried, and at once began helping the officers to fix up the -dinner table. - -In ten minutes the table was ready and a napkin spread on it. On the -table were vodka, a flask of rum, white bread, roast mutton, and salt. - -Sitting at table with the officers and tearing the fat savory mutton -with his hands, down which the grease trickled, Petya was in an -ecstatic childish state of love for all men, and consequently of -confidence that others loved him in the same way. - -"So then what do you think, Vasili Dmitrich?" said he to Denisov. -"It's all right my staying a day with you?" And not waiting for a -reply he answered his own question: "You see I was told to find out- -well, I am finding out.... Only do let me into the very... into the -chief... I don't want a reward... But I want..." - -Petya clenched his teeth and looked around, throwing back his head -and flourishing his arms. - -"Into the vewy chief..." Denisov repeated with a smile. - -"Only, please let me command something, so that I may really -command..." Petya went on. "What would it be to you?... Oh, you want a -knife?" he said, turning to an officer who wished to cut himself a -piece of mutton. - -And he handed him his clasp knife. The officer admired it. - -"Please keep it. I have several like it," said Petya, blushing. -"Heavens! I was quite forgetting!" he suddenly cried. "I have some -raisins, fine ones; you know, seedless ones. We have a new sutler -and he has such capital things. I bought ten pounds. I am used to -something sweet. Would you like some?..." and Petya ran out into the -passage to his Cossack and brought back some bags which contained -about five pounds of raisins. "Have some, gentlemen, have some!" - -"You want a coffeepot, don't you?" he asked the esaul. "I bought a -capital one from our sutler! He has splendid things. And he's very -honest, that's the chief thing. I'll be sure to send it to you. Or -perhaps your flints are giving out, or are worn out--that happens -sometimes, you know. I have brought some with me, here they are"- -and he showed a bag--"a hundred flints. I bought them very cheap. -Please take as many as you want, or all if you like...." - -Then suddenly, dismayed lest he had said too much, Petya stopped and -blushed. - -He tried to remember whether he had not done anything else that -was foolish. And running over the events of the day he remembered -the French drummer boy. "It's capital for us here, but what of him? -Where have they put him? Have they fed him? Haven't they hurt his -feelings?" he thought. But having caught himself saying too much about -the flints, he was now afraid to speak out. - -"I might ask," he thought, "but they'll say: 'He's a boy himself and -so he pities the boy.' I'll show them tomorrow whether I'm a boy. Will -it seem odd if I ask?" Petya thought. "Well, never mind!" and -immediately, blushing and looking anxiously at the officers to see -if they appeared ironical, he said: - -"May I call in that boy who was taken prisoner and give him -something to eat?... Perhaps..." - -"Yes, he's a poor little fellow," said Denisov, who evidently saw -nothing shameful in this reminder. "Call him in. His name is Vincent -Bosse. Have him fetched." - -"I'll call him," said Petya. - -"Yes, yes, call him. A poor little fellow," Denisov repeated. - -Petya was standing at the door when Denisov said this. He slipped in -between the officers, came close to Denisov, and said: - -"Let me kiss you, dear old fellow! Oh, how fine, how splendid!" - -And having kissed Denisov he ran out of the hut. - -"Bosse! Vincent!" Petya cried, stopping outside the door. - -"Who do you want, sir?" asked a voice in the darkness. - -Petya replied that he wanted the French lad who had been captured -that day. - -"Ah, Vesenny?" said a Cossack. - -Vincent, the boy's name, had already been changed by the Cossacks -into Vesenny (vernal) and into Vesenya by the peasants and soldiers. -In both these adaptations the reference to spring (vesna) matched -the impression made by the young lad. - -"He is warming himself there by the bonfire. Ho, Vesenya! -Vesenya!--Vesenny!" laughing voices were heard calling to one -another in the darkness. - -"He's a smart lad," said an hussar standing near Petya. "We gave him -something to eat a while ago. He was awfully hungry!" - -The sound of bare feet splashing through the mud was heard in the -darkness, and the drummer boy came to the door. - -"Ah, c'est vous!" said Petya. "Voulez-vous manger? N'ayez pas -peur, on ne vous fera pas de mal,"* he added shyly and affectionately, -touching the boy's hand. "Entrez, entrez."*[2] - - -*"Ah, it's you! Do you want something to eat? Don't be afraid, -they won't hurt you." - -*[2] "Come in, come in." - - -"Merci, monsieur,"* said the drummer boy in a trembling almost -childish voice, and he began scraping his dirty feet on the threshold. - - -*"Thank you, sir." - - -There were many things Petya wanted to say to the drummer boy, but -did not dare to. He stood irresolutely beside him in the passage. Then -in the darkness he took the boy's hand and pressed it. - -"Come in, come in!" he repeated in a gentle whisper. "Oh, what can I -do for him?" he thought, and opening the door he let the boy pass in -first. - -When the boy had entered the hut, Petya sat down at a distance -from him, considering it beneath his dignity to pay attention to -him. But he fingered the money in his pocket and wondered whether it -would seem ridiculous to give some to the drummer boy. - - - - - -CHAPTER VIII - - -The arrival of Dolokhov diverted Petya's attention from the -drummer boy, to whom Denisov had had some mutton and vodka given, -and whom he had had dressed in a Russian coat so that he might be kept -with their band and not sent away with the other prisoners. Petya -had heard in the army many stories of Dolokhov's extraordinary bravery -and of his cruelty to the French, so from the moment he entered the -hut Petya did not take his eyes from him, but braced himself up more -and more and held his head high, that he might not be unworthy even of -such company. - -Dolokhov's appearance amazed Petya by its simplicity. - -Denisov wore a Cossack coat, had a beard, had an icon of Nicholas -the Wonder-Worker on his breast, and his way of speaking and -everything he did indicated his unusual position. But Dolokhov, who in -Moscow had worn a Persian costume, had now the appearance of a most -correct officer of the Guards. He was clean-shaven and wore a -Guardsman's padded coat with an Order of St. George at his -buttonhole and a plain forage cap set straight on his head. He took -off his wet felt cloak in a corner of the room, and without greeting -anyone went up to Denisov and began questioning him about the matter -in hand. Denisov told him of the designs the large detachments had -on the transport, of the message Petya had brought, and his own -replies to both generals. Then he told him all he knew of the French -detachment. - -"That's so. But we must know what troops they are and their -numbers," said Dolokhov. "It will be necessary to go there. We can't -start the affair without knowing for certain how many there are. I -like to work accurately. Here now--wouldn't one of these gentlemen -like to ride over to the French camp with me? I have brought a spare -uniform." - -"I, I... I'll go with you!" cried Petya. - -"There's no need for you to go at all," said Denisov, addressing -Dolokhov, "and as for him, I won't let him go on any account." - -"I like that!" exclaimed Petya. "Why shouldn't I go?" - -"Because it's useless." - -"Well, you must excuse me, because... because... I shall go, and -that's all. You'll take me, won't you?" he said, turning to Dolokhov. - -"Why not?" Dolokhov answered absently, scrutinizing the face of -the French drummer boy. "Have you had that youngster with you long?" -he asked Denisov. - -"He was taken today but he knows nothing. I'm keeping him with me." - -"Yes, and where do you put the others?" inquired Dolokhov. - -"Where? I send them away and take a weceipt for them," shouted -Denisov, suddenly flushing. "And I say boldly that I have not a single -man's life on my conscience. Would it be difficult for you to send -thirty or thwee hundwed men to town under escort, instead of staining- -I speak bluntly--staining the honor of a soldier?" - -"That kind of amiable talk would be suitable from this young count -of sixteen," said Dolokhov with cold irony, "but it's time for you -to drop it." - -"Why, I've not said anything! I only say that I'll certainly go with -you," said Petya shyly. - -"But for you and me, old fellow, it's time to drop these amenities," -continued Dolokhov, as if he found particular pleasure in speaking -of this subject which irritated Denisov. "Now, why have you kept -this lad?" he went on, swaying his head. "Because you are sorry for -him! Don't we know those 'receipts' of yours? You send a hundred men -away, and thirty get there. The rest either starve or get killed. So -isn't it all the same not to send them?" - -The esaul, screwing up his light-colored eyes, nodded approvingly. - -"That's not the point. I'm not going to discuss the matter. I do not -wish to take it on my conscience. You say they'll die. All wight. Only -not by my fault!" - -Dolokhov began laughing. - -"Who has told them not to capture me these twenty times over? But if -they did catch me they'd string me up to an aspen tree, and with all -your chivalry just the same." He paused. "However, we must get to -work. Tell the Cossack to fetch my kit. I have two French uniforms -in it. Well, are you coming with me?" he asked Petya. - -"I? Yes, yes, certainly!" cried Petya, blushing almost to tears -and glancing at Denisov. - -While Dolokhov had been disputing with Denisov what should be done -with prisoners, Petya had once more felt awkward and restless; but -again he had no time to grasp fully what they were talking about. -"If grown-up, distinguished men think so, it must be necessary and -right," thought he. "But above all Denisov must not dare to imagine -that I'll obey him and that he can order me about. I will certainly go -to the French camp with Dolokhov. If he can, so can I!" - -And to all Denisov's persuasions, Petya replied that he too was -accustomed to do everything accurately and not just anyhow, and that -he never considered personal danger. - -"For you'll admit that if we don't know for sure how many of them -there are... hundreds of lives may depend on it, while there are -only two of us. Besides, I want to go very much and certainly will go, -so don't hinder me," said he. "It will only make things worse..." - - - - - -CHAPTER IX - - -Having put on French greatcoats and shakos, Petya and Dolokhov -rode to the clearing from which Denisov had reconnoitered the French -camp, and emerging from the forest in pitch darkness they descended -into the hollow. On reaching the bottom, Dolokhov told the Cossacks -accompanying him to await him there and rode on at a quick trot -along the road to the bridge. Petya, his heart in his mouth with -excitement, rode by his side. - -"If we're caught, I won't be taken alive! I have a pistol," -whispered he. - -"Don't talk Russian," said Dolokhov in a hurried whisper, and at -that very moment they heard through the darkness the challenge: "Qui -vive?"* and the click of a musket. - - -*"Who goes there?" - - -The blood rushed to Petya's face and he grasped his pistol. - -"Lanciers du 6-me,"* replied Dolokhov, neither hastening nor -slackening his horse's pace. - - -*"Lancers of the 6th Regiment." - - -The black figure of a sentinel stood on the bridge. - -"Mot d'ordre."* - - -*"Password." - - -Dolokhov reined in his horse and advanced at a walk. - -"Dites donc, le colonel Gerard est ici?"* he asked. - - -*"Tell me, is Colonel Gerard here?" - - -"Mot d'ordre," repeated the sentinel, barring the way and not -replying. - -"Quand un officier fait sa ronde, les sentinelles ne demandent pas -le mot d'ordre..." cried Dolokhov suddenly flaring up and riding -straight at the sentinel. "Je vous demande si le colonel est ici."* - - -*"When an officer is making his round, sentinels don't ask him for -the password.... I am asking you if the colonel is here." - - -And without waiting for an answer from the sentinel, who had stepped -aside, Dolokhov rode up the incline at a walk. - -Noticing the black outline of a man crossing the road, Dolokhov -stopped him and inquired where the commander and officers were. The -man, a soldier with a sack over his shoulder, stopped, came close up -to Dolokhov's horse, touched it with his hand, and explained simply -and in a friendly way that the commander and the officers were -higher up the hill to the right in the courtyard of the farm, as he -called the landowner's house. - -Having ridden up the road, on both sides of which French talk -could be heard around the campfires, Dolokhov turned into the -courtyard of the landowner's house. Having ridden in, he dismounted -and approached a big blazing campfire, around which sat several men -talking noisily. Something was boiling in a small cauldron at the edge -of the fire and a soldier in a peaked cap and blue overcoat, lit up by -the fire, was kneeling beside it stirring its contents with a ramrod. - -"Oh, he's a hard nut to crack," said one of the officers who was -sitting in the shadow at the other side of the fire. - -"He'll make them get a move on, those fellows!" said another, -laughing. - -Both fell silent, peering out through the darkness at the sound of -Dolokhov's and Petya's steps as they advanced to the fire leading -their horses. - -"Bonjour, messieurs!"* said Dolokhov loudly and clearly. - - -*"Good day, gentlemen." - - -There was a stir among the officers in the shadow beyond the fire, -and one tall, long-necked officer, walking round the fire, came up -to Dolokhov. - -"Is that you, Clement?" he asked. "Where the devil...?" But, noticing -his mistake, he broke off short and, with a frown, greeted Dolokhov as -a stranger, asking what he could do for him. - -Dolokhov said that he and his companion were trying to overtake -their regiment, and addressing the company in general asked whether -they knew anything of the 6th Regiment. None of them knew anything, -and Petya thought the officers were beginning to look at him and -Dolokhov with hostility and suspicion. For some seconds all were -silent. - -"If you were counting on the evening soup, you have come too -late," said a voice from behind the fire with a repressed laugh. - -Dolokhov replied that they were not hungry and must push on -farther that night. - -He handed the horses over to the soldier who was stirring the pot -and squatted down on his heels by the fire beside the officer with the -long neck. That officer did not take his eyes from Dolokhov and -again asked to what regiment he belonged. Dolokhov, as if he had not -heard the question, did not reply, but lighting a short French pipe -which he took from his pocket began asking the officer in how far -the road before them was safe from Cossacks. - -"Those brigands are everywhere," replied an officer from behind -the fire. - -Dolokhov remarked that the Cossacks were a danger only to stragglers -such as his companion and himself, "but probably they would not dare -to attack large detachments?" he added inquiringly. No one replied. - -"Well, now he'll come away," Petya thought every moment as he -stood by the campfire listening to the talk. - -But Dolokhov restarted the conversation which had dropped and -began putting direct questions as to how many men there were in the -battalion, how many battalions, and how many prisoners. Asking about -the Russian prisoners with that detachment, Dolokhov said: - -"A horrid business dragging these corpses about with one! It would -be better to shoot such rabble," and burst into loud laughter, so -strange that Petya thought the French would immediately detect their -disguise, and involuntarily took a step back from the campfire. - -No one replied a word to Dolokhov's laughter, and a French officer -whom they could not see (he lay wrapped in a greatcoat) rose and -whispered something to a companion. Dolokhov got up and called to -the soldier who was holding their horses. - -"Will they bring our horses or not?" thought Petya, instinctively -drawing nearer to Dolokhov. - -The horses were brought. - -"Good evening, gentlemen," said Dolokhov. - -Petya wished to say "Good night" but could not utter a word. The -officers were whispering together. Dolokhov was a long time mounting -his horse which would not stand still, then he rode out of the yard at -a footpace. Petya rode beside him, longing to look round to see -whether or no the French were running after them, but not daring to. - -Coming out onto the road Dolokhov did not ride back across the -open country, but through the village. At one spot he stopped and -listened. "Do you hear?" he asked. Petya recognized the sound of -Russian voices and saw the dark figures of Russian prisoners round -their campfires. When they had descended to the bridge Petya and -Dolokhov rode past the sentinel, who without saying a word paced -morosely up and down it, then they descended into the hollow where the -Cossacks awaited them. - -"Well now, good-by. Tell Denisov, 'at the first shot at -daybreak,'" said Dolokhov and was about to ride away, but Petya seized -hold of him. - -"Really!" he cried, "you are such a hero! Oh, how fine, how -splendid! How I love you!" - -"All right, all right!" said Dolokhov. But Petya did not let go of -him and Dolokhov saw through the gloom that Petya was bending toward -him and wanted to kiss him. Dolokhov kissed him, laughed, turned his -horse, and vanished into the darkness. - - - - - -CHAPTER X - - -Having returned to the watchman's hut, Petya found Denisov in the -passage. He was awaiting Petya's return in a state of agitation, -anxiety, and self-reproach for having let him go. - -"Thank God!" he exclaimed. "Yes, thank God!" he repeated, -listening to Petya's rapturous account. "But, devil take you, I -haven't slept because of you! Well, thank God. Now lie down. We can -still get a nap before morning." - -"But... no," said Petya, "I don't want to sleep yet. Besides I -know myself, if I fall asleep it's finished. And then I am used to not -sleeping before a battle." - -He sat awhile in the hut joyfully recalling the details of his -expedition and vividly picturing to himself what would happen next -day. - -Then, noticing that Denisov was asleep, he rose and went out of -doors. - -It was still quite dark outside. The rain was over, but drops were -still falling from the trees. Near the watchman's hut the black shapes -of the Cossacks' shanties and of horses tethered together could be -seen. Behind the hut the dark shapes of the two wagons with their -horses beside them were discernible, and in the hollow the dying -campfire gleamed red. Not all the Cossacks and hussars were asleep; -here and there, amid the sounds of falling drops and the munching of -the horses near by, could be heard low voices which seemed to be -whispering. - -Petya came out, peered into the darkness, and went up to the wagons. -Someone was snoring under them, and around them stood saddled horses -munching their oats. In the dark Petya recognized his own horse, which -he called "Karabakh" though it was of Ukranian breed, and went up to -it. - -"Well, Karabakh! We'll do some service tomorrow," said he, -sniffing its nostrils and kissing it. - -"Why aren't you asleep, sir?" said a Cossack who was sitting under a -wagon. - -"No, ah... Likhachev--isn't that your name? Do you know I have -only just come back! We've been into the French camp." - -And Petya gave the Cossack a detailed account not only of his ride -but also of his object, and why he considered it better to risk his -life than to act "just anyhow." - -"Well, you should get some sleep now," said the Cossack. - -"No, I am used to this," said Petya. "I say, aren't the flints in -your pistols worn out? I brought some with me. Don't you want any? You -can have some." - - -The Cossack bent forward from under the wagon to get a closer look -at Petya. - -"Because I am accustomed to doing everything accurately," said -Petya. "Some fellows do things just anyhow, without preparation, and -then they're sorry for it afterwards. I don't like that." - -"Just so," said the Cossack. - -"Oh yes, another thing! Please, my dear fellow, will you sharpen -my saber for me? It's got bl..." (Petya feared to tell a lie, and -the saber never had been sharpened.) "Can you do it?" - -"Of course I can." - -Likhachev got up, rummaged in his pack, and soon Petya heard the -warlike sound of steel on whetstone. He climbed onto the wagon and sat -on its edge. The Cossack was sharpening the saber under the wagon. - -"I say! Are the lads asleep?" asked Petya. - -"Some are, and some aren't--like us." - -"Well, and that boy?" - -"Vesenny? Oh, he's thrown himself down there in the passage. Fast -asleep after his fright. He was that glad!" - -After that Petya remained silent for a long time, listening to the -sounds. He heard footsteps in the darkness and a black figure -appeared. - -"What are you sharpening?" asked a man coming up to the wagon. - -"Why, this gentleman's saber." - -"That's right," said the man, whom Petya took to be an hussar. -"Was the cup left here?" - -"There, by the wheel!" - -The hussar took the cup. - -"It must be daylight soon," said he, yawning, and went away. - -Petya ought to have known that he was in a forest with Denisov's -guerrilla band, less than a mile from the road, sitting on a wagon -captured from the French beside which horses were tethered, that under -it Likhachev was sitting sharpening a saber for him, that the big dark -blotch to the right was the watchman's hut, and the red blotch below -to the left was the dying embers of a campfire, that the man who had -come for the cup was an hussar who wanted a drink; but he neither knew -nor waited to know anything of all this. He was in a fairy kingdom -where nothing resembled reality. The big dark blotch might really be -the watchman's hut or it might be a cavern leading to the very -depths of the earth. Perhaps the red spot was a fire, or it might be -the eye of an enormous monster. Perhaps he was really sitting on a -wagon, but it might very well be that he was not sitting on a wagon -but on a terribly high tower from which, if he fell, he would have -to fall for a whole day or a whole month, or go on falling and never -reach the bottom. Perhaps it was just the Cossack, Likhachev, who -was sitting under the wagon, but it might be the kindest, bravest, -most wonderful, most splendid man in the world, whom no one knew of. -It might really have been that the hussar came for water and went back -into the hollow, but perhaps he had simply vanished--disappeared -altogether and dissolved into nothingness. - -Nothing Petya could have seen now would have surprised him. He was -in a fairy kingdom where everything was possible. - -He looked up at the sky. And the sky was a fairy realm like the -earth. It was clearing, and over the tops of the trees clouds were -swiftly sailing as if unveiling the stars. Sometimes it looked as if -the clouds were passing, and a clear black sky appeared. Sometimes -it seemed as if the black spaces were clouds. Sometimes the sky seemed -to be rising high, high overhead, and then it seemed to sink so low -that one could touch it with one's hand. - -Petya's eyes began to close and he swayed a little. - -The trees were dripping. Quiet talking was heard. The horses neighed -and jostled one another. Someone snored. - -"Ozheg-zheg, Ozheg-zheg..." hissed the saber against the -whetstone, and suddenly Petya heard an harmonious orchestra playing -some unknown, sweetly solemn hymn. Petya was as musical as Natasha and -more so than Nicholas, but had never learned music or thought about -it, and so the melody that unexpectedly came to his mind seemed to him -particularly fresh and attractive. The music became more and more -audible. The melody grew and passed from one instrument to another. -And what was played was a fugue--though Petya had not the least -conception of what a fugue is. Each instrument--now resembling a -violin and now a horn, but better and clearer than violin or horn- -played its own part, and before it had finished the melody merged with -another instrument that began almost the same air, and then with a -third and a fourth; and they all blended into one and again became -separate and again blended, now into solemn church music, now into -something dazzlingly brilliant and triumphant. - -"Oh--why, that was in a dream!" Petya said to himself, as he lurched -forward. "It's in my ears. But perhaps it's music of my own. Well, -go on, my music! Now!..." - -He closed his eyes, and, from all sides as if from a distance, -sounds fluttered, grew into harmonies, separated, blended, and again -all mingled into the same sweet and solemn hymn. "Oh, this is -delightful! As much as I like and as I like!" said Petya to himself. -He tried to conduct that enormous orchestra. - -"Now softly, softly die away!" and the sounds obeyed him. "Now -fuller, more joyful. Still more and more joyful!" And from an -unknown depth rose increasingly triumphant sounds. "Now voices join -in!" ordered Petya. And at first from afar he heard men's voices and -then women's. The voices grew in harmonious triumphant strength, and -Petya listened to their surpassing beauty in awe and joy. - -With a solemn triumphal march there mingled a song, the drip from -the trees, and the hissing of the saber, "Ozheg-zheg-zheg..." and -again the horses jostled one another and neighed, not disturbing the -choir but joining in it. - -Petya did not know how long this lasted: he enjoyed himself all -the time, wondered at his enjoyment and regretted that there was no -one to share it. He was awakened by Likhachev's kindly voice. - -"It's ready, your honor; you can split a Frenchman in half with it!" - -Petya woke up. - -"It's getting light, it's really getting light!" he exclaimed. - -The horses that had previously been invisible could now be seen to -their very tails, and a watery light showed itself through the bare -branches. Petya shook himself, jumped up, took a ruble from his pocket -and gave it to Likhachev; then he flourished the saber, tested it, and -sheathed it. The Cossacks were untying their horses and tightening -their saddle girths. - -"And here's the commander," said Likhachev. - -Denisov came out of the watchman's hut and, having called Petya, -gave orders to get ready. - - - - -CHAPTER XI - - -The men rapidly picked out their horses in the semidarkness, -tightened their saddle girths, and formed companies. Denisov stood -by the watchman's hut giving final orders. The infantry of the -detachment passed along the road and quickly disappeared amid the -trees in the mist of early dawn, hundreds of feet splashing through -the mud. The esaul gave some orders to his men. Petya held his horse -by the bridle, impatiently awaiting the order to mount. His face, -having been bathed in cold water, was all aglow, and his eyes were -particularly brilliant. Cold shivers ran down his spine and his -whole body pulsed rhythmically. - -"Well, is ev'wything weady?" asked Denisov. "Bwing the horses." - -The horses were brought. Denisov was angry with the Cossack -because the saddle girths were too slack, reproved him, and mounted. -Petya put his foot in the stirrup. His horse by habit made as if to -nip his leg, but Petya leaped quickly into the saddle unconscious of -his own weight and, turning to look at the hussars starting in the -darkness behind him, rode up to Denisov. - -"Vasili Dmitrich, entrust me with some commission! Please... for -God's sake...!" said he. - -Denisov seemed to have forgotten Petya's very existence. He turned -to glance at him. - -"I ask one thing of you," he said sternly, "to obey me and not shove -yourself forward anywhere." - -He did not say another word to Petya but rode in silence all the -way. When they had come to the edge of the forest it was noticeably -growing light over the field. Denisov talked in whispers with the -esaul and the Cossacks rode past Petya and Denisov. When they had -all ridden by, Denisov touched his horse and rode down the hill. -Slipping onto their haunches and sliding, the horses descended with -their riders into the ravine. Petya rode beside Denisov, the pulsation -of his body constantly increasing. It was getting lighter and lighter, -but the mist still hid distant objects. Having reached the valley, -Denisov looked back and nodded to a Cossack beside him. - -"The signal!" said he. - -The Cossack raised his arm and a shot rang out. In an instant the -tramp of horses galloping forward was heard, shouts came from -various sides, and then more shots. - -At the first sound of trampling hoofs and shouting, Petya lashed his -horse and loosening his rein galloped forward, not heeding Denisov who -shouted at him. It seemed to Petya that at the moment the shot was -fired it suddenly became as bright as noon. He galloped to the bridge. -Cossacks were galloping along the road in front of him. On the -bridge he collided with a Cossack who had fallen behind, but he -galloped on. In front of him soldiers, probably Frenchmen, were -running from right to left across the road. One of them fell in the -mud under his horse's feet. - -Cossacks were crowding about a hut, busy with something. From the -midst of that crowd terrible screams arose. Petya galloped up, and the -first thing he saw was the pale face and trembling jaw of a Frenchman, -clutching the handle of a lance that had been aimed at him. - -"Hurrah!... Lads!... ours!" shouted Petya, and giving rein to his -excited horse he galloped forward along the village street. - -He could hear shooting ahead of him. Cossacks, hussars, and ragged -Russian prisoners, who had come running from both sides of the road, -were shouting something loudly and incoherently. A gallant-looking -Frenchman, in a blue overcoat, capless, and with a frowning red -face, had been defending himself against the hussars. When Petya -galloped up the Frenchman had already fallen. "Too late again!" -flashed through Petya's mind and he galloped on to the place from -which the rapid firing could be heard. The shots came from the yard of -the landowner's house he had visited the night before with Dolokhov. -The French were making a stand there behind a wattle fence in a garden -thickly overgrown with bushes and were firing at the Cossacks who -crowded at the gateway. Through the smoke, as he approached the -gate, Petya saw Dolokhov, whose face was of a pale-greenish tint, -shouting to his men. "Go round! Wait for the infantry!" he exclaimed -as Petya rode up to him. - -"Wait?... Hurrah-ah-ah!" shouted Petya, and without pausing a moment -galloped to the place whence came the sounds of firing and where the -smoke was thickest. - -A volley was heard, and some bullets whistled past, while others -plashed against something. The Cossacks and Dolokhov galloped after -Petya into the gateway of the courtyard. In the dense wavering smoke -some of the French threw down their arms and ran out of the bushes -to meet the Cossacks, while others ran down the hill toward the -pond. Petya was galloping along the courtyard, but instead of -holding the reins he waved both his arms about rapidly and -strangely, slipping farther and farther to one side in his saddle. His -horse, having galloped up to a campfire that was smoldering in the -morning light, stopped suddenly, and Petya fell heavily on to the -wet ground. The Cossacks saw that his arms and legs jerked rapidly -though his head was quite motionless. A bullet had pierced his skull. - -After speaking to the senior French officer, who came out of the -house with a white handkerchief tied to his sword and announced that -they surrendered, Dolokhov dismounted and went up to Petya, who lay -motionless with outstretched arms. - -"Done for!" he said with a frown, and went to the gate to meet -Denisov who was riding toward him. - -"Killed?" cried Denisov, recognizing from a distance the -unmistakably lifeless attitude--very familiar to him--in which Petya's -body was lying. - -"Done for!" repeated Dolokhov as if the utterance of these words -afforded him pleasure, and he went quickly up to the prisoners, who -were surrounded by Cossacks who had hurried up. "We won't take -them!" he called out to Denisov. - -Denisov did not reply; he rode up to Petya, dismounted, and with -trembling hands turned toward himself the bloodstained, -mud-bespattered face which had already gone white. - -"I am used to something sweet. Raisins, fine ones... take them all!" -he recalled Petya's words. And the Cossacks looked round in surprise -at the sound, like the yelp of a dog, with which Denisov turned -away, walked to the wattle fence, and seized hold of it. - -Among the Russian prisoners rescued by Denisov and Dolokhov was -Pierre Bezukhov. - - - - - -CHAPTER XII - -During the whole of their march from Moscow no fresh orders had been -issued by the French authorities concerning the party of prisoners -among whom was Pierre. On the twenty-second of October that party -was no longer with the same troops and baggage trains with which it -had left Moscow. Half the wagons laden with hardtack that had traveled -the first stages with them had been captured by Cossacks, the other -half had gone on ahead. Not one of those dismounted cavalrymen who had -marched in front of the prisoners was left; they had all -disappeared. The artillery the prisoners had seen in front of them -during the first days was now replaced by Marshal Junot's enormous -baggage train, convoyed by Westphalians. Behind the prisoners came a -cavalry baggage train. - -From Vyazma onwards the French army, which had till then moved in -three columns, went on as a single group. The symptoms of disorder -that Pierre had noticed at their first halting place after leaving -Moscow had now reached the utmost limit. - -The road along which they moved was bordered on both sides by dead -horses; ragged men who had fallen behind from various regiments -continually changed about, now joining the moving column, now again -lagging behind it. - -Several times during the march false alarms had been given and the -soldiers of the escort had raised their muskets, fired, and run -headlong, crushing one another, but had afterwards reassembled and -abused each other for their causeless panic. - -These three groups traveling together--the cavalry stores, the -convoy of prisoners, and Junot's baggage train--still constituted a -separate and united whole, though each of the groups was rapidly -melting away. - -Of the artillery baggage train which had consisted of a hundred -and twenty wagons, not more than sixty now remained; the rest had been -captured or left behind. Some of Junot's wagons also had been captured -or abandoned. Three wagons had been raided and robbed by stragglers -from Davout's corps. From the talk of the Germans Pierre learned -that a larger guard had been allotted to that baggage train than to -the prisoners, and that one of their comrades, a German soldier, had -been shot by the marshal's own order because a silver spoon -belonging to the marshal had been found in his possession. - -The group of prisoners had melted away most of all. Of the three -hundred and thirty men who had set out from Moscow fewer than a -hundred now remained. The prisoners were more burdensome to the escort -than even the cavalry saddles or Junot's baggage. They understood that -the saddles and Junot's spoon might be of some use, but that cold -and hungry soldiers should have to stand and guard equally cold and -hungry Russians who froze and lagged behind on the road (in which case -the order was to shoot them) was not merely incomprehensible but -revolting. And the escort, as if afraid, in the grievous condition -they themselves were in, of giving way to the pity they felt for the -prisoners and so rendering their own plight still worse, treated -them with particular moroseness and severity. - -At Dorogobuzh while the soldiers of the convoy, after locking the -prisoners in a stable, had gone off to pillage their own stores, -several of the soldier prisoners tunneled under the wall and ran away, -but were recaptured by the French and shot. - -The arrangement adopted when they started, that the officer -prisoners should be kept separate from the rest, had long since been -abandoned. All who could walk went together, and after the third stage -Pierre had rejoined Karataev and the gray-blue bandy-legged dog that -had chosen Karataev for its master. - -On the third day after leaving Moscow Karataev again fell ill with -the fever he had suffered from in the hospital in Moscow, and as he -grew gradually weaker Pierre kept away from him. Pierre did not know -why, but since Karataev had begun to grow weaker it had cost him an -effort to go near him. When he did so and heard the subdued moaning -with which Karataev generally lay down at the halting places, and when -he smelled the odor emanating from him which was now stronger than -before, Pierre moved farther away and did not think about him. - -While imprisoned in the shed Pierre had learned not with his -intellect but with his whole being, by life itself, that man is -created for happiness, that happiness is within him, in the -satisfaction of simple human needs, and that all unhappiness arises -not from privation but from superfluity. And now during these last -three weeks of the march he had learned still another new, consolatory -truth--that nothing in this world is terrible. He had learned that -as there is no condition in which man can be happy and entirely -free, so there is no condition in which he need be unhappy and lack -freedom. He learned that suffering and freedom have their limits and -that those limits are very near together; that the person in a bed -of roses with one crumpled petal suffered as keenly as he now, -sleeping on the bare damp earth with one side growing chilled while -the other was warming; and that when he had put on tight dancing shoes -he had suffered just as he did now when he walked with bare feet -that were covered with sores--his footgear having long since fallen to -pieces. He discovered that when he had married his wife--of his own -free will as it had seemed to him--he had been no more free than now -when they locked him up at night in a stable. Of all that he himself -subsequently termed his sufferings, but which at the time he -scarcely felt, the worst was the state of his bare, raw, and -scab-covered feet. (The horseflesh was appetizing and nourishing, -the saltpeter flavor of the gunpowder they used instead of salt was -even pleasant; there was no great cold, it was always warm walking -in the daytime, and at night there were the campfires; the lice that -devoured him warmed his body.) The one thing that was at first hard to -bear was his feet. - -After the second day's march Pierre, having examined his feet by the -campfire, thought it would be impossible to walk on them; but when -everybody got up he went along, limping, and, when he had warmed up, -walked without feeling the pain, though at night his feet were more -terrible to look at than before. However, he did not look at them now, -but thought of other things. - -Only now did Pierre realize the full strength of life in man and the -saving power he has of transferring his attention from one thing to -another, which is like the safety valve of a boiler that allows -superfluous steam to blow off when the pressure exceeds a certain -limit. - -He did not see and did not hear how they shot the prisoners who -lagged behind, though more than a hundred perished in that way. He did -not think of Karataev who grew weaker every day and evidently would -soon have to share that fate. Still less did Pierre think about -himself. The harder his position became and the more terrible the -future, the more independent of that position in which he found -himself were the joyful and comforting thoughts, memories, and -imaginings that came to him. - - - - - -CHAPTER XIII - - -At midday on the twenty-second of October Pierre was going uphill -along the muddy, slippery road, looking at his feet and at the -roughness of the way. Occasionally he glanced at the familiar crowd -around him and then again at his feet. The former and the latter -were alike familiar and his own. The blue-gray bandy legged dog ran -merrily along the side of the road, sometimes in proof of its -agility and self-satisfaction lifting one hind leg and hopping along -on three, and then again going on all four and rushing to bark at -the crows that sat on the carrion. The dog was merrier and sleeker -than it had been in Moscow. All around lay the flesh of different -animals--from men to horses--in various stages of decomposition; and -as the wolves were kept off by the passing men the dog could eat all -it wanted. - -It had been raining since morning and had seemed as if at any moment -it might cease and the sky clear, but after a short break it began -raining harder than before. The saturated road no longer absorbed -the water, which ran along the ruts in streams. - -Pierre walked along, looking from side to side, counting his steps -in threes, and reckoning them off on his fingers. Mentally -addressing the rain, he repeated: "Now then, now then, go on! Pelt -harder!" - -It seemed to him that he was thinking of nothing, but far down and -deep within him his soul was occupied with something important and -comforting. This something was a most subtle spiritual deduction -from a conversation with Karataev the day before. - -At their yesterday's halting place, feeling chilly by a dying -campfire, Pierre had got up and gone to the next one, which was -burning better. There Platon Karataev was sitting covered up--head and -all--with his greatcoat as if it were a vestment, telling the soldiers -in his effective and pleasant though now feeble voice a story Pierre -knew. It was already past midnight, the hour when Karataev was usually -free of his fever and particularly lively. When Pierre reached the -fire and heard Platon's voice enfeebled by illness, and saw his -pathetic face brightly lit up by the blaze, he felt a painful prick at -his heart. His feeling of pity for this man frightened him and he -wished to go away, but there was no other fire, and Pierre sat down, -trying not to look at Platon. - -"Well, how are you?" he asked. - -"How am I? If we grumble at sickness, God won't grant us death," -replied Platon, and at once resumed the story he had begun. - -"And so, brother," he continued, with a smile on his pale -emaciated face and a particularly happy light in his eyes, "you -see, brother..." - -Pierre had long been familiar with that story. Karataev had told -it to him alone some half-dozen times and always with a specially -joyful emotion. But well as he knew it, Pierre now listened to that -tale as to something new, and the quiet rapture Karataev evidently -felt as he told it communicated itself also to Pierre. The story was -of an old merchant who lived a good and God-fearing life with his -family, and who went once to the Nizhni fair with a companion--a -rich merchant. - -Having put up at an inn they both went to sleep, and next morning -his companion was found robbed and with his throat cut. A bloodstained -knife was found under the old merchant's pillow. He was tried, -knouted, and his nostrils having been torn off, "all in due form" as -Karataev put it, he was sent to hard labor in Siberia. - -"And so, brother" (it was at this point that Pierre came up), "ten -years or more passed by. The old man was living as a convict, -submitting as he should and doing no wrong. Only he prayed to God -for death. Well, one night the convicts were gathered just as we -are, with the old man among them. And they began telling what each was -suffering for, and how they had sinned against God. One told how he -had taken a life, another had taken two, a third had set a house on -fire, while another had simply been a vagrant and had done nothing. So -they asked the old man: 'What are you being punished for, Daddy?'--'I, -my dear brothers,' said he, 'am being punished for my own and other -men's sins. But I have not killed anyone or taken anything that was -not mine, but have only helped my poorer brothers. I was a merchant, -my dear brothers, and had much property. 'And he went on to tell -them all about it in due order. 'I don't grieve for myself,' he -says, 'God, it seems, has chastened me. Only I am sorry for my old -wife and the children,' and the old man began to weep. Now it happened -that in the group was the very man who had killed the other -merchant. 'Where did it happen, Daddy?' he said. 'When, and in what -month?' He asked all about it and his heart began to ache. So he comes -up to the old man like this, and falls down at his feet! 'You are -perishing because of me, Daddy,' he says. 'It's quite true, lads, that -this man,' he says, 'is being tortured innocently and for nothing! I,' -he says, 'did that deed, and I put the knife under your head while you -were asleep. Forgive me, Daddy,' he says, 'for Christ's sake!'" - -Karataev paused, smiling joyously as he gazed into the fire, and -he drew the logs together. - -"And the old man said, 'God will forgive you, we are all sinners -in His sight. I suffer for my own sins,' and he wept bitter tears. -Well, and what do you think, dear friends?" Karataev continued, his -face brightening more and more with a rapturous smile as if what he -now had to tell contained the chief charm and the whole meaning of his -story: "What do you think, dear fellows? That murderer confessed to -the authorities. 'I have taken six lives,' he says (he was a great -sinner), 'but what I am most sorry for is this old man. Don't let -him suffer because of me.' So he confessed and it was all written down -and the papers sent off in due form. The place was a long way off, and -while they were judging, what with one thing and another, filling in -the papers all in due form--the authorities I mean--time passed. The -affair reached the Tsar. After a while the Tsar's decree came: to -set the merchant free and give him a compensation that had been -awarded. The paper arrived and they began to look for the old man. -'Where is the old man who has been suffering innocently and in vain? A -paper has come from the Tsar!' so they began looking for him," here -Karataev's lower jaw trembled, "but God had already forgiven him--he -was dead! That's how it was, dear fellows!" Karataev concluded and sat -for a long time silent, gazing before him with a smile. - -And Pierre's soul was dimly but joyfully filled not by the story -itself but by its mysterious significance: by the rapturous joy that -lit up Karataev's face as he told it, and the mystic significance of -that joy. - - - - - -CHAPTER XIV - - -"A vos places!"* suddenly cried a voice. - - -*"To your places." - - -A pleasant feeling of excitement and an expectation of something -joyful and solemn was aroused among the soldiers of the convoy and the -prisoners. From all sides came shouts of command, and from the left -came smartly dressed cavalrymen on good horses, passing the -prisoners at a trot. The expression on all faces showed the tension -people feel at the approach of those in authority. The prisoners -thronged together and were pushed off the road. The convoy formed up. - -"The Emperor! The Emperor! The Marshal! The Duke!" and hardly had -the sleek cavalry passed, before a carriage drawn by six gray horses -rattled by. Pierre caught a glimpse of a man in a three-cornered hat -with a tranquil look on his handsome, plump, white face. It was one of -the marshals. His eye fell on Pierre's large and striking figure, -and in the expression with which he frowned and looked away Pierre -thought he detected sympathy and a desire to conceal that sympathy. - -The general in charge of the stores galloped after the carriage with -a red and frightened face, whipping up his skinny horse. Several -officers formed a group and some soldiers crowded round them. Their -faces all looked excited and worried. - -"What did he say? What did he say?" Pierre heard them ask. - -While the marshal was passing, the prisoners had huddled together in -a crowd, and Pierre saw Karataev whom he had not yet seen that -morning. He sat in his short overcoat leaning against a birch tree. On -his face, besides the look of joyful emotion it had worn yesterday -while telling the tale of the merchant who suffered innocently, -there was now an expression of quiet solemnity. - -Karataev looked at Pierre with his kindly round eyes now filled with -tears, evidently wishing him to come near that he might say -something to him. But Pierre was not sufficiently sure of himself. -He made as if he did not notice that look and moved hastily away. - -When the prisoners again went forward Pierre looked round. -Karataev was still sitting at the side of the road under the birch -tree and two Frenchmen were talking over his head. Pierre did not look -round again but went limping up the hill. - -From behind, where Karataev had been sitting, came the sound of a -shot. Pierre heard it plainly, but at that moment he remembered that -he had not yet finished reckoning up how many stages still remained to -Smolensk--a calculation he had begun before the marshal went by. And -he again started reckoning. Two French soldiers ran past Pierre, one -of whom carried a lowered and smoking gun. They both looked pale, -and in the expression on their faces--one of them glanced timidly at -Pierre--there was something resembling what he had seen on the face of -the young soldier at the execution. Pierre looked at the soldier and -remembered that, two days before, that man had burned his shirt -while drying it at the fire and how they had laughed at him. - -Behind him, where Karataev had been sitting, the dog began to -howl. "What a stupid beast! Why is it howling?" thought Pierre. - -His comrades, the prisoner soldiers walking beside him, avoided -looking back at the place where the shot had been fired and the dog -was howling, just as Pierre did, but there was a set look on all their -faces. - - - - - -CHAPTER XV - - -The stores, the prisoners, and the marshal's baggage train stopped -at the village of Shamshevo. The men crowded together round the -campfires. Pierre went up to the fire, ate some roast horseflesh, -lay down with his back to the fire, and immediately fell asleep. He -again slept as he had done at Mozhaysk after the battle of Borodino. - -Again real events mingled with dreams and again someone, he or -another, gave expression to his thoughts, and even to the same -thoughts that had been expressed in his dream at Mozhaysk. - -"Life is everything. Life is God. Everything changes and moves and -that movement is God. And while there is life there is joy in -consciousness of the divine. To love life is to love God. Harder and -more blessed than all else is to love this life in one's sufferings, -in innocent sufferings." - -"Karataev!" came to Pierre's mind. - -And suddenly he saw vividly before him a long-forgotten, kindly -old man who had given him geography lessons in Switzerland. "Wait a -bit," said the old man, and showed Pierre a globe. This globe was -alive--a vibrating ball without fixed dimensions. Its whole surface -consisted of drops closely pressed together, and all these drops moved -and changed places, sometimes several of them merging into one, -sometimes one dividing into many. Each drop tried to spread out and -occupy as much space as possible, but others striving to do the same -compressed it, sometimes destroyed it, and sometimes merged with it. - -"That is life," said the old teacher. - -"How simple and clear it is," thought Pierre. "How is it I did not -know it before?" - -"God is in the midst, and each drop tries to expand so as to reflect -Him to the greatest extent. And it grows, merges, disappears from -the surface, sinks to the depths, and again emerges. There now, -Karataev has spread out and disappeared. Do you understand, my child?" -said the teacher. - -"Do you understand, damn you?" shouted a voice, and Pierre woke up. - -He lifted himself and sat up. A Frenchman who had just pushed a -Russian soldier away was squatting by the fire, engaged in roasting -a piece of meat stuck on a ramrod. His sleeves were rolled up and -his sinewy, hairy, red hands with their short fingers deftly turned -the ramrod. His brown morose face with frowning brows was clearly -visible by the glow of the charcoal. - -"It's all the same to him," he muttered, turning quickly to a -soldier who stood behind him. "Brigand! Get away!" - -And twisting the ramrod he looked gloomily at Pierre, who turned -away and gazed into the darkness. A prisoner, the Russian soldier -the Frenchman had pushed away, was sitting near the fire patting -something with his hand. Looking more closely Pierre recognized the -blue-gray dog, sitting beside the soldier, wagging its tail. - -"Ah, he's come?" said Pierre. "And Plat-" he began, but did not -finish. - -Suddenly and simultaneously a crowd of memories awoke in his -fancy--of the look Platon had given him as he sat under the tree, of -the shot heard from that spot, of the dog's howl, of the guilty -faces of the two Frenchmen as they ran past him, of the lowered and -smoking gun, and of Karataev's absence at this halt--and he was on the -point of realizing that Karataev had been killed, but just at that -instant, he knew not why, the recollection came to his mind of a -summer evening he had spent with a beautiful Polish lady on the -veranda of his house in Kiev. And without linking up the events of the -day or drawing a conclusion from them, Pierre closed his eyes, -seeing a vision of the country in summertime mingled with memories -of bathing and of the liquid, vibrating globe, and he sank into -water so that it closed over his head. - -Before sunrise he was awakened by shouts and loud and rapid -firing. French soldiers were running past him. - -"The Cossacks!" one of them shouted, and a moment later a crowd of -Russians surrounded Pierre. - -For a long time he could not understand what was happening to him. -All around he heard his comrades sobbing with joy. - -"Brothers! Dear fellows! Darlings!" old soldiers exclaimed, weeping, -as they embraced Cossacks and hussars. - -The hussars and Cossacks crowded round the prisoners; one offered -them clothes, another boots, and a third bread. Pierre sobbed as he -sat among them and could not utter a word. He hugged the first soldier -who approached him, and kissed him, weeping. - -Dolokhov stood at the gate of the ruined house, letting a crowd of -disarmed Frenchmen pass by. The French, excited by all that had -happened, were talking loudly among themselves, but as they passed -Dolokhov who gently switched his boots with his whip and watched -them with cold glassy eyes that boded no good, they became silent. -On the opposite side stood Dolokhov's Cossack, counting the -prisoners and marking off each hundred with a chalk line on the gate. - -"How many?" Dolokhov asked the Cossack. - -"The second hundred," replied the Cossack. - -"Filez, filez!"* Dolokhov kept saying, having adopted this -expression from the French, and when his eyes met those of the -prisoners they flashed with a cruel light. - - -*"Get along, get along!" - - -Denisov, bareheaded and with a gloomy face, walked behind some -Cossacks who were carrying the body of Petya Rostov to a hole that had -been dug in the garden. - - - - - -CHAPTER XVI - - -After the twenty-eighth of October when the frosts began, the flight -of the French assumed a still more tragic character, with men -freezing, or roasting themselves to death at the campfires, while -carriages with people dressed in furs continued to drive past, -carrying away the property that had been stolen by the Emperor, kings, -and dukes; but the process of the flight and disintegration of the -French army went on essentially as before. - -From Moscow to Vyazma the French army of seventy-three thousand -men not reckoning the Guards (who did nothing during the whole war but -pillage) was reduced to thirty-six thousand, though not more than five -thousand had fallen in battle. From this beginning the succeeding -terms of the progression could be determined mathematically. The -French army melted away and perished at the same rate from Moscow to -Vyazma, from Vyazma to Smolensk, from Smolensk to the Berezina, and -from the Berezina to Vilna--independently of the greater or lesser -intensity of the cold, the pursuit, the barring of the way, or any -other particular conditions. Beyond Vyazma the French army instead -of moving in three columns huddled together into one mass, and so went -on to the end. Berthier wrote to his Emperor (we know how far -commanding officers allow themselves to diverge from the truth in -describing the condition of an army) and this is what he said: - - -I deem it my duty to report to Your Majesty the condition of the -various corps I have had occasion to observe during different stages -of the last two or three days' march. They are almost disbanded. -Scarcely a quarter of the soldiers remain with the standards of -their regiments, the others go off by themselves in different -directions hoping to find food and escape discipline. In general -they regard Smolensk as the place where they hope to recover. During -the last few days many of the men have been seen to throw away their -cartridges and their arms. In such a state of affairs, whatever your -ultimate plans may be, the interest of Your Majesty's service -demands that the army should be rallied at Smolensk and should first -of all be freed from ineffectives, such as dismounted cavalry, -unnecessary baggage, and artillery material that is no longer in -proportion to the present forces. The soldiers, who are worn out -with hunger and fatigue, need these supplies as well as a few days' -rest. Many have died last days on the road or at the bivouacs. This -state of things is continually becoming worse and makes one fear -that unless a prompt remedy is applied the troops will no longer be -under control in case of an engagement. - -November 9: twenty miles from Smolensk. - - -After staggering into Smolensk which seemed to them a promised land, -the French, searching for food, killed one another, sacked their own -stores, and when everything had been plundered fled farther. - -They all went without knowing whither or why they were going. -Still less did that genius, Napoleon, know it, for no one issued any -orders to him. But still he and those about him retained their old -habits: wrote commands, letters, reports, and orders of the day; -called one another sire, mon cousin, prince d'Eckmuhl, roi de -Naples, and so on. But these orders and reports were only on paper, -nothing in them was acted upon for they could not be carried out, -and though they entitled one another Majesties, Highnesses, or -Cousins, they all felt that they were miserable wretches who had -done much evil for which they had now to pay. And though they -pretended to be concerned about the army, each was thinking only of -himself and of how to get away quickly and save himself. - - - - -CHAPTER XVII - - -The movements of the Russian and French armies during the campaign -from Moscow back to the Niemen were like those in a game of Russian -blindman's bluff, in which two players are blindfolded and one of them -occasionally rings a little bell to inform the catcher of his -whereabouts. First he rings his bell fearlessly, but when he gets into -a tight place he runs away as quietly as he can, and often thinking to -escape runs straight into his opponent's arms. - -At first while they were still moving along the Kaluga road, -Napoleon's armies made their presence known, but later when they -reached the Smolensk road they ran holding the clapper of their bell -tight--and often thinking they were escaping ran right into the -Russians. - -Owing to the rapidity of the French flight and the Russian pursuit -and the consequent exhaustion of the horses, the chief means of -approximately ascertaining the enemy's position--by cavalry -scouting--was not available. Besides, as a result of the frequent -and rapid change of position by each army, even what information was -obtained could not be delivered in time. If news was received one -day that the enemy had been in a certain position the day before, by -the third day when something could have been done, that army was -already two days' march farther on and in quite another position. - -One army fled and the other pursued. Beyond Smolensk there were -several different roads available for the French, and one would have -thought that during their stay of four days they might have learned -where the enemy was, might have arranged some more advantageous plan -and undertaken something new. But after a four days' halt the mob, -with no maneuvers or plans, again began running along the beaten -track, neither to the right nor to the left but along the old--the -worst--road, through Krasnoe and Orsha. - -Expecting the enemy from behind and not in front, the French -separated in their flight and spread out over a distance of -twenty-four hours. In front of them all fled the Emperor, then the -kings, then the dukes. The Russian army, expecting Napoleon to take -the road to the right beyond the Dnieper--which was the only -reasonable thing for him to do--themselves turned to the right and -came out onto the highroad at Krasnoe. And here as in a game of -blindman's buff the French ran into our vanguard. Seeing their enemy -unexpectedly the French fell into confusion and stopped short from the -sudden fright, but then they resumed their flight, abandoning their -comrades who were farther behind. Then for three days separate -portions of the French army--first Murat's (the vice-king's), then -Davout's, and then Ney's--ran, as it were, the gauntlet of the Russian -army. They abandoned one another, abandoned all their heavy baggage, -their artillery, and half their men, and fled, getting past the -Russians by night by making semicircles to the right. - -Ney, who came last, had been busying himself blowing up the walls of -Smolensk which were in nobody's way, because despite the unfortunate -plight of the French or because of it, they wished to punish the floor -against which they had hurt themselves. Ney, who had had a corps of -ten thousand men, reached Napoleon at Orsha with only one thousand men -left, having abandoned all the rest and all his cannon, and having -crossed the Dnieper at night by stealth at a wooded spot. - -From Orsha they fled farther along the road to Vilna, still -playing at blindman's buff with the pursuing army. At the Berezina -they again became disorganized, many were drowned and many -surrendered, but those who got across the river fled farther. Their -supreme chief donned a fur coat and, having seated himself in a -sleigh, galloped on alone, abandoning his companions. The others who -could do so drove away too, leaving those who could not to surrender -or die. - - - - - -CHAPTER XVIII - - -This campaign consisted in a flight of the French during which -they did all they could to destroy themselves. From the time they -turned onto the Kaluga road to the day their leader fled from the -army, none of the movements of the crowd had any sense. So one might -have thought that regarding this period of the campaign the -historians, who attributed the actions of the mass to the will of -one man, would have found it impossible to make the story of the -retreat fit their theory. But no! Mountains of books have been written -by the historians about this campaign, and everywhere are described -Napoleon's arrangements, the maneuvers, and his profound plans which -guided the army, as well as the military genius shown by his marshals. - -The retreat from Malo-Yaroslavets when he had a free road into a -well-supplied district and the parallel road was open to him along -which Kutuzov afterwards pursued him--this unnecessary retreat along a -devastated road--is explained to us as being due to profound -considerations. Similarly profound considerations are given for his -retreat from Smolensk to Orsha. Then his heroism at Krasnoe is -described, where he is reported to have been prepared to accept battle -and take personal command, and to have walked about with a birch stick -and said: - -"J'ai assez fait l'empereur; il est temps de faire le general,"* but -nevertheless immediately ran away again, abandoning to its fate the -scattered fragments of the army he left behind. - - -*"I have acted the Emperor long enough; it is time to act the -general." - - -Then we are told of the greatness of soul of the marshals, -especially of Ney--a greatness of soul consisting in this: that he -made his way by night around through the forest and across the Dnieper -and escaped to Orsha, abandoning standards, artillery, and nine tenths -of his men. - -And lastly, the final departure of the great Emperor from his heroic -army is presented to us by the historians as something great and -characteristic of genius. Even that final running away, described in -ordinary language as the lowest depth of baseness which every child is -taught to be ashamed of--even that act finds justification in the -historians' language. - -When it is impossible to stretch the very elastic threads of -historical ratiocination any farther, when actions are clearly -contrary to all that humanity calls right or even just, the historians -produce a saving conception of "greatness." "Greatness," it seems, -excludes the standards of right and wrong. For the "great" man nothing -is wrong, there is no atrocity for which a "great" man can be blamed. - -"C'est grand!"* say the historians, and there no longer exists -either good or evil but only "grand" and "not grand." Grand is good, -not grand is bad. Grand is the characteristic, in their conception, of -some special animals called "heroes." And Napoleon, escaping home in a -warm fur coat and leaving to perish those who were not merely his -comrades but were (in his opinion) men he had brought there, feels que -c'est grand,*[2] and his soul is tranquil. - - -*"It is great." - -*[2] That it is great. - - -"Du sublime (he saw something sublime in himself) au ridicule il n'y -a qu'un pas,"* said he. And the whole world for fifty years has been -repeating: "Sublime! Grand! Napoleon le Grand!" Du sublime au ridicule -il n'y a qu'un pas. - - -*"From the sublime to the ridiculous is but a step." - - -And it occurs to no one that to admit a greatness not -commensurable with the standard of right and wrong is merely to -admit one's own nothingness and immeasurable meanness. - -For us with the standard of good and evil given us by Christ, no -human actions are incommensurable. And there is no greatness where -simplicity, goodness, and truth are absent. - - - - - -CHAPTER XIX - - -What Russian, reading the account of the last part of the campaign -of 1812, has not experienced an uncomfortable feeling of regret, -dissatisfaction, and perplexity? Who has not asked himself how it is -that the French were not all captured or destroyed when our three -armies surrounded them in superior numbers, when the disordered -French, hungry and freezing, surrendered in crowds, and when (as the -historians relate) the aim of the Russians was to stop the French, -to cut them off, and capture them all? - -How was it that the Russian army, which when numerically weaker than -the French had given battle at Borodino, did not achieve its purpose -when it had surrounded the French on three sides and when its aim -was to capture them? Can the French be so enormously superior to us -that when we had surrounded them with superior forces we could not -beat them? How could that happen? - -History (or what is called by that name) replying to these questions -says that this occurred because Kutuzov and Tormasov and Chichagov, -and this man and that man, did not execute such and such maneuvers... - -But why did they not execute those maneuvers? And why if they were -guilty of not carrying out a prearranged plan were they not tried -and punished? But even if we admitted that Kutuzov, Chichagov, and -others were the cause of the Russian failures, it is still -incomprehensible why, the position of the Russian army being what it -was at Krasnoe and at the Berezina (in both cases we had superior -forces), the French army with its marshals, kings, and Emperor was not -captured, if that was what the Russians aimed at. - -The explanation of this strange fact given by Russian military -historians (to the effect that Kutuzov hindered an attack) is -unfounded, for we know that he could not restrain the troops from -attacking at Vyazma and Tarutino. - -Why was the Russian army--which with inferior forces had withstood -the enemy in full strength at Borodino--defeated at Krasnoe and the -Berezina by the disorganized crowds of the French when it was -numerically superior? - -If the aim of the Russians consisted in cutting off and capturing -Napoleon and his marshals--and that aim was not merely frustrated -but all attempts to attain it were most shamefully baffled--then -this last period of the campaign is quite rightly considered by the -French to be a series of victories, and quite wrongly considered -victorious by Russian historians. - -The Russian military historians in so far as they submit to claims -of logic must admit that conclusion, and in spite of their lyrical -rhapsodies about valor, devotion, and so forth, must reluctantly admit -that the French retreat from Moscow was a series of victories for -Napoleon and defeats for Kutuzov. - -But putting national vanity entirely aside one feels that such a -conclusion involves a contradiction, since the series of French -victories brought the French complete destruction, while the series of -Russian defeats led to the total destruction of their enemy and the -liberation of their country. - -The source of this contradiction lies in the fact that the -historians studying the events from the letters of the sovereigns -and the generals, from memoirs, reports, projects, and so forth, -have attributed to this last period of the war of 1812 an aim that -never existed, namely that of cutting off and capturing Napoleon -with his marshals and his army. - -There never was or could have been such an aim, for it would have -been senseless and its attainment quite impossible. - -It would have been senseless, first because Napoleon's -disorganized army was flying from Russia with all possible speed, that -is to say, was doing just what every Russian desired. So what was -the use of performing various operations on the French who were -running away as fast as they possibly could? - -Secondly, it would have been senseless to block the passage of men -whose whole energy was directed to flight. - -Thirdly, it would have been senseless to sacrifice one's own -troops in order to destroy the French army, which without external -interference was destroying itself at such a rate that, though its -path was not blocked, it could not carry across the frontier more than -it actually did in December, namely a hundredth part of the original -army. - -Fourthly, it would have been senseless to wish to take captive the -Emperor, kings, and dukes--whose capture would have been in the -highest degree embarrassing for the Russians, as the most adroit -diplomatists of the time (Joseph de Maistre and others) recognized. -Still more senseless would have been the wish to capture army corps of -the French, when our own army had melted away to half before -reaching Krasnoe and a whole division would have been needed to convoy -the corps of prisoners, and when our men were not always getting -full rations and the prisoners already taken were perishing of hunger. - -All the profound plans about cutting off and capturing Napoleon -and his army were like the plan of a market gardener who, when driving -out of his garden a cow that had trampled down the beds he had -planted, should run to the gate and hit the cow on the head. The -only thing to be said in excuse of that gardener would be that he -was very angry. But not even that could be said for those who drew -up this project, for it was not they who had suffered from the -trampled beds. - -But besides the fact that cutting off Napoleon with his army would -have been senseless, it was impossible. - -It was impossible first because--as experience shows that a -three-mile movement of columns on a battlefield never coincides with -the plans--the probability of Chichagov, Kutuzov, and Wittgenstein -effecting a junction on time at an appointed place was so remote as to -be tantamount to impossibility, as in fact thought Kutuzov, who when -he received the plan remarked that diversions planned over great -distances do not yield the desired results. - -Secondly it was impossible, because to paralyze the momentum with -which Napoleon's army was retiring, incomparably greater forces than -the Russians possessed would have been required. - -Thirdly it was impossible, because the military term "to cut off" -has no meaning. One can cut off a slice of bread, but not an army. -To cut off an army--to bar its road--is quite impossible, for there is -always plenty of room to avoid capture and there is the night when -nothing can be seen, as the military scientists might convince -themselves by the example of Krasnoe and of the Berezina. It is only -possible to capture prisoners if they agree to be captured, just as it -is only possible to catch a swallow if it settles on one's hand. Men -can only be taken prisoners if they surrender according to the rules -of strategy and tactics, as the Germans did. But the French troops -quite rightly did not consider that this suited them, since death by -hunger and cold awaited them in flight or captivity alike. - -Fourthly and chiefly it was impossible, because never since the -world began has a war been fought under such conditions as those -that obtained in 1812, and the Russian army in its pursuit of the -French strained its strength to the utmost and could not have done -more without destroying itself. - -During the movement of the Russian army from Tarutino to Krasnoe -it lost fifty thousand sick or stragglers, that is a number equal to -the population of a large provincial town. Half the men fell out of -the army without a battle. - -And it is of this period of the campaign--when the army lacked boots -and sheepskin coats, was short of provisions and without vodka, and -was camping out at night for months in the snow with fifteen degrees -of frost, when there were only seven or eight hours of daylight and -the rest was night in which the influence of discipline cannot be -maintained, when men were taken into that region of death where -discipline fails, not for a few hours only as in a battle, but for -months, where they were every moment fighting death from hunger and -cold, when half the army perished in a single month--it is of this -period of the campaign that the historians tell us how Miloradovich -should have made a flank march to such and such a place, Tormasov to -another place, and Chichagov should have crossed (more than -knee-deep in snow) to somewhere else, and how so-and-so "routed" and -"cut off" the French and so on and so on. - -The Russians, half of whom died, did all that could and should -have been done to attain an end worthy of the nation, and they are not -to blame because other Russians, sitting in warm rooms, proposed -that they should do what was impossible. - -All that strange contradiction now difficult to understand between -the facts and the historical accounts only arises because the -historians dealing with the matter have written the history of the -beautiful words and sentiments of various generals, and not the -history of the events. - -To them the words of Miloradovich seem very interesting, and so do -their surmises and the rewards this or that general received; but -the question of those fifty thousand men who were left in hospitals -and in graves does not even interest them, for it does not come within -the range of their investigation. - -Yet one need only discard the study of the reports and general plans -and consider the movement of those hundreds of thousands of men who -took a direct part in the events, and all the questions that seemed -insoluble easily and simply receive an immediate and certain solution. - -The aim of cutting off Napoleon and his army never existed except in -the imaginations of a dozen people. It could not exist because it -was senseless and unattainable. - -The people had a single aim: to free their land from invasion. -That aim was attained in the first place of itself, as the French -ran away, and so it was only necessary not to stop their flight. -Secondly it was attained by the guerrilla warfare which was destroying -the French, and thirdly by the fact that a large Russian army was -following the French, ready to use its strength in case their movement -stopped. - -The Russian army had to act like a whip to a running animal. And the -experienced driver knew it was better to hold the whip raised as a -menace than to strike the running animal on the head. - - - - - -BOOK FIFTEEN: 1812 --13 - - - - - -CHAPTER I - - -When seeing a dying animal a man feels a sense of horror: -substance similar to his own is perishing before his eyes. But when it -is a beloved and intimate human being that is dying, besides this -horror at the extinction of life there is a severance, a spiritual -wound, which like a physical wound is sometimes fatal and sometimes -heals, but always aches and shrinks at any external irritating touch. - -After Prince Andrew's death Natasha and Princess Mary alike felt -this. Drooping in spirit and closing their eyes before the menacing -cloud of death that overhung them, they dared not look life in the -face. They carefully guarded their open wounds from any rough and -painful contact. Everything: a carriage passing rapidly in the street, -a summons to dinner, the maid's inquiry what dress to prepare, or -worse still any word of insincere or feeble sympathy, seemed an -insult, painfully irritated the wound, interrupting that necessary -quiet in which they both tried to listen to the stern and dreadful -choir that still resounded in their imagination, and hindered their -gazing into those mysterious limitless vistas that for an instant -had opened out before them. - -Only when alone together were they free from such outrage and -pain. They spoke little even to one another, and when they did it -was of very unimportant matters. - -Both avoided any allusion to the future. To admit the possibility of -a future seemed to them to insult his memory. Still more carefully did -they avoid anything relating to him who was dead. It seemed to them -that what they had lived through and experienced could not be -expressed in words, and that any reference to the details of his -life infringed the majesty and sacredness of the mystery that had been -accomplished before their eyes. - -Continued abstention from speech, and constant avoidance of -everything that might lead up to the subject--this halting on all -sides at the boundary of what they might not mention--brought before -their minds with still greater purity and clearness what they were -both feeling. - -But pure and complete sorrow is as impossible as pure and complete -joy. Princess Mary, in her position as absolute and independent -arbiter of her own fate and guardian and instructor of her nephew, was -the first to be called back to life from that realm of sorrow in which -she had dwelt for the first fortnight. She received letters from her -relations to which she had to reply; the room in which little Nicholas -had been put was damp and he began to cough; Alpatych came to -Yaroslavl with reports on the state of their affairs and with advice -and suggestions that they should return to Moscow to the house on -the Vozdvizhenka Street, which had remained uninjured and needed -only slight repairs. Life did not stand still and it was necessary -to live. Hard as it was for Princess Mary to emerge from the realm -of secluded contemplation in which she had lived till then, and -sorry and almost ashamed as she felt to leave Natasha alone, yet the -cares of life demanded her attention and she involuntarily yielded -to them. She went through the accounts with Alpatych, conferred with -Dessalles about her nephew, and gave orders and made preparations -for the journey to Moscow. - -Natasha remained alone and, from the time Princess Mary began making -preparations for departure, held aloof from her too. - -Princess Mary asked the countess to let Natasha go with her to -Moscow, and both parents gladly accepted this offer, for they saw -their daughter losing strength every day and thought that a change -of scene and the advice of Moscow doctors would be good for her. - -"I am not going anywhere," Natasha replied when this was proposed to -her. "Do please just leave me alone!" And she ran out of the room, -with difficulty refraining from tears of vexation and irritation -rather than of sorrow. - -After she felt herself deserted by Princes Mary and alone in her -grief, Natasha spent most of the time in her room by herself, -sitting huddled up feet and all in the corner of the sofa, tearing and -twisting something with her slender nervous fingers and gazing -intently and fixedly at whatever her eyes chanced to fall on. This -solitude exhausted and tormented her but she was in absolute need of -it. As soon as anyone entered she got up quickly, changed her position -and expression, and picked up a book or some sewing, evidently waiting -impatiently for the intruder to go. - -She felt all the time as if she might at any moment penetrate that -on which--with a terrible questioning too great for her strength- -her spiritual gaze was fixed. - -One day toward the end of December Natasha, pale and thin, dressed -in a black woolen gown, her plaited hair negligently twisted into a -knot, was crouched feet and all in the corner of her sofa, nervously -crumpling and smoothing out the end of her sash while she looked at -a corner of the door. - -She was gazing in the direction in which he had gone--to the other -side of life. And that other side of life, of which she had never -before thought and which had formerly seemed to her so far away and -improbable, was now nearer and more akin and more comprehensible -than this side of life, where everything was either emptiness and -desolation or suffering and indignity. - -She was gazing where she knew him to be; but she could not imagine -him otherwise than as he had been here. She now saw him again as he -had been at Mytishchi, at Troitsa, and at Yaroslavl. - -She saw his face, heard his voice, repeated his words and her own, -and sometimes devised other words they might have spoken. - -There he is lying back in an armchair in his velvet cloak, leaning -his head on his thin pale hand. His chest is dreadfully hollow and his -shoulders raised. His lips are firmly closed, his eyes glitter, and -a wrinkle comes and goes on his pale forehead. One of his legs -twitches just perceptibly, but rapidly. Natasha knows that he is -struggling with terrible pain. "What is that pain like? Why does he -have that pain? What does he feel? How does it hurt him?" thought -Natasha. He noticed her watching him, raised his eyes, and began to -speak seriously: - -"One thing would be terrible," said he: "to bind oneself forever -to a suffering man. It would be continual torture." And he looked -searchingly at her. Natasha as usual answered before she had time to -think what she would say. She said: "This can't go on--it won't. You -will get well--quite well." - -She now saw him from the commencement of that scene and relived what -she had then felt. She recalled his long sad and severe look at -those words and understood the meaning of the rebuke and despair in -that protracted gaze. - -"I agreed," Natasha now said to herself, "that it would be -dreadful if he always continued to suffer. I said it then only because -it would have been dreadful for him, but he understood it differently. -He thought it would be dreadful for me. He then still wished to live -and feared death. And I said it so awkwardly and stupidly! I did not -say what I meant. I thought quite differently. Had I said what I -thought, I should have said: even if he had to go on dying, to die -continually before my eyes, I should have been happy compared with -what I am now. Now there is nothing... nobody. Did he know that? No, -he did not and never will know it. And now it will never, never be -possible to put it right." And now he again seemed to be saying the -same words to her, only in her imagination Natasha this time gave -him a different answer. She stopped him and said: "Terrible for you, -but not for me! You know that for me there is nothing in life but you, -and to suffer with you is the greatest happiness for me," and he -took her hand and pressed it as he had pressed it that terrible -evening four days before his death. And in her imagination she said -other tender and loving words which she might have said then but -only spoke now: "I love thee!... thee! I love, love..." she said, -convulsively pressing her hands and setting her teeth with a desperate -effort... - -She was overcome by sweet sorrow and tears were already rising in -her eyes; then she suddenly asked herself to whom she was saying this. -Again everything was shrouded in hard, dry perplexity, and again -with a strained frown she peered toward the world where he was. And -now, now it seemed to her she was penetrating the mystery.... But at -the instant when it seemed that the incomprehensible was revealing -itself to her a loud rattle of the door handle struck painfully on her -ears. Dunyasha, her maid, entered the room quickly and abruptly with a -frightened look on her face and showing no concern for her mistress. - -"Come to your Papa at once, please!" said she with a strange, -excited look. "A misfortune... about Peter Ilynich... a letter," she -finished with a sob. - - - - - -CHAPTER II - - -Besides a feeling of aloofness from everybody Natasha was feeling -a special estrangement from the members of her own family. All of -them--her father, mother, and Sonya--were so near to her, so familiar, -so commonplace, that all their words and feelings seemed an insult -to the world in which she had been living of late, and she felt not -merely indifferent to them but regarded them with hostility. She heard -Dunyasha's words about Peter Ilynich and a misfortune, but did not -grasp them. - -"What misfortune? What misfortune can happen to them? They just live -their own old, quiet, and commonplace life," thought Natasha. - -As she entered the ballroom her father was hurriedly coming out of -her mother's room. His face was puckered up and wet with tears. He had -evidently run out of that room to give vent to the sobs that were -choking him. When he saw Natasha he waved his arms despairingly and -burst into convulsively painful sobs that distorted his soft round -face. - -"Pe... Petya... Go, go, she... is calling..." and weeping like a -child and quickly shuffling on his feeble legs to a chair, he almost -fell into it, covering his face with his hands. - -Suddenly an electric shock seemed to run through Natasha's whole -being. Terrible anguish struck her heart, she felt a dreadful ache -as if something was being torn inside her and she were dying. But -the pain was immediately followed by a feeling of release from the -oppressive constraint that had prevented her taking part in life. -The sight of her father, the terribly wild cries of her mother that -she heard through the door, made her immediately forget herself and -her own grief. - -She ran to her father, but he feebly waved his arm, pointing to -her mother's door. Princess Mary, pale and with quivering chin, came -out from that room and taking Natasha by the arm said something to -her. Natasha neither saw nor heard her. She went in with rapid -steps, pausing at the door for an instant as if struggling with -herself, and then ran to her mother. - -The countess was lying in an armchair in a strange and awkward -position, stretching out and beating her head against the wall. -Sonya and the maids were holding her arms. - -"Natasha! Natasha!..." cried the countess. "It's not true... it's -not true... He's lying... Natasha!" she shrieked, pushing those around -her away. "Go away, all of you; it's not true! Killed!... ha, ha, -ha!... It's not true!" - -Natasha put one knee on the armchair, stooped over her mother, -embraced her, and with unexpected strength raised her, turned her face -toward herself, and clung to her. - -"Mummy!... darling!... I am here, my dearest Mummy," she kept on -whispering, not pausing an instant. - -She did not let go of her mother but struggled tenderly with her, -demanded a pillow and hot water, and unfastened and tore open her -mother's dress. - -"My dearest darling... Mummy, my precious!..." she whispered -incessantly, kissing her head, her hands, her face, and feeling her -own irrepressible and streaming tears tickling her nose and cheeks. - -The countess pressed her daughter's hand, closed her eyes, and -became quiet for a moment. Suddenly she sat up with unaccustomed -swiftness, glanced vacantly around her, and seeing Natasha began to -press her daughter's head with all her strength. Then she turned -toward her daughter's face which was wincing with pain and gazed -long at it. - -"Natasha, you love me?" she said in a soft trustful whisper. -"Natasha, you would not deceive me? You'll tell me the whole truth?" - -Natasha looked at her with eyes full of tears and in her look -there was nothing but love and an entreaty for forgiveness. - -"My darling Mummy!" she repeated, straining all the power of her -love to find some way of taking on herself the excess of grief that -crushed her mother. - -And again in a futile struggle with reality her mother, refusing -to believe that she could live when her beloved boy was killed in -the bloom of life, escaped from reality into a world of delirium. - -Natasha did not remember how that day passed nor that night, nor the -next day and night. She did not sleep and did not leave her mother. -Her persevering and patient love seemed completely to surround the -countess every moment, not explaining or consoling, but recalling -her to life. - -During the third night the countess kept very quiet for a few -minutes, and Natasha rested her head on the arm of her chair and -closed her eyes, but opened them again on hearing the bedstead -creak. The countess was sitting up in bed and speaking softly. - -"How glad I am you have come. You are tired. Won't you have some -tea?" Natasha went up to her. "You have improved in looks and grown -more manly," continued the countess, taking her daughter's hand. - -"Mamma! What are you saying..." - -"Natasha, he is no more, no more!" - -And embracing her daughter, the countess began to weep for the first -time. - - - - - -CHAPTER III - - -Princess Mary postponed her departure. Sonya and the count tried -to replace Natasha but could not. They saw that she alone was able -to restrain her mother from unreasoning despair. For three weeks -Natasha remained constantly at her mother's side, sleeping on a lounge -chair in her room, making her eat and drink, and talking to her -incessantly because the mere sound of her tender, caressing tones -soothed her mother. - -The mother's wounded spirit could not heal. Petya's -death had torn from her half her life. When the news of Petya's -death had come she had been a fresh and vigorous woman of fifty, but a -month later she left her room a listless old woman taking no -interest in life. But the same blow that almost killed the countess, -this second blow, restored Natasha to life. - -A spiritual wound produced by a rending of the spiritual body is -like a physical wound and, strange as it may seem, just as a deep -wound may heal and its edges join, physical and spiritual wounds alike -can yet heal completely only as the result of a vital force from -within. - -Natasha's wound healed in that way. She thought her life was -ended, but her love for her mother unexpectedly showed her that the -essence of life--love--was still active within her. Love awoke and -so did life. - -Prince Andrew's last days had bound Princess Mary and Natasha -together; this new sorrow brought them still closer to one another. -Princess Mary put off her departure, and for three weeks looked -after Natasha as if she had been a sick child. The last weeks passed -in her mother's bedroom had strained Natasha's physical strength. - -One afternoon noticing Natasha shivering with fever, Princess Mary -took her to her own room and made her lie down on the bed. Natasha lay -down, but when Princess Mary had drawn the blinds and was going away -she called her back. - -"I don't want to sleep, Mary, sit by me a little." - -"You are tired--try to sleep." - -"No, no. Why did you bring me away? She will be asking for me." - -"She is much better. She spoke so well today," said Princess Mary. - -Natasha lay on the bed and in the semidarkness of the room scanned -Princess Mary's face. - -"Is she like him?" thought Natasha. "Yes, like and yet not like. But -she is quite original, strange, new, and unknown. And she loves me. -What is in her heart? All that is good. But how? What is her mind -like? What does she think about me? Yes, she is splendid!" - -"Mary," she said timidly, drawing Princess Mary's hand to herself, -"Mary, you mustn't think me wicked. No? Mary darling, how I love -you! Let us be quite, quite friends." - -And Natasha, embracing her, began kissing her face and hands, making -Princess Mary feel shy but happy by this demonstration of her -feelings. - -From that day a tender and passionate friendship such as exists only -between women was established between Princess Mary and Natasha. -They were continually kissing and saying tender things to one -another and spent most of their time together. When one went out the -other became restless and hastened to rejoin her. Together they felt -more in harmony with one another than either of them felt with herself -when alone. A feeling stronger than friendship sprang up between them; -an exclusive feeling of life being possible only in each other's -presence. - -Sometimes they were silent for hours; sometimes after they were -already in bed they would begin talking and go on till morning. They -spoke most of what was long past. Princess Mary spoke of her -childhood, of her mother, her father, and her daydreams; and -Natasha, who with a passive lack of understanding had formerly -turned away from that life of devotion, submission, and the poetry -of Christian self-sacrifice, now feeling herself bound to Princess -Mary by affection, learned to love her past too and to understand a -side of life previously incomprehensible to her. She did not think -of applying submission and self-abnegation to her own life, for she -was accustomed to seek other joys, but she understood and loved in -another those previously incomprehensible virtues. For Princess -Mary, listening to Natasha's tales of childhood and early youth, there -also opened out a new and hitherto uncomprehended side of life: belief -in life and its enjoyment. - -Just as before, they never mentioned him so as not to lower (as they -thought) their exalted feelings by words; but this silence about him -had the effect of making them gradually begin to forget him without -being conscious of it. - -Natasha had grown thin and pale and physically so weak that they all -talked about her health, and this pleased her. But sometimes she was -suddenly overcome by fear not only of death but of sickness, weakness, -and loss of good looks, and involuntarily she examined her bare arm -carefully, surprised at its thinness, and in the morning noticed her -drawn and, as it seemed to her, piteous face in her glass. It seemed -to her that things must be so, and yet it was dreadfully sad. - -One day she went quickly upstairs and found herself out of breath. -Unconsciously she immediately invented a reason for going down, and -then, testing her strength, ran upstairs again, observing the result. - -Another time when she called Dunyasha her voice trembled, so she -called again--though she could hear Dunyasha coming--called her in the -deep chest tones in which she had been wont to sing, sing, and -listened attentively to herself. - -She did not know and would not have believed it, but beneath the -layer of slime that covered her soul and seemed to her impenetrable, -delicate young shoots of grass were already sprouting, which taking -root would so cover with their living verdure the grief that weighed -her down that it would soon no longer be seen or noticed. The wound -had begun to heal from within. - -At the end of January Princess Mary left for Moscow, and the count -insisted on Natasha's going with her to consult the doctors. - - - - - -CHAPTER IV - - -After the encounter at Vyazma, where Kutuzov had been unable to hold -back his troops in their anxiety to overwhelm and cut off the enemy -and so on, the farther movement of the fleeing French, and of the -Russians who pursued them, continued as far as Krasnoe without a -battle. The flight was so rapid that the Russian army pursuing the -French could not keep up with them; cavalry and artillery horses broke -down, and the information received of the movements of the French -was never reliable. - -The men in the Russian army were so worn out by this continuous -marching at the rate of twenty-seven miles a day that they could not -go any faster. - -To realize the degree of exhaustion of the Russian army it is only -necessary to grasp clearly the meaning of the fact that, while not -losing more than five thousand killed and wounded after Tarutino and -less than a hundred prisoners, the Russian army which left that -place a hundred thousand strong reached Krasnoe with only fifty -thousand. - -The rapidity of the Russian pursuit was just as destructive to our -army as the flight of the French was to theirs. The only difference -was that the Russian army moved voluntarily, with no such threat of -destruction as hung over the French, and that the sick Frenchmen -were left behind in enemy hands while the sick Russians left behind -were among their own people. The chief cause of the wastage of -Napoleon's army was the rapidity of its movement, and a convincing -proof of this is the corresponding decrease of the Russian army. - -Kutuzov as far as was in his power, instead of trying to check the -movement of the French as was desired in Petersburg and by the Russian -army generals, directed his whole activity here, as he had done at -Tarutino and Vyazma, to hastening it on while easing the movement of -our army. - -But besides this, since the exhaustion and enormous diminution of -the army caused by the rapidity of the advance had become evident, -another reason for slackening the pace and delaying presented itself -to Kutuzov. The aim of the Russian army was to pursue the French. -The road the French would take was unknown, and so the closer our -troops trod on their heels the greater distance they had to cover. -Only by following at some distance could one cut across the zigzag -path of the French. All the artful maneuvers suggested by our generals -meant fresh movements of the army and a lengthening of its marches, -whereas the only reasonable aim was to shorten those marches. To -that end Kutuzov's activity was directed during the whole campaign -from Moscow to Vilna--not casually or intermittently but so -consistently that he never once deviated from it. - -Kutuzov felt and knew--not by reasoning or science but with the -whole of his Russian being--what every Russian soldier felt: that -the French were beaten, that the enemy was flying and must be driven -out; but at the same time he like the soldiers realized all the -hardship of this march, the rapidity of which was unparalleled for -such a time of the year. - -But to the generals, especially the foreign ones in the Russian -army, who wished to distinguish themselves, to astonish somebody, -and for some reason to capture a king or a duke--it seemed that now- -when any battle must be horrible and senseless--was the very time to -fight and conquer somebody. Kutuzov merely shrugged his shoulders when -one after another they presented projects of maneuvers to be made with -those soldiers--ill-shod, insufficiently clad, and half starved--who -within a month and without fighting a battle had dwindled to half -their number, and who at the best if the flight continued would have -to go a greater distance than they had already traversed, before -they reached the frontier. - -This longing to distinguish themselves, to maneuver, to overthrow, -and to cut off showed itself particularly whenever the Russians -stumbled on the French army. - -So it was at Krasnoe, where they expected to find one of the three -French columns and stumbled instead on Napoleon himself with sixteen -thousand men. Despite all Kutuzov's efforts to avoid that ruinous -encounter and to preserve his troops, the massacre of the broken mob -of French soldiers by worn-out Russians continued at Krasnoe for three -days. - -Toll wrote a disposition: "The first column will march to so and -so," etc. And as usual nothing happened in accord with the -disposition. Prince Eugene of Wurttemberg fired from a hill over the -French crowds that were running past, and demanded reinforcements -which did not arrive. The French, avoiding the Russians, dispersed and -hid themselves in the forest by night, making their way round as -best they could, and continued their flight. - -Miloradovich, who said he did not want to know anything about the -commissariat affairs of his detachment, and could never be found -when he was wanted--that chevalier sans peur et sans reproche* as he -styled himself--who was fond of parleys with the French, sent envoys -demanding their surrender, wasted time, and did not do what he was -ordered to do. - - -*Knight without fear and without reproach. - - -"I give you that column, lads," he said, riding up to the troops and -pointing out the French to the cavalry. - -And the cavalry, with spurs and sabers urging on horses that could -scarcely move, trotted with much effort to the column presented to -them--that is to say, to a crowd of Frenchmen stark with cold, -frost-bitten, and starving--and the column that had been presented -to them threw down its arms and surrendered as it had long been -anxious to do. - -At Krasnoe they took twenty-six thousand prisoners, several -hundred cannon, and a stick called a "marshal's staff," and disputed -as to who had distinguished himself and were pleased with their -achievement--though they much regretted not having taken Napoleon, -or at least a marshal or a hero of some sort, and reproached one -another and especially Kutuzov for having failed to do so. - -These men, carried away by their passions, were but blind tools of -the most melancholy law of necessity, but considered themselves heroes -and imagined that they were accomplishing a most noble and honorable -deed. They blamed Kutuzov and said that from the very beginning of the -campaign he had prevented their vanquishing Napoleon, that he -thought nothing but satisfying his passions and would not advance from -the Linen Factories because he was comfortable there, that at -Krasnoe he checked the advance because on learning that Napoleon was -there he had quite lost his head, and that it was probable that he had -an understanding with Napoleon and had been bribed by him, and so -on, and so on. - -Not only did his contemporaries, carried away by their passions, -talk in this way, but posterity and history have acclaimed Napoleon as -grand, while Kutuzov is described by foreigners as a crafty, -dissolute, weak old courtier, and by Russians as something indefinite- -a sort of puppet useful only because he had a Russian name. - - - - - -CHAPTER V - - -In 1812 and 1813 Kutuzov was openly accused of blundering. The -Emperor was dissatisfied with him. And in a history recently written -by order of the Highest Authorities it is said that Kutuzov was a -cunning court liar, frightened of the name of Napoleon, and that by -his blunders at Krasnoe and the Berezina he deprived the Russian -army of the glory of complete victory over the French.* - - -*History of the year 1812. The character of Kutuzov and -reflections on the unsatisfactory results of the battles at Krasnoe, -by Bogdanovich. - - -Such is the fate not of great men (grands hommes) whom the Russian -mind does not acknowledge, but of those rare and always solitary -individuals who, discerning the will of Providence, submit their -personal will to it. The hatred and contempt of the crowd punish -such men for discerning the higher laws. - -For Russian historians, strange and terrible to say, Napoleon- -that most insignificant tool of history who never anywhere, even in -exile, showed human dignity--Napoleon is the object of adulation and -enthusiasm; he is grand. But Kutuzov--the man who from the beginning -to the end of his activity in 1812, never once swerving by word or -deed from Borodino to Vilna, presented an example exceptional in -history of self-sacrifice and a present consciousness of the future -importance of what was happening--Kutuzov seems to them something -indefinite and pitiful, and when speaking of him and of the year -1812 they always seem a little ashamed. - -And yet it is difficult to imagine an historical character whose -activity was so unswervingly directed to a single aim; and it would be -difficult to imagine any aim more worthy or more consonant with the -will of the whole people. Still more difficult would it be to find -an instance in history of the aim of an historical personage being -so completely accomplished as that to which all Kutuzov's efforts were -directed in 1812. - -Kutuzov never talked of "forty centuries looking down from the -Pyramids," of the sacrifices he offered for the fatherland, or of what -he intended to accomplish or had accomplished; in general he said -nothing about himself, adopted no prose, always appeared to be the -simplest and most ordinary of men, and said the simplest and most -ordinary things. He wrote letters to his daughters and to Madame de -Stael, read novels, liked the society of pretty women, jested with -generals, officers, and soldiers, and never contradicted those who -tried to prove anything to him. When Count Rostopchin at the Yauza -bridge galloped up to Kutuzov with personal reproaches for having -caused the destruction of Moscow, and said: "How was it you promised -not to abandon Moscow without a battle?" Kutuzov replied: "And I shall -not abandon Moscow without a battle," though Moscow was then already -abandoned. When Arakcheev, coming to him from the Emperor, said that -Ermolov ought to be appointed chief of the artillery, Kutuzov replied: -"Yes, I was just saying so myself," though a moment before he had said -quite the contrary. What did it matter to him--who then alone amid a -senseless crowd understood the whole tremendous significance of what -was happening--what did it matter to him whether Rostopchin attributed -the calamities of Moscow to him or to himself? Still less could it -matter to him who was appointed chief of the artillery. - -Not merely in these cases but continually did that old man--who by -experience of life had reached the conviction that thoughts and the -words serving as their expression are not what move people--use -quite meaningless words that happened to enter his head. - -But that man, so heedless of his words, did not once during the -whole time of his activity utter one word inconsistent with the single -aim toward which he moved throughout the whole war. Obviously in spite -of himself, in very diverse circumstances, he repeatedly expressed his -real thoughts with the bitter conviction that he would not be -understood. Beginning with the battle of Borodino, from which time his -disagreement with those about him began, he alone said that the battle -of Borodino was a victory, and repeated this both verbally and in -his dispatches and reports up to the time of his death. He alone -said that the loss of Moscow is not the loss of Russia. In reply to -Lauriston's proposal of peace, he said: There can be no peace, for -such is the people's will. He alone during the retreat of the French -said that all our maneuvers are useless, everything is being -accomplished of itself better than we could desire; that the enemy -must be offered "a golden bridge"; that neither the Tarutino, the -Vyazma, nor the Krasnoe battles were necessary; that we must keep some -force to reach the frontier with, and that he would not sacrifice a -single Russian for ten Frenchmen. - -And this courtier, as he is described to us, who lies to Arakcheev -to please the Emperor, he alone--incurring thereby the Emperor's -displeasure--said in Vilna that to carry the war beyond the frontier -is useless and harmful. - -Nor do words alone prove that only he understood the meaning of -the events. His actions--without the smallest deviation--were all -directed to one and the same threefold end: (1) to brace all his -strength for conflict with the French, (2) to defeat them, and (3) -to drive them out of Russia, minimizing as far as possible the -sufferings of our people and of our army. - -This procrastinator Kutuzov, whose motto was "Patience and Time," -this enemy of decisive action, gave battle at Borodino, investing -the preparations for it with unparalleled solemnity. This Kutuzov -who before the battle of Austerlitz began said that it would be -lost, he alone, in contradiction to everyone else, declared till his -death that Borodino was a victory, despite the assurance of generals -that the battle was lost and despite the fact that for an army to have -to retire after winning a battle was unprecedented. He alone during -the whole retreat insisted that battles, which were useless then, -should not be fought, and that a new war should not be begun nor the -frontiers of Russia crossed. - -It is easy now to understand the significance of these events--if -only we abstain from attributing to the activity of the mass aims that -existed only in the heads of a dozen individuals--for the events and -results now lie before us. - -But how did that old man, alone, in opposition to the general -opinion, so truly discern the importance of the people's view of the -events that in all his activity he was never once untrue to it? - -The source of that extraordinary power of penetrating the meaning of -the events then occuring lay in the national feeling which he -possessed in full purity and strength. - -Only the recognition of the fact that he possessed this feeling -caused the people in so strange a manner, contrary to the Tsar's wish, -to select him--an old man in disfavor--to be their representative in -the national war. And only that feeling placed him on that highest -human pedestal from which he, the commander in chief, devoted all -his powers not to slaying and destroying men but to saving and showing -pity on them. - -That simple, modest, and therefore truly great, figure could not -be cast in the false mold of a European hero--the supposed ruler of -men--that history has invented. - -To a lackey no man can be great, for a lackey has his own conception -of greatness. - - - - - -CHAPTER VI - - -The fifth of November was the first day of what is called the battle -of Krasnoe. Toward evening--after much disputing and many mistakes -made by generals who did not go to their proper places, and after -adjutants had been sent about with counterorders--when it had become -plain that the enemy was everywhere in flight and that there could and -would be no battle, Kutuzov left Krasnoe and went to Dobroe whither -his headquarters had that day been transferred. - -The day was clear and frosty. Kutuzov rode to Dobroe on his plump -little white horse, followed by an enormous suite of discontented -generals who whispered among themselves behind his back. All along the -road groups of French prisoners captured that day (there were seven -thousand of them) were crowding to warm themselves at campfires. -Near Dobroe an immense crowd of tattered prisoners, buzzing with -talk and wrapped and bandaged in anything they had been able to get -hold of, were standing in the road beside a long row of unharnessed -French guns. At the approach of the commander in chief the buzz of -talk ceased and all eyes were fixed on Kutuzov who, wearing a white -cap with a red band and a padded overcoat that bulged on his round -shoulders, moved slowly along the road on his white horse. One of -the generals was reporting to him where the guns and prisoners had -been captured. - -Kutuzov seemed preoccupied and did not listen to what the general -was saying. He screwed up his eyes with a dissatisfied look as he -gazed attentively and fixedly at these prisoners, who presented a -specially wretched appearance. Most of them were disfigured by -frost-bitten noses and cheeks, and nearly all had red, swollen and -festering eyes. - -One group of the French stood close to the road, and two of them, -one of whom had his face covered with sores, were tearing a piece of -raw flesh with their hands. There was something horrible and bestial -in the fleeting glance they threw at the riders and in the -malevolent expression with which, after a glance at Kutuzov, the -soldier with the sores immediately turned away and went on with what -he was doing. - -Kutuzov looked long and intently at these two soldiers. He -puckered his face, screwed up his eyes, and pensively swayed his head. -At another spot he noticed a Russian soldier laughingly patting a -Frenchman on the shoulder, saying something to him in a friendly -manner, and Kutuzov with the same expression on his face again -swayed his head. - -"What were you saying?" he asked the general, who continuing his -report directed the commander in chief's attention to some standards -captured from the French and standing in front of the Preobrazhensk -regiment. - -"Ah, the standards!" said Kutuzov, evidently detaching himself -with difficulty from the thoughts that preoccupied him. - -He looked about him absently. Thousands of eyes were looking at -him from all sides awaiting a word from him. - -He stopped in front of the Preobrazhensk regiment, sighed deeply, -and closed his eyes. One of his suite beckoned to the soldiers -carrying the standards to advance and surround the commander in -chief with them. Kutuzov was silent for a few seconds and then, -submitting with evident reluctance to the duty imposed by his -position, raised his head and began to speak. A throng of officers -surrounded him. He looked attentively around at the circle of -officers, recognizing several of them. - -"I thank you all!" he said, addressing the soldiers and then again -the officers. In the stillness around him his slowly uttered words -were distinctly heard. "I thank you all for your hard and faithful -service. The victory is complete and Russia will not forget you! Honor -to you forever." - -He paused and looked around. - -"Lower its head, lower it!" he said to a soldier who had -accidentally lowered the French eagle he was holding before the -Preobrazhensk standards. "Lower, lower, that's it. Hurrah lads!" he -added, addressing the men with a rapid movement of his chin. - -"Hur-r-rah!" roared thousands of voices. - -While the soldiers were shouting Kutuzov leaned forward in his -saddle and bowed his head, and his eye lit up with a mild and -apparently ironic gleam. - -"You see, brothers..." said he when the shouts had ceased... and all -at once his voice and the expression of his face changed. It was no -longer the commander in chief speaking but an ordinary old man who -wanted to tell his comrades something very important. - -There was a stir among the throng of officers and in the ranks of -the soldiers, who moved that they might hear better what he was -going to say. - -"You see, brothers, I know it's hard for you, but it can't be -helped! Bear up; it won't be for long now! We'll see our visitors -off and then we'll rest. The Tsar won't forget your service. It is -hard for you, but still you are at home while they--you see what -they have come to," said he, pointing to the prisoners. "Worse off -than our poorest beggars. While they were strong we didn't spare -ourselves, but now we may even pity them. They are human beings too. -Isn't it so, lads?" - -He looked around, and in the direct, respectful, wondering gaze -fixed upon him he read sympathy with what he had said. His face grew -brighter and brighter with an old man's mild smile, which drew the -corners of his lips and eyes into a cluster of wrinkles. He ceased -speaking and bowed his head as if in perplexity. - -"But after all who asked them here? Serves them right, the bloody -bastards!" he cried, suddenly lifting his head. - -And flourishing his whip he rode off at a gallop for the first -time during the whole campaign, and left the broken ranks of the -soldiers laughing joyfully and shouting "Hurrah!" - -Kutuzov's words were hardly understood by the troops. No one could -have repeated the field marshal's address, begun solemnly and then -changing into an old man's simplehearted talk; but the hearty -sincerity of that speech, the feeling of majestic triumph combined -with pity for the foe and consciousness of the justice of our cause, -exactly expressed by that old man's good-natured expletives, was not -merely understood but lay in the soul of every soldier and found -expression in their joyous and long-sustained shouts. Afterwards -when one of the generals addressed Kutuzov asking whether he wished -his caleche to be sent for, Kutuzov in answering unexpectedly gave a -sob, being evidently greatly moved. - - - - - -CHAPTER VII - - -When the troops reached their night's halting place on the eighth of -November, the last day of the Krasnoe battles, it was already -growing dusk. All day it had been calm and frosty with occasional -lightly falling snow and toward evening it began to clear. Through the -falling snow a purple-black and starry sky showed itself and the frost -grew keener. - -An infantry regiment which had left Tarutino three thousand strong -but now numbered only nine hundred was one of the first to arrive that -night at its halting place--a village on the highroad. The -quartermasters who met the regiment announced that all the huts were -full of sick and dead Frenchmen, cavalrymen, and members of the staff. -There was only one hut available for the regimental commander. - -The commander rode up to his hut. The regiment passed through the -village and stacked its arms in front of the last huts. - -Like some huge many-limbed animal, the regiment began to prepare its -lair and its food. One part of it dispersed and waded knee-deep -through the snow into a birch forest to the right of the village, -and immediately the sound of axes and swords, the crashing of -branches, and merry voices could be heard from there. Another -section amid the regimental wagons and horses which were standing in a -group was busy getting out caldrons and rye biscuit, and feeding the -horses. A third section scattered through the village arranging -quarters for the staff officers, carrying out the French corpses -that were in the huts, and dragging away boards, dry wood, and -thatch from the roofs, for the campfires, or wattle fences to serve -for shelter. - -Some fifteen men with merry shouts were shaking down the high wattle -wall of a shed, the roof of which had already been removed. - -"Now then, all together--shove!" cried the voices, and the huge -surface of the wall, sprinkled with snow and creaking with frost, -was seen swaying in the gloom of the night. The lower stakes cracked -more and more and at last the wall fell, and with it the men who had -been pushing it. Loud, coarse laughter and joyous shouts ensued. - -"Now then, catch hold in twos! Hand up the lever! That's it... Where -are you shoving to?" - -"Now, all together! But wait a moment, boys... With a song!" - -All stood silent, and a soft, pleasant velvety voice began to -sing. At the end of the third verse as the last note died away, twenty -voices roared out at once: "Oo-oo-oo-oo! That's it. All together! -Heave away, boys!..." but despite their united efforts the wattle -hardly moved, and in the silence that followed the heavy breathing -of the men was audible. - -"Here, you of the Sixth Company! Devils that you are! Lend a hand... -will you? You may want us one of these days." - -Some twenty men of the Sixth Company who were on their way into -the village joined the haulers, and the wattle wall, which was about -thirty-five feet long and seven feet high, moved forward along the -village street, swaying, pressing upon and cutting the shoulders of -the gasping men. - -"Get along... Falling? What are you stopping for? There now..." - -Merry senseless words of abuse flowed freely. - -"What are you up to?" suddenly came the authoritative voice of a -sergeant major who came upon the men who were hauling their burden. -"There are gentry here; the general himself is in that hut, and you -foul-mouthed devils, you brutes, I'll give it to you!" shouted he, -hitting the first man who came in his way a swinging blow on the back. -"Can't you make less noise?" - -The men became silent. The soldier who had been struck groaned and -wiped his face, which had been scratched till it bled by his falling -against the wattle. - -"There, how that devil hits out! He's made my face all bloody," said -he in a frightened whisper when the sergeant major had passed on. - -"Don't you like it?" said a laughing voice, and moderating their -tones the men moved forward. - -When they were out of the village they began talking again as loud -as before, interlarding their talk with the same aimless expletives. - -In the hut which the men had passed, the chief officers had gathered -and were in animated talk over their tea about the events of the day -and the maneuvers suggested for tomorrow. It was proposed to make a -flank march to the left, cut off the Vice-King (Murat) and capture -him. - -By the time the soldiers had dragged the wattle fence to its place -the campfires were blazing on all sides ready for cooking, the wood -crackled, the snow was melting, and black shadows of soldiers -flitted to and fro all over the occupied space where the snow had been -trodden down. - -Axes and choppers were plied all around. Everything was done without -any orders being given. Stores of wood were brought for the night, -shelters were rigged up for the officers, caldrons were being -boiled, and muskets and accouterments put in order. - -The wattle wall the men had brought was set up in a semicircle by -the Eighth Company as a shelter from the north, propped up by musket -rests, and a campfire was built before it. They beat the tattoo, -called the roll, had supper, and settled down round the fires for -the night--some repairing their footgear, some smoking pipes, and some -stripping themselves naked to steam the lice out of their shirts. - - - - - -CHAPTER VIII - - -One would have thought that under the almost incredibly wretched -conditions the Russian soldiers were in at that time--lacking warm -boots and sheepskin coats, without a roof over their heads, in the -snow with eighteen degrees of frost, and without even full rations -(the commissariat did not always keep up with the troops)--they -would have presented a very sad and depressing spectacle. - -On the contrary, the army had never under the best material -conditions presented a more cheerful and animated aspect. This was -because all who began to grow depressed or who lost strength were -sifted out of the army day by day. All the physically or morally -weak had long since been left behind and only the flower of the -army--physically and mentally--remained. - -More men collected behind the wattle fence of the Eighth Company -than anywhere else. Two sergeants major were sitting with them and -their campfire blazed brighter than others. For leave to sit by -their wattle they demanded contributions of fuel. - -"Eh, Makeev! What has become of you, you son of a bitch? Are you -lost or have the wolves eaten you? Fetch some more wood!" shouted a -red-haired and red-faced man, screwing up his eyes and blinking -because of the smoke but not moving back from the fire. "And you, -Jackdaw, go and fetch some wood!" said he to another soldier. - -This red-haired man was neither a sergeant nor a corporal, but being -robust he ordered about those weaker than himself. The soldier they -called "Jackdaw," a thin little fellow with a sharp nose, rose -obediently and was about to go but at that instant there came into the -light of the fire the slender, handsome figure of a young soldier -carrying a load of wood. - -"Bring it here--that's fine!" - -They split up the wood, pressed it down on the fire, blew at it with -their mouths, and fanned it with the skirts of their greatcoats, -making the flames hiss and crackle. The men drew nearer and lit -their pipes. The handsome young soldier who had brought the wood, -setting his arms akimbo, began stamping his cold feet rapidly and -deftly on the spot where he stood. - -"Mother! The dew is cold but clear.... It's well that I'm a -musketeer..." he sang, pretending to hiccough after each syllable. - -"Look out, your soles will fly off!" shouted the red-haired man, -noticing that the sole of the dancer's boot was hanging loose. "What a -fellow you are for dancing!" - -The dancer stopped, pulled off the loose piece of leather, and threw -it on the fire. - -"Right enough, friend," said he, and, having sat down, took out of -his knapsack a scrap of blue French cloth, and wrapped it round his -foot. "It's the steam that spoils them," he added, stretching out -his feet toward the fire. - -"They'll soon be issuing us new ones. They say that when we've -finished hammering them, we're to receive double kits!" - -"And that son of a bitch Petrov has lagged behind after all, it -seems," said one sergeant major. - -"I've had an eye on him this long while," said the other. - -"Well, he's a poor sort of soldier..." - -"But in the Third Company they say nine men were missing yesterday." - -"Yes, it's all very well, but when a man's feet are frozen how can -he walk?" - -"Eh? Don't talk nonsense!" said a sergeant major. - -"Do you want to be doing the same?" said an old soldier, turning -reproachfully to the man who had spoken of frozen feet. - -"Well, you know," said the sharp-nosed man they called Jackdaw in -a squeaky and unsteady voice, raising himself at the other side of the -fire, "a plump man gets thin, but for a thin one it's death. Take -me, now! I've got no strength left," he added, with sudden -resolution turning to the sergeant major. "Tell them to send me to - -hospital; I'm aching all over; anyway I shan't be able to keep up." - -"That'll do, that'll do!" replied the sergeant major quietly. - -The soldier said no more and the talk went on. - -"What a lot of those Frenchies were taken today, and the fact is -that not one of them had what you might call real boots on," said a -soldier, starting a new theme. "They were no more than make-believes." - -"The Cossacks have taken their boots. They were clearing the hut for -the colonel and carried them out. It was pitiful to see them, boys," -put in the dancer. "As they turned them over one seemed still alive -and, would you believe it, he jabbered something in their lingo." - -"But they're a clean folk, lads," the first man went on; "he was -white--as white as birchbark--and some of them are such fine -fellows, you might think they were nobles." - -"Well, what do you think? They make soldiers of all classes there." - -"But they don't understand our talk at all," said the dancer with -a puzzled smile. "I asked him whose subject he was, and he jabbered in -his own way. A queer lot!" - -"But it's strange, friends," continued the man who had wondered at -their whiteness, "the peasants at Mozhaysk were saying that when -they began burying the dead--where the battle was you know--well, -those dead had been lying there for nearly a month, and says the -peasant, 'they lie as white as paper, clean, and not as much smell -as a puff of powder smoke.'" - -"Was it from the cold?" asked someone. - -"You're a clever fellow! From the cold indeed! Why, it was hot. If -it had been from the cold, ours would not have rotted either. 'But,' -he says, 'go up to ours and they are all rotten and maggoty. So,' he -says, 'we tie our faces up with kerchiefs and turn our heads away as -we drag them off: we can hardly do it. But theirs,' he says, 'are -white as paper and not so much smell as a whiff of gunpowder.'" - -All were silent. - -"It must be from their food," said the sergeant major. "They used to -gobble the same food as the gentry." - -No one contradicted him. - -"That peasant near Mozhaysk where the battle was said the men were -all called up from ten villages around and they carted for twenty days -and still didn't finish carting the dead away. And as for the -wolves, he says..." - -"That was a real battle," said an old soldier. "It's the only one -worth remembering; but since that... it's only been tormenting folk." - -"And do you know, Daddy, the day before yesterday we ran at them -and, my word, they didn't let us get near before they just threw -down their muskets and went on their knees. 'Pardon!' they say. That's -only one case. They say Platov took 'Poleon himself twice. But he -didn't know the right charm. He catches him and catches him--no -good! He turns into a bird in his hands and flies away. And there's no -way of killing him either." - -"You're a first-class liar, Kiselev, when I come to look at you!" - -"Liar, indeed! It's the real truth." - -"If he fell into my hands, when I'd caught him I'd bury him in the -ground with an aspen stake to fix him down. What a lot of men he's -ruined!" - -"Well, anyhow we're going to end it. He won't come here again," -remarked the old soldier, yawning. - -The conversation flagged, and the soldiers began settling down to -sleep. - -"Look at the stars. It's wonderful how they shine! You would think -the women had spread out their linen," said one of the men, gazing -with admiration at the Milky Way. - -"That's a sign of a good harvest next year." - -"We shall want some more wood." - -"You warm your back and your belly gets frozen. That's queer." - -"O Lord!" - -"What are you pushing for? Is the fire only for you? Look how he's -sprawling!" - -In the silence that ensued, the snoring of those who had fallen -asleep could be heard. Others turned over and warmed themselves, now -and again exchanging a few words. From a campfire a hundred paces -off came a sound of general, merry laughter. - -"Hark at them roaring there in the Fifth Company!" said one of the -soldiers, "and what a lot of them there are!" - -One of the men got up and went over to the Fifth Company. - -"They're having such fun," said he, coming back. "Two Frenchies have -turned up. One's quite frozen and the other's an awful swaggerer. He's -singing songs...." - -"Oh, I'll go across and have a look...." - -And several of the men went over to the Fifth Company. - - - - - -CHAPTER IX - - -The fifth company was bivouacking at the very edge of the forest. -A huge campfire was blazing brightly in the midst of the snow, -lighting up the branches of trees heavy with hoarfrost. - -About midnight they heard the sound of steps in the snow of the -forest, and the crackling of dry branches. - -"A bear, lads," said one of the men. - -They all raised their heads to listen, and out of the forest into -the bright firelight stepped two strangely clad human figures clinging -to one another. - -These were two Frenchmen who had been hiding in the forest. They -came up to the fire, hoarsely uttering something in a language our -soldiers did not understand. One was taller than the other; he wore an -officer's hat and seemed quite exhausted. On approaching the fire he -had been going to sit down, but fell. The other, a short sturdy -soldier with a shawl tied round his head, was stronger. He raised -his companion and said something, pointing to his mouth. The -soldiers surrounded the Frenchmen, spread a greatcoat on the ground -for the sick man, and brought some buckwheat porridge and vodka for -both of them. - -The exhausted French officer was Ramballe and the man with his -head wrapped in the shawl was Morel, his orderly. - -When Morel had drunk some vodka and finished his bowl of porridge he -suddenly became unnaturally merry and chattered incessantly to the -soldiers, who could not understand him. Ramballe refused food and -resting his head on his elbow lay silent beside the campfire, -looking at the Russian soldiers with red and vacant eyes. Occasionally -he emitted a long-drawn groan and then again became silent. Morel, -pointing to his shoulders, tried to impress on the soldiers the fact -that Ramballe was an officer and ought to be warmed. A Russian officer -who had come up to the fire sent to ask his colonel whether he would -not take a French officer into his hut to warm him, and when the -messenger returned and said that the colonel wished the officer to -be brought to him, Ramballe was told to go. He rose and tried to walk, -but staggered and would have fallen had not a soldier standing by held -him up. - -"You won't do it again, eh?" said one of the soldiers, winking and -turning mockingly to Ramballe. - -"Oh, you fool! Why talk rubbish, lout that you are--a real peasant!" -came rebukes from all sides addressed to the jesting soldier. - -They surrounded Ramballe, lifted him on the crossed arms of two -soldiers, and carried him to the hut. Ramballe put his arms around -their necks while they carried him and began wailing plaintively: - -"Oh, you fine fellows, my kind, kind friends! These are men! Oh, -my brave, kind friends," and he leaned his head against the shoulder -of one of the men like a child. - -Meanwhile Morel was sitting in the best place by the fire, -surrounded by the soldiers. - -Morel, a short sturdy Frenchman with inflamed and streaming eyes, -was wearing a woman's cloak and had a shawl tied woman fashion round -his head over his cap. He was evidently tipsy, and was singing a -French song in a hoarse broken voice, with an arm thrown round the -nearest soldier. The soldiers simply held their sides as they -watched him. - -"Now then, now then, teach us how it goes! I'll soon pick it up. How -is it?" said the man--a singer and a wag--whom Morel was embracing. - -"Vive Henri Quatre! Vive ce roi valiant!" sang Morel, winking. "Ce -diable a quatre..."* - - -*"Long live Henry the Fourth, that valiant king! That rowdy devil." - - -"Vivarika! Vif-seruvaru! Sedyablyaka!" repeated the soldier, -flourishing his arm and really catching the tune. - -"Bravo! Ha, ha, ha!" rose their rough, joyous laughter from all -sides. - -Morel, wrinkling up his face, laughed too. - -"Well, go on, go on!" - - "Qui eut le triple talent, - De boire, de battre, - Et d'etre un vert galant."* - - -*Who had a triple talent - - For drinking, for fighting, - - And for being a gallant old boy... - - -"It goes smoothly, too. Well, now, Zaletaev!" - -"Ke..." Zaletaev, brought out with effort: "ke-e-e-e," he drawled, -laboriously pursing his lips, "le-trip-ta-la-de-bu-de-ba, e -de-tra-va-ga-la" he sang. - -"Fine! Just like the Frenchie! Oh, ho ho! Do you want some more to -eat?" - -"Give him some porridge: it takes a long time to get filled up after -starving." - -They gave him some more porridge and Morel with a laugh set to -work on his third bowl. All the young soldiers smiled gaily as they -watched him. The older men, who thought it undignified to amuse -themselves with such nonsense, continued to lie at the opposite side -of the fire, but one would occasionally raise himself on an elbow -and glance at Morel with a smile. - -"They are men too," said one of them as he wrapped himself up in his -coat. "Even wormwood grows on its own root." - -"O Lord, O Lord! How starry it is! Tremendous! That means a hard -frost...." - -They all grew silent. The stars, as if knowing that no one was -looking at them, began to disport themselves in the dark sky: now -flaring up, now vanishing, now trembling, they were busy whispering -something gladsome and mysterious to one another. - - - - - -CHAPTER X - - -The French army melted away at the uniform rate of a mathematical -progression; and that crossing of the Berezina about which so much has -been written was only one intermediate stage in its destruction, and -not at all the decisive episode of the campaign. If so much has been -and still is written about the Berezina, on the French side this is -only because at the broken bridge across that river the calamities -their army had been previously enduring were suddenly concentrated -at one moment into a tragic spectacle that remained in every memory, -and on the Russian side merely because in Petersburg--far from the -seat of war--a plan (again one of Pfuel's) had been devised to catch -Napoleon in a strategic trap at the Berezina River. Everyone assured -himself that all would happen according to plan, and therefore -insisted that it was just the crossing of the Berezina that -destroyed the French army. In reality the results of the crossing were -much less disastrous to the French--in guns and men lost--than Krasnoe -had been, as the figures show. - -The sole importance of the crossing of the Berezina lies in the fact -that it plainly and indubitably proved the fallacy of all the plans -for cutting off the enemy's retreat and the soundness of the only -possible line of action--the one Kutuzov and the general mass of the -army demanded--namely, simply to follow the enemy up. The French crowd -fled at a continually increasing speed and all its energy was directed -to reaching its goal. It fled like a wounded animal and it was -impossible to block its path. This was shown not so much by the -arrangements it made for crossing as by what took place at the -bridges. When the bridges broke down, unarmed soldiers, people from -Moscow and women with children who were with the French transport, -all--carried on by vis inertiae--pressed forward into boats and into -the ice-covered water and did not, surrender. - -That impulse was reasonable. The condition of fugitives and of -pursuers was equally bad. As long as they remained with their own -people each might hope for help from his fellows and the definite -place he held among them. But those who surrendered, while remaining -in the same pitiful plight, would be on a lower level to claim a share -in the necessities of life. The French did not need to be informed -of the fact that half the prisoners--with whom the Russians did not -know what to do--perished of cold and hunger despite their captors' -desire to save them; they felt that it could not be otherwise. The -most compassionate Russian commanders, those favorable to the -French--and even the Frenchmen in the Russian service--could do -nothing for the prisoners. The French perished from the conditions -to which the Russian army was itself exposed. It was impossible to -take bread and clothes from our hungry and indispensable soldiers to -give to the French who, though not harmful, or hated, or guilty, -were simply unnecessary. Some Russians even did that, but they were -exceptions. - -Certain destruction lay behind the French but in front there was -hope. Their ships had been burned, there was no salvation save in -collective flight, and on that the whole strength of the French was -concentrated. - -The farther they fled the more wretched became the plight of the -remnant, especially after the Berezina, on which (in consequence of -the Petersburg plan) special hopes had been placed by the Russians, -and the keener grew the passions of the Russian commanders, blamed one -another and Kutuzov most of all. Anticipation that the failure of -the Petersburg Berezina plan would be attributed to Kutuzov led to -dissatisfaction, contempt, and ridicule, more and more strongly -expressed. The ridicule and contempt were of course expressed in a -respectful form, making it impossible for him to ask wherein he was to -blame. They did not talk seriously to him; when reporting to him or -asking for his sanction they appeared to be fulfilling a regrettable -formality, but they winked behind his back and tried to mislead him at -every turn. - -Because they could not understand him all these people assumed -that it was useless to talk to the old man; that he would never -grasp the profundity of their plans, that he would answer with his -phrases (which they thought were mere phrases) about a "golden -bridge," about the impossibility of crossing the frontier with a crowd -of tatterdemalions, and so forth. They had heard all that before. -And all he said--that it was necessary to await provisions, or that -the men had no boots--was so simple, while what they proposed was so -complicated and clever, that it was evident that he was old and stupid -and that they, though not in power, were commanders of genius. - -After the junction with the army of the brilliant admiral and -Petersburg hero Wittgenstein, this mood and the gossip of the staff -reached their maximum. Kutuzov saw this and merely sighed and shrugged -his shoulders. Only once, after the affair of the Berezina, did he get -angry and write to Bennigsen (who reported separately to the -Emperor) the following letter: - -"On account of your spells of ill health, will your excellency -please be so good as to set off for Kaluga on receipt of this, and -there await further commands and appointments from His Imperial -Majesty." - -But after Bennigsen's departure, the Grand Duke Tsarevich -Constantine Pavlovich joined the army. He had taken part in the -beginning of the campaign but had subsequently been removed from the -army by Kutuzov. Now having come to the army, he informed Kutuzov of -the Emperor's displeasure at the poor success of our forces and the -slowness of their advance. The Emperor intended to join the army -personally in a few days' time. - -The old man, experienced in court as well as in military affairs- -this same Kutuzov who in August had been chosen commander in chief -against the sovereign's wishes and who had removed the Grand Duke -and heir--apparent from the army--who on his own authority and -contrary to the Emperor's will had decided on the abandonment of -Moscow, now realized at once that his day was over, that his part -was played, and that the power he was supposed to hold was no longer -his. And he understood this not merely from the attitude of the court. -He saw on the one hand that the military business in which he had -played his part was ended and felt that his mission was -accomplished; and at the same time he began to be conscious of the -physical weariness of his aged body and of the necessity of physical -rest. - -On the twenty-ninth of November Kutuzov entered Vilna--his "dear -Vilna" as he called it. Twice during his career Kutuzov had been -governor of Vilna. In that wealthy town, which had not been injured, -he found old friends and associations, besides the comforts of life of -which he had so long been deprived. And he suddenly turned from the -cares of army and state and, as far as the passions that seethed -around him allowed, immersed himself in the quiet life to which he had -formerly been accustomed, as if all that was taking place and all that -had still to be done in the realm of history did not concern him at -all. - -Chichagov, one of the most zealous "cutters-off" and -"breakers-up," who had first wanted to effect a diversion in Greece -and then in Warsaw but never wished to go where he was sent: -Chichagov, noted for the boldness with which he spoke to the -Emperor, and who considered Kutuzov to be under an obligation to him -because when he was sent to make peace with Turkey in 1811 -independently of Kutuzov, and found that peace had already been -concluded, he admitted to the Emperor that the merit of securing -that peace was really Kutuzov's; this Chichagov was the first to -meet Kutuzov at the castle where the latter was to stay. In undress -naval uniform, with a dirk, and holding his cap under his arm, he -handed Kutuzov a garrison report and the keys of the town. The -contemptuously respectful attitude of the younger men to the old man -in his dotage was expressed in the highest degree by the behavior of -Chichagov, who knew of the accusations that were being directed -against Kutuzov. - -When speaking to Chichagov, Kutuzov incidentally mentioned that -the vehicles packed with china that had been captured from him at -Borisov had been recovered and would be restored to him. - -"You mean to imply that I have nothing to eat out of.... On the -contrary, I can supply you with everything even if you want to give -dinner parties," warmly replied Chichagov, who tried by every word -he spoke to prove his own rectitude and therefore imagined Kutuzov -to be animated by the same desire. - -Kutuzov, shrugging his shoulders, replied with his subtle -penetrating smile: "I meant merely to say what I said." - -Contrary to the Emperor's wish Kutuzov detained the greater part -of the army at Vilna. Those about him said that he became -extraordinarily slack and physically feeble during his stay in that -town. He attended to army affairs reluctantly, left everything to -his generals, and while awaiting the Emperor's arrival led a -dissipated life. - -Having left Petersburg on the seventh of December with his suite- -Count Tolstoy, Prince Volkonski, Arakcheev, and others--the Emperor -reached Vilna on the eleventh, and in his traveling sleigh drove -straight to the castle. In spite of the severe frost some hundred -generals and staff officers in full parade uniform stood in front of -the castle, as well as a guard of honor of the Semenov regiment. - -A courier who galloped to the castle in advance, in a troyka with -three foam-flecked horses, shouted "Coming!" and Konovnitsyn rushed -into the vestibule to inform Kutuzov, who was waiting in the hall -porter's little lodge. - -A minute later the old man's large stout figure in full-dress -uniform, his chest covered with orders and a scarf drawn round his -stomach, waddled out into the porch. He put on his hat with its -peaks to the sides and, holding his gloves in his hand and walking -with an effort sideways down the steps to the level of the street, -took in his hand the report he had prepared for the Emperor. - -There was running to and fro and whispering; another troyka -furiously up, and then all eyes were turned on an approaching sleigh -in which the figures of the Emperor and Volkonski could already be -descried. - -From the habit of fifty years all this had a physically agitating -effect on the old general. He carefully and hastily felt himself all -over, readjusted his hat, and pulling himself together drew himself up -and, at the very moment when the Emperor, having alighted from the -sleigh, lifted his eyes to him, handed him the report and began -speaking in his smooth, ingratiating voice. - -The Emperor with a rapid glance scanned Kutuzov from head to foot, -frowned for an instant, but immediately mastering himself went up to -the old man, extended his arms and embraced him. And this embrace too, -owing to a long-standing impression related to his innermost feelings, -had its usual effect on Kutuzov and he gave a sob. - -The Emperor greeted the officers and the Semenov guard, and again -pressing the old man's hand went with him into the castle. - -When alone with the field marshal the Emperor expressed his -dissatisfaction at the slowness of the pursuit and at the mistakes -made at Krasnoe and the Berezina, and informed him of his intentions -for a future campaign abroad. Kutuzov made no rejoinder or remark. The -same submissive, expressionless look with which he had listened to the -Emperor's commands on the field of Austerlitz seven years before -settled on his face now. - -When Kutuzov came out of the study and with lowered head was -crossing the ballroom with his heavy waddling gait, he was arrested by -someone's voice saying: - -"Your Serene Highness!" - -Kutuzov raised his head and looked for a long while into the eyes of -Count Tolstoy, who stood before him holding a silver salver on which -lay a small object. Kutuzov seemed not to understand what was expected -of him. - -Suddenly he seemed to remember; a scarcely perceptible smile flashed -across his puffy face, and bowing low and respectfully he took the -object that lay on the salver. It was the Order of St. George of the -First Class. - - - - - -CHAPTER XI - - -Next day the field marshal gave a dinner and ball which the -Emperor honored by his presence. Kutuzov had received the Order of St. -George of the First Class and the Emperor showed him the highest -honors, but everyone knew of the imperial dissatisfaction with him. -The proprieties were observed and the Emperor was the first to set -that example, but everybody understood that the old man was -blameworthy and good-for-nothing. When Kutuzov, conforming to a custom -of Catherine's day, ordered the standards that had been captured to be -lowered at the Emperor's feet on his entering the ballroom, the -Emperor made a wry face and muttered something in which some people -caught the words, "the old comedian." - -The Emperor's displeasure with Kutuzov was specially increased at -Vilna by the fact that Kutuzov evidently could not or would not -understand the importance of the coming campaign. - -When on the following morning the Emperor said to the officers -assembled about him: "You have not only saved Russia, you have saved -Europe!" they all understood that the war was not ended. - -Kutuzov alone would not see this and openly expressed his opinion -that no fresh war could improve the position or add to the glory of -Russia, but could only spoil and lower the glorious position that -Russia had gained. He tried to prove to the Emperor the -impossibility of levying fresh troops, spoke of the hardships -already endured by the people, of the possibility of failure and so -forth. - -This being the field marshal's frame of mind he was naturally -regarded as merely a hindrance and obstacle to the impending war. - -To avoid unpleasant encounters with the old man, the natural -method was to do what had been done with him at Austerlitz and with -Barclay at the beginning of the Russian campaign--to transfer the -authority to the Emperor himself, thus cutting the ground from under -the commander in chief's feet without upsetting the old man by -informing him of the change. - -With this object his staff was gradually reconstructed and its -real strength removed and transferred to the Emperor. Toll, -Konovnitsyn, and Ermolov received fresh appointments. Everyone spoke -loudly of the field marshal's great weakness and failing health. - -His health had to be bad for his place to be taken away and given to -another. And in fact his health was poor. - -So naturally, simply, and gradually--just as he had come from Turkey -to the Treasury in Petersburg to recruit the militia, and then to -the army when he was needed there--now when his part was played out, -Kutuzov's place was taken by a new and necessary performer. - -The war 1812, besides its national significance dear to every -Russian heart, was now to assume another, a European, significance. - -The movement of peoples from west to east was to be succeeded by a -movement of peoples from east to west, and for this fresh war -another leader was necessary, having qualities and views differing -from Kutuzov's and animated by different motives. - -Alexander I was as necessary for the movement of the peoples from -east to west and for the refixing of national frontiers as Kutuzov had -been for the salvation and glory of Russia. - -Kutuzov did not understand what Europe, the balance of power, or -Napoleon meant. He could not understand it. For the representative -of the Russian people, after the enemy had been destroyed and Russia -had been liberated and raised to the summit of her glory, there was -nothing left to do as a Russian. Nothing remained for the -representative of the national war but to die, and Kutuzov died. - - - - - -CHAPTER XII - - -As generally happens, Pierre did not feel the full effects of the -physical privation and strain he had suffered as prisoner until -after they were over. After his liberation he reached Orel, and on the -third day there, when preparing to go to Kiev, he fell ill and was -laid up for three months. He had what the doctors termed "bilious -fever." But despite the fact that the doctors treated him, bled him, -and gave him medicines to drink, he recovered. - -Scarcely any impression was left on Pierre's mind by all that -happened to him from the time of his rescue till his illness. He -remembered only the dull gray weather now rainy and now snowy, -internal physical distress, and pains in his feet and side. He -remembered a general impression of the misfortunes and sufferings of -people and of being worried by the curiosity of officers and -generals who questioned him, he also remembered his difficulty in -procuring a conveyance and horses, and above all he remembered his -incapacity to think and feel all that time. On the day of his rescue -he had seen the body of Petya Rostov. That same day he had learned -that Prince Andrew, after surviving the battle of Borodino for more -than a month had recently died in the Rostovs' house at Yaroslavl, and -Denisov who told him this news also mentioned Helene's death, -supposing that Pierre had heard of it long before. All this at the -time seemed merely strange to Pierre: he felt he could not grasp its -significance. Just then he was only anxious to get away as quickly -as possible from places where people were killing one another, to some -peaceful refuge where he could recover himself, rest, and think over -all the strange new facts he had learned; but on reaching Orel he -immediately fell ill. When he came to himself after his illness he saw -in attendance on him two of his servants, Terenty and Vaska, who had -come from Moscow; and also his cousin the eldest princess, who had -been living on his estate at Elets and hearing of his rescue and -illness had come to look after him. - -It was only gradually during his convalescence that Pierre lost -the impressions he had become accustomed to during the last few months -and got used to the idea that no one would oblige him to go anywhere -tomorrow, that no one would deprive him of his warm bed, and that he -would be sure to get his dinner, tea, and supper. But for a long -time in his dreams he still saw himself in the conditions of -captivity. In the same way little by little he came to understand -the news he had been told after his rescue, about the death of -Prince Andrew, the death of his wife, and the destruction of the -French. - -A joyous feeling of freedom--that complete inalienable freedom -natural to man which he had first experienced at the first halt -outside Moscow--filled Pierre's soul during his convalescence. He -was surprised to find that this inner freedom, which was independent -of external conditions, now had as it were an additional setting of -external liberty. He was alone in a strange town, without -acquaintances. No one demanded anything of him or sent him anywhere. -He had all he wanted: the thought of his wife which had been a -continual torment to him was no longer there, since she was no more. - -"Oh, how good! How splendid!" said he to himself when a cleanly laid -table was moved up to him with savory beef tea, or when he lay down -for the night on a soft clean bed, or when he remembered that the -French had gone and that his wife was no more. "Oh, how good, how -splendid!" - -And by old habit he asked himself the question: "Well, and what -then? What am I going to do?" And he immediately gave himself the -answer: "Well, I shall live. Ah, how splendid!" - -The very question that had formerly tormented him, the thing he -had continually sought to find--the aim of life--no longer existed for -him now. That search for the aim of life had not merely disappeared -temporarily--he felt that it no longer existed for him and could not -present itself again. And this very absence of an aim gave him the -complete, joyous sense of freedom which constituted his happiness at -this time. - -He could not see an aim, for he now had faith--not faith in any kind -of rule, or words, or ideas, but faith in an ever-living, -ever-manifest God. Formerly he had sought Him in aims he set -himself. That search for an aim had been simply a search for God, -and suddenly in his captivity he had learned not by words or reasoning -but by direct feeling what his nurse had told him long ago: that God -is here and everywhere. In his captivity he had learned that in -Karataev God was greater, more infinite and unfathomable than in the -Architect of the Universe recognized by the Freemasons. He felt like a -man who after straining his eyes to see into the far distance finds -what he sought at his very feet. All his life he had looked over the -heads of the men around him, when he should have merely looked in -front of him without straining his eyes. - -In the past he had never been able to find that great inscrutable -infinite something. He had only felt that it must exist somewhere -and had looked for it. In everything near and comprehensible he had -only what was limited, petty, commonplace, and senseless. He had -equipped himself with a mental telescope and looked into remote space, -where petty worldliness hiding itself in misty distance had seemed -to him great and infinite merely because it was not clearly seen. -And such had European life, politics, Freemasonry, philosophy, and -philanthropy seemed to him. But even then, at moments of weakness as -he had accounted them, his mind had penetrated to those distances -and he had there seen the same pettiness, worldliness, and -senselessness. Now, however, he had learned to see the great, eternal, -and infinite in everything, and therefore--to see it and enjoy its -contemplation--he naturally threw away the telescope through which -he had till now gazed over men's heads, and gladly regarded the -ever-changing, eternally great, unfathomable, and infinite life around -him. And the closer he looked the more tranquil and happy he became. -That dreadful question, "What for?" which had formerly destroyed all -his mental edifices, no longer existed for him. To that question, -"What for?" a simple answer was now always ready in his soul: "Because -there is a God, that God without whose will not one hair falls from -a man's head." - - - - - -CHAPTER XIII - - -In external ways Pierre had hardly changed at all. In appearance -he was just what he used to be. As before he was absent-minded and -seemed occupied not with what was before his eyes but with something -special of his own. The difference between his former and present self -was that formerly when he did not grasp what lay before him or was -said to him, he had puckered his forehead painfully as if vainly -seeking to distinguish something at a distance. At present he still -forgot what was said to him and still did not see what was before -his eyes, but he now looked with a scarcely perceptible and -seemingly ironic smile at what was before him and listened to what was -said, though evidently seeing and hearing something quite different. -Formerly he had appeared to be a kindhearted but unhappy man, and so -people had been inclined to avoid him. Now a smile at the joy of -life always played round his lips, and sympathy for others, shone in -his eyes with a questioning look as to whether they were as -contented as he was, and people felt pleased by his presence. - -Previously he had talked a great deal, grew excited when he -talked, and seldom listened; now he was seldom carried away in -conversation and knew how to listen so that people readily told him -their most intimate secrets. - -The princess, who had never liked Pierre and had been particularly -hostile to him since she had felt herself under obligations to him -after the old count's death, now after staying a short time in Orel- -where she had come intending to show Pierre that in spite of his -ingratitude she considered it her duty to nurse him--felt to her -surprise and vexation that she had become fond of him. Pierre did -not in any way seek her approval, he merely studied her with interest. -Formerly she had felt that he regarded her with indifference and -irony, and so had shrunk into herself as she did with others and had -shown him only the combative side of her nature; but now he seemed -to be trying to understand the most intimate places of her heart, and, -mistrustfully at first but afterwards gratefully, she let him see -the hidden, kindly sides of her character. - -The most cunning man could not have crept into her confidence more -successfully, evoking memories of the best times of her youth and -showing sympathy with them. Yet Pierre's cunning consisted simply in -finding pleasure in drawing out the human qualities of the embittered, -hard, and (in her own way) proud princess. - -"Yes, he is a very, very kind man when he is not under the influence -of bad people but of people such as myself," thought she. - -His servants too--Terenty and Vaska--in their own way noticed the -change that had taken place in Pierre. They considered that he had -become much "simpler." Terenty, when he had helped him undress and -wished him good night, often lingered with his master's boots in his -hands and clothes over his arm, to see whether he would not start a -talk. And Pierre, noticing that Terenty wanted a chat, generally -kept him there. - -"Well, tell me... now, how did you get food?" he would ask. - -And Terenty would begin talking of the destruction of Moscow, and of -the old count, and would stand for a long time holding the clothes and -talking, or sometimes listening to Pierre's stories, and then would go -out into the hall with a pleasant sense of intimacy with his master -and affection for him. - -The doctor who attended Pierre and visited him every day, though -he considered it his duty as a doctor to pose as a man whose every -moment was of value to suffering humanity, would sit for hours with -Pierre telling him his favorite anecdotes and his observations on -the characters of his patients in general, and especially of the -ladies. - -"It's a pleasure to talk to a man like that; he is not like our -provincials," he would say. - -There were several prisoners from the French army in Orel, and the -doctor brought one of them, a young Italian, to see Pierre. - -This officer began visiting Pierre, and the princess used to make -fun of the tenderness the Italian expressed for him. - -The Italian seemed happy only when he could come to see Pierre, talk -with him, tell him about his past, his life at home, and his love, and -pour out to him his indignation against the French and especially -against Napoleon. - -"If all Russians are in the least like you, it is sacrilege to fight -such a nation," he said to Pierre. "You, who have suffered so from the -French, do not even feel animosity toward them." - -Pierre had evoked the passionate affection of the Italian merely -by evoking the best side of his nature and taking a pleasure in so -doing. - -During the last days of Pierre's stay in Orel his old Masonic -acquaintance Count Willarski, who had introduced him to the lodge in -1807, came to see him. Willarski was married to a Russian heiress -who had a large estate in Orel province, and he occupied a temporary -post in the commissariat department in that town. - -Hearing that Bezukhov was in Orel, Willarski, though they had -never been intimate, came to him with the professions of friendship -and intimacy that people who meet in a desert generally express for -one another. Willarski felt dull in Orel and was pleased to meet a man -of his own circle and, as he supposed, of similar interests. - -But to his surprise Willarski soon noticed that Pierre had lagged -much behind the times, and had sunk, as he expressed it to himself, -into apathy and egotism. - -"You are letting yourself go, my dear fellow," he said. - -But for all that Willarski found it pleasanter now than it had -been formerly to be with Pierre, and came to see him every day. To -Pierre as he looked at and listened to Willarski, it seemed strange to -think that he had been like that himself but a short time before. - -Willarski was a married man with a family, busy with his family -affairs, his wife's affairs, and his official duties. He regarded -all these occupations as hindrances to life, and considered that -they were all contemptible because their aim was the welfare of -himself and his family. Military, administrative, political, and -Masonic interests continually absorbed his attention. And Pierre, -without trying to change the other's views and without condemning him, -but with the quiet, joyful, and amused smile now habitual to him, -was interested in this strange though very familiar phenomenon. - -There was a new feature in Pierre's relations with Willarski, with -the princess, with the doctor, and with all the people he now met, -which gained for him the general good will. This was his -acknowledgment of the impossibility of changing a man's convictions by -words, and his recognition of the possibility of everyone thinking, -feeling, and seeing things each from his own point of view. This -legitimate peculiarity of each individual which used to excite and -irritate Pierre now became a basis of the sympathy he felt for, and -the interest he took in, other people. The difference, and sometimes -complete contradiction, between men's opinions and their lives, and -between one man and another, pleased him and drew from him an amused -and gentle smile. - -In practical matters Pierre unexpectedly felt within himself a -center of gravity he had previously lacked. Formerly all pecuniary -questions, especially requests for money to which, as an extremely -wealthy man, he was very exposed, produced in him a state of -hopeless agitation and perplexity. "To give or not to give?" he had -asked himself. "I have it and he needs it. But someone else needs it -still more. Who needs it most? And perhaps they are both impostors?" -In the old days he had been unable to find a way out of all these -surmises and had given to all who asked as long as he had anything -to give. Formerly he had been in a similar state of perplexity with -regard to every question concerning his property, when one person -advised one thing and another something else. - -Now to his surprise he found that he no longer felt either doubt -or perplexity about these questions. There was now within him a -judge who by some rule unknown to him decided what should or should -not be done. - -He was as indifferent as heretofore to money matters, but now he -felt certain of what ought and what ought not to be done. The first -time he had recourse to his new judge was when a French prisoner, a -colonel, came to him and, after talking a great deal about his -exploits, concluded by making what amounted to a demand that Pierre -should give him four thousand francs to send to his wife and children. -Pierre refused without the least difficulty or effort, and was -afterwards surprised how simple and easy had been what used to -appear so insurmountably difficult. At the same time that he refused -the colonel's demand he made up his mind that he must have recourse to -artifice when leaving Orel, to induce the Italian officer to accept -some money of which he was evidently in need. A further proof to -Pierre of his own more settled outlook on practical matters was -furnished by his decision with regard to his wife's debts and to the -rebuilding of his houses in and near Moscow. - -His head steward came to him at Orel and Pierre reckoned up with him -his diminished income. The burning of Moscow had cost him, according -to the head steward's calculation, about two million rubles. - -To console Pierre for these losses the head steward gave him an -estimate showing that despite these losses his income would not be -diminished but would even be increased if he refused to pay his wife's -debts which he was under no obligation to meet, and did not rebuild -his Moscow house and the country house on his Moscow estate, which had -cost him eighty thousand rubles a year and brought in nothing. - -"Yes, of course that's true," said Pierre with a cheerful smile. -"I don't need all that at all. By being ruined I have become much -richer." - -But in January Savelich came from Moscow and gave him an account -of the state of things there, and spoke of the estimate an architect -had made of the cost of rebuilding the town and country houses, -speaking of this as of a settled matter. About the same time he -received letters from Prince Vasili and other Petersburg acquaintances -speaking of his wife's debts. And Pierre decided that the steward's -proposals which had so pleased him were wrong and that he must go to -Petersburg and settle his wife's affairs and must rebuild in Moscow. -Why this was necessary he did not know, but he knew for certain that -it was necessary. His income would be reduced by three fourths, but he -felt it must be done. - -Willarski was going to Moscow and they agreed to travel together. - -During the whole time of his convalescence in Orel Pierre had -experienced a feeling of joy, freedom, and life; but when during his -journey he found himself in the open world and saw hundreds of new -faces, that feeling was intensified. Throughout his journey he felt -like a schoolboy on holiday. Everyone--the stagecoach driver, the -post-house overseers, the peasants on the roads and in the villages- -had a new significance for him. The presence and remarks of -Willarski who continually deplored the ignorance and poverty of Russia -and its backwardness compared with Europe only heightened Pierre's -pleasure. Where Willarski saw deadness Pierre saw an extraordinary -strength and vitality--the strength which in that vast space amid -the snows maintained the life of this original, peculiar, and unique -people. He did not contradict Willarski and even seemed to agree -with him--an apparent agreement being the simplest way to avoid -discussions that could lead to nothing--and he smiled joyfully as he -listened to him. - - - - - -CHAPTER XIV - - -It would be difficult to explain why and whither ants whose heap has -been destroyed are hurrying: some from the heap dragging bits of -rubbish, larvae, and corpses, others back to the heap, or why they -jostle, overtake one another, and fight, and it would be equally -difficult to explain what caused the Russians after the departure of -the French to throng to the place that had formerly been Moscow. But -when we watch the ants round their ruined heap, the tenacity, -energy, and immense number of the delving insects prove that despite -the destruction of the heap, something indestructible, which though -intangible is the real strength of the colony, still exists; and -similarly, though in Moscow in the month of October there was no -government no churches, shrines, riches, or houses--it was still the -Moscow it had been in August. All was destroyed, except something -intangible yet powerful and indestructible. - -The motives of those who thronged from all sides to Moscow after -it had been cleared of the enemy were most diverse and personal, and -at first for the most part savage and brutal. One motive only they all -had in common: a desire to get to the place that had been called -Moscow, to apply their activities there. - -Within a week Moscow already had fifteen thousand inhabitants, in -a fortnight twenty-five thousand, and so on. By the autumn of 1813 the -number, ever increasing and increasing, exceeded what it had been in -1812. - -The first Russians to enter Moscow were the Cossacks of -Wintzingerode's detachment, peasants from the adjacent villages, and -residents who had fled from Moscow and had been hiding in its -vicinity. The Russians who entered Moscow, finding it plundered, -plundered it in their turn. They continued what the French had -begun. Trains of peasant carts came to Moscow to carry off to the -villages what had been abandoned in the ruined houses and the streets. -The Cossacks carried off what they could to their camps, and the -householders seized all they could find in other houses and moved it -to their own, pretending that it was their property. - -But the first plunderers were followed by a second and a third -contingent, and with increasing numbers plundering became more and -more difficult and assumed more definite forms. - -The French found Moscow abandoned but with all the organizations -of regular life, with diverse branches of commerce and -craftsmanship, with luxury, and governmental and religious -institutions. These forms were lifeless but still existed. There -were bazaars, shops, warehouses, market stalls, granaries--for the -most part still stocked with goods--and there were factories and -workshops, palaces and wealthy houses filled with luxuries, hospitals, -prisons, government offices, churches, and cathedrals. The longer -the French remained the more these forms of town life perished, -until finally all was merged into one confused, lifeless scene of -plunder. - -The more the plundering by the French continued, the more both the -wealth of Moscow and the strength of its plunderers was destroyed. But -plundering by the Russians, with which the reoccupation of the city -began, had an opposite effect: the longer it continued and the greater -the number of people taking part in it the more rapidly was the wealth -of the city and its regular life restored. - -Besides the plunderers, very various people, some drawn by -curiosity, some by official duties, some by self-interest--house -owners, clergy, officials of all kinds, tradesmen, artisans, and -peasants--streamed into Moscow as blood flows to the heart. - -Within a week the peasants who came with empty carts to carry off -plunder were stopped by the authorities and made to cart the corpses -out of the town. Other peasants, having heard of their comrades' -discomfiture, came to town bringing rye, oats, and hay, and beat -down one another's prices to below what they had been in former -days. Gangs of carpenters hoping for high pay arrived in Moscow -every day, and on all sides logs were being hewn, new houses built, -and old, charred ones repaired. Tradesmen began trading in booths. -Cookshops and taverns were opened in partially burned houses. The -clergy resumed the services in many churches that had not been burned. -Donors contributed Church property that had been stolen. Government -clerks set up their baize-covered tables and their pigeonholes of -documents in small rooms. The higher authorities and the police -organized the distribution of goods left behind by the French. The -owners of houses in which much property had been left, brought there -from other houses, complained of the injustice of taking everything to -the Faceted Palace in the Kremlin; others insisted that as the -French had gathered things from different houses into this or that -house, it would be unfair to allow its owner to keep all that was -found there. They abused the police and bribed them, made out -estimates at ten times their value for government stores that had -perished in the fire, and demanded relief. And Count Rostopchin -wrote proclamations. - - - - - -CHAPTER XV - - -At the end of January Pierre went to Moscow and stayed in an annex -of his house which had not been burned. He called on Count -Rostopchin and on some acquaintances who were back in Moscow, and he -intended to leave for Petersburg two days later. Everybody was -celebrating the victory, everything was bubbling with life in the -ruined but reviving city. Everyone was pleased to see Pierre, everyone -wished to meet him, and everyone questioned him about what he had -seen. Pierre felt particularly well disposed toward them all, but -was now instinctively on his guard for fear of binding himself in -any way. To all questions put to him--whether important or quite -trifling--such as: Where would he live? Was he going to rebuild? -When was he going to Petersburg and would he mind taking a parcel -for someone?--he replied: "Yes, perhaps," or, "I think so," and so on. - -He had heard that the Rostovs were at Kostroma but the thought of -Natasha seldom occurred to him. If it did it was only as a pleasant -memory of the distant past. He felt himself not only free from -social obligations but also from that feeling which, it seemed to him, -he had aroused in himself. - -On the third day after his arrival he heard from the Drubetskoys -that Princess Mary was in Moscow. The death, sufferings, and last days -of Prince Andrew had often occupied Pierre's thoughts and now recurred -to him with fresh vividness. Having heard at dinner that Princess Mary -was in Moscow and living in her house--which had not been burned--in -Vozdvizhenka Street, he drove that same evening to see her. - -On his way to the house Pierre kept thinking of Prince Andrew, of -their friendship, of his various meetings with him, and especially -of the last one at Borodino. - -"Is it possible that he died in the bitter frame of mind he was then -in? Is it possible that the meaning of life was not disclosed to him -before he died?" thought Pierre. He recalled Karataev and his death -and involuntarily began to compare these two men, so different, and -yet so similar in that they had both lived and both died and in the -love he felt for both of them. - -Pierre drove up to the house of the old prince in a most serious -mood. The house had escaped the fire; it showed signs of damage but -its general aspect was unchanged. The old footman, who met Pierre with -a stern face as if wishing to make the visitor feel that the absence -of the old prince had not disturbed the order of things in the -house, informed him that the princess had gone to her own -apartments, and that she received on Sundays. - -"Announce me. Perhaps she will see me," said Pierre. - -"Yes, sir," said the man. "Please step into the portrait gallery." - -A few minutes later the footman returned with Dessalles, who brought -word from the princess that she would be very glad to see Pierre if he -would excuse her want of ceremony and come upstairs to her apartment. - -In a rather low room lit by one candle sat the princess and with her -another person dressed in black. Pierre remembered that the princess -always had lady companions, but who they were and what they were -like he never knew or remembered. "This must be one of her -companions," he thought, glancing at the lady in the black dress. - -The princess rose quickly to meet him and held out her hand. - -"Yes," she said, looking at his altered face after he had kissed her -hand, "so this is how we meet again. He spoke of you even at the -very last," she went on, turning her eyes from Pierre to her companion -with a shyness that surprised him for an instant. - -"I was so glad to hear of your safety. It was the first piece of -good news we had received for a long time." - -Again the princess glanced round at her companion with even more -uneasiness in her manner and was about to add something, but Pierre -interrupted her. - -"Just imagine--I knew nothing about him!" said he. "I thought he had -been killed. All I know I heard at second hand from others. I only -know that he fell in with the Rostovs.... What a strange coincidence!" - -Pierre spoke rapidly and with animation. He glanced once at the -companion's face, saw her attentive and kindly gaze fixed on him, and, -as often happens when one is talking, felt somehow that this companion -in the black dress was a good, kind, excellent creature who would -not hinder his conversing freely with Princess Mary. - -But when he mentioned the Rostovs, Princess Mary's face expressed -still greater embarrassment. She again glanced rapidly from Pierre's -face to that of the lady in the black dress and said: - -"Do you really not recognize her?" - -Pierre looked again at the companion's pale, delicate face with -its black eyes and peculiar mouth, and something near to him, long -forgotten and more than sweet, looked at him from those attentive -eyes. - -"But no, it can't be!" he thought. "This stern, thin, pale face that -looks so much older! It cannot be she. It merely reminds me of her." -But at that moment Princess Mary said, "Natasha!" And with difficulty, -effort, and stress, like the opening of a door grown rusty on its -hinges, a smile appeared on the face with the attentive eyes, and from -that opening door came a breath of fragrance which suffused Pierre -with a happiness he had long forgotten and of which he had not even -been thinking--especially at that moment. It suffused him, seized him, -and enveloped him completely. When she smiled doubt was no longer -possible, it was Natasha and he loved her. - -At that moment Pierre involuntarily betrayed to her, to Princess -Mary, and above all to himself, a secret of which he himself had -been unaware. He flushed joyfully yet with painful distress. He -tried to hide his agitation. But the more he tried to hide it the more -clearly--clearer than any words could have done--did he betray to -himself, to her, and to Princess Mary that he loved her. - -"No, it's only the unexpectedness of it," thought Pierre. But as -soon as he tried to continue the conversation he had begun with -Princess Mary he again glanced at Natasha, and a still-deeper flush -suffused his face and a still-stronger agitation of mingled joy and -fear seized his soul. He became confused in his speech and stopped -in the middle of what he was saying. - -Pierre had failed to notice Natasha because he did not at all expect -to see her there, but he had failed to recognize her because the -change in her since he last saw her was immense. She had grown thin -and pale, but that was not what made her unrecognizable; she was -unrecognizable at the moment he entered because on that face whose -eyes had always shone with a suppressed smile of the joy of life, -now when he first entered and glanced at her there was not the least -shadow of a smile: only her eyes were kindly attentive and sadly -interrogative. - -Pierre's confusion was not reflected by any confusion on Natasha's -part, but only by the pleasure that just perceptibly lit up her -whole face. - - - - - -CHAPTER XVI - - -"She has come to stay with me," said Princess Mary. "The count and -countess will be here in a few days. The countess is in a dreadful -state; but it was necessary for Natasha herself to see a doctor. -They insisted on her coming with me." - -"Yes, is there a family free from sorrow now?" said Pierre, -addressing Natasha. "You know it happened the very day we were -rescued. I saw him. What a delightful boy he was!" - -Natasha looked at him, and by way of answer to his words her eyes -widened and lit up. - -"What can one say or think of as a consolation?" said Pierre. -"Nothing! Why had such a splendid boy, so full of life, to die?" - -"Yes, in these days it would be hard to live without faith..." -remarked Princess Mary. - -"Yes, yes, that is really true," Pierre hastily interrupted her. - -"Why is it true?" Natasha asked, looking attentively into Pierre's -eyes. - -"How can you ask why?" said Princess Mary. "The thought alone of -what awaits..." - -Natasha without waiting for Princess Mary to finish again looked -inquiringly at Pierre. - -"And because," Pierre continued, "only one who believes that there -is a God ruling us can bear a loss such as hers and... yours." - -Natasha had already opened her mouth to speak but suddenly -stopped. Pierre hurriedly turned away from her and again addressed -Princess Mary, asking about his friend's last days. - -Pierre's confusion had now almost vanished, but at the same time -he felt that his freedom had also completely gone. He felt that -there was now a judge of his every word and action whose judgment -mattered more to him than that of all the rest of the world. As he -spoke now he was considering what impression his words would make on -Natasha. He did not purposely say things to please her, but whatever -he was saying he regarded from her standpoint. - -Princess Mary--reluctantly as is usual in such cases--began -telling of the condition in which she had found Prince Andrew. But -Pierre's face quivering with emotion, his questions and his eager -restless expression, gradually compelled her to go into details -which she feared to recall for her own sake. - -"Yes, yes, and so...?" Pierre kept saying as he leaned toward her -with his whole body and eagerly listened to her story. "Yes, yes... so -he grew tranquil and softened? With all his soul he had always -sought one thing--to be perfectly good--so he could not be afraid of -death. The faults he had--if he had any--were not of his making. So he -did soften?... What a happy thing that he saw you again," he added, -suddenly turning to Natasha and looking at her with eyes full of -tears. - -Natasha's face twitched. She frowned and lowered her eyes for a -moment. She hesitated for an instant whether to speak or not. - -"Yes, that was happiness," she then said in her quiet voice with its -deep chest notes. "For me it certainly was happiness." She paused. -"And he... he... he said he was wishing for it at the very moment I -entered the room...." - -Natasha's voice broke. She blushed, pressed her clasped hands on her -knees, and then controlling herself with an evident effort lifted -her head and began to speak rapidly. - -"We knew nothing of it when we started from Moscow. I did not dare -to ask about him. Then suddenly Sonya told me he was traveling with -us. I had no idea and could not imagine what state he was in, all I -wanted was to see him and be with him," she said, trembling, and -breathing quickly. - -And not letting them interrupt her she went on to tell what she -had never yet mentioned to anyone--all she had lived through during -those three weeks of their journey and life at Yaroslavl. - -Pierre listened to her with lips parted and eyes fixed upon her full -of tears. As he listened he did not think of Prince Andrew, nor of -death, nor of what she was telling. He listened to her and felt only -pity for her, for what she was suffering now while she was speaking. - -Princess Mary, frowning in her effort to hold back her tears, sat -beside Natasha, and heard for the first time the story of those last -days of her brother's and Natasha's love. - -Evidently Natasha needed to tell that painful yet joyful tale. - -She spoke, mingling most trifling details with the intimate -secrets of her soul, and it seemed as if she could never finish. -Several times she repeated the same thing twice. - -Dessalles' voice was heard outside the door asking whether little -Nicholas might come in to say good night. - -"Well, that's all--everything," said Natasha. - -She got up quickly just as Nicholas entered, almost ran to the -door which was hidden by curtains, struck her head against it, and -rushed from the room with a moan either of pain or sorrow. - -Pierre gazed at the door through which she had disappeared and did -not understand why he suddenly felt all alone in the world. - -Princess Mary roused him from his abstraction by drawing his -attention to her nephew who had entered the room. - -At that moment of emotional tenderness young Nicholas' face, which -resembled his father's, affected Pierre so much that when he had -kissed the boy he got up quickly, took out his handkerchief, and -went to the window. He wished to take leave of Princess Mary, but -she would not let him go. - -"No, Natasha and I sometimes don't go to sleep till after two, so -please don't go. I will order supper. Go downstairs, we will come -immediately." - -Before Pierre left the room Princess Mary told him: "This is the -first time she has talked of him like that." - - - - - -CHAPTER XVII - - -Pierre was shown into the large, brightly lit dining room; a few -minutes later he heard footsteps and Princess Mary entered with -Natasha. Natasha was calm, though a severe and grave expression had -again settled on her face. They all three of them now experienced that -feeling of awkwardness which usually follows after a serious and -heartfelt talk. It is impossible to go back to the same -conversation, to talk of trifles is awkward, and yet the desire to -speak is there and silence seems like affectation. They went -silently to table. The footmen drew back the chairs and pushed them up -again. Pierre unfolded his cold table napkin and, resolving to break -the silence, looked at Natasha and at Princess Mary. They had -evidently both formed the same resolution; the eyes of both shone with -satisfaction and a confession that besides sorrow life also has joy. - -"Do you take vodka, Count?" asked Princess Mary, and those words -suddenly banished the shadows of the past. "Now tell us about -yourself," said she. "One hears such improbable wonders about you." - -"Yes," replied Pierre with the smile of mild irony now habitual to -him. "They even tell me wonders I myself never dreamed of! Mary -Abramovna invited me to her house and kept telling me what had -happened, or ought to have happened, to me. Stepan Stepanych also -instructed me how I ought to tell of my experiences. In general I have -noticed that it is very easy to be an interesting man (I am an -interesting man now); people invite me out and tell me all about -myself." - -Natasha smiled and was on the point of speaking. - -"We have been told," Princess Mary interrupted her, "that you lost -two millions in Moscow. Is that true?" - -"But I am three times as rich as before," returned Pierre. - -Though the position was now altered by his decision to pay his -wife's debts and to rebuild his houses, Pierre still maintained that -he had become three times as rich as before. - -"What I have certainly gained is freedom," he began seriously, but -did not continue, noticing that this theme was too egotistic. - -"And are you building?" - -"Yes. Savelich says I must!" - -"Tell me, you did not know of the countess' death when you decided -to remain in Moscow?" asked Princess Mary and immediately blushed, -noticing that her question, following his mention of freedom, ascribed -to his words a meaning he had perhaps not intended. - -"No," answered Pierre, evidently not considering awkward the meaning -Princess Mary had given to his words. "I heard of it in Orel and you -cannot imagine how it shocked me. We were not an exemplary couple," he -added quickly, glancing at Natasha and noticing on her face -curiosity as to how he would speak of his wife, "but her death shocked -me terribly. When two people quarrel they are always both in fault, -and one's own guilt suddenly becomes terribly serious when the other -is no longer alive. And then such a death... without friends and -without consolation! I am very, very sorry for her," he concluded, and -was pleased to notice a look of glad approval on Natasha's face. - -"Yes, and so you are once more an eligible bachelor," said -Princess Mary. - -Pierre suddenly flushed crimson and for a long time tried not to -look at Natasha. When he ventured to glance her way again her face was -cold, stern, and he fancied even contemptuous. - -"And did you really see and speak to Napoleon, as we have been -told?" said Princess Mary. - -Pierre laughed. - -"No, not once! Everybody seems to imagine that being taken -prisoner means being Napoleon's guest. Not only did I never see him -but I heard nothing about him--I was in much lower company!" - -Supper was over, and Pierre who at first declined to speak about his -captivity was gradually led on to do so. - -"But it's true that you remained in Moscow to kill Napoleon?" -Natasha asked with a slight smile. "I guessed it then when we met at -the Sukharev tower, do you remember?" - -Pierre admitted that it was true, and from that was gradually led by -Princess Mary's questions and especially by Natasha's into giving a -detailed account of his adventures. - -At first he spoke with the amused and mild irony now customary -with him toward everybody and especially toward himself, but when he -came to describe the horrors and sufferings he had witnessed he was -unconsciously carried away and began speaking with the suppressed -emotion of a man re-experiencing in recollection strong impressions he -has lived through. - -Princess Mary with a gentle smile looked now at Pierre and now at -Natasha. In the whole narrative she saw only Pierre and his -goodness. Natasha, leaning on her elbow, the expression of her face -constantly changing with the narrative, watched Pierre with an -attention that never wandered--evidently herself experiencing all that -he described. Not only her look, but her exclamations and the brief -questions she put, showed Pierre that she understood just what he -wished to convey. It was clear that she understood not only what he -said but also what he wished to, but could not, express in words. -The account Pierre gave of the incident with the child and the woman -for protecting whom he was arrested was this: "It was an awful -sight--children abandoned, some in the flames... One was snatched -out before my eyes... and there were women who had their things -snatched off and their earrings torn out..." he flushed and grew -confused. "Then a patrol arrived and all the men--all those who were - -not looting, that is--were arrested, and I among them." - -"I am sure you're not telling us everything; I am sure you did -something..." said Natasha and pausing added, "something fine?" - -Pierre continued. When he spoke of the execution he wanted to pass -over the horrible details, but Natasha insisted that he should not -omit anything. - -Pierre began to tell about Karataev, but paused. By this time he had -risen from the table and was pacing the room, Natasha following him -with her eyes. Then he added: - -"No, you can't understand what I learned from that illiterate man- -that simple fellow." - -"Yes, yes, go on!" said Natasha. "Where is he?" - -"They killed him almost before my eyes." - -And Pierre, his voice trembling continually, went on to tell of -the last days of their retreat, of Karataev's illness and his death. - -He told of his adventures as he had never yet recalled them. He now, -as it were, saw a new meaning in all he had gone through. Now that -he was telling it all to Natasha he experienced that pleasure which -a man has when women listen to him--not clever women who when -listening either try to remember what they hear to enrich their -minds and when opportunity offers to retell it, or who wish to adopt -it to some thought of their own and promptly contribute their own -clever comments prepared in their little mental workshop--but the -pleasure given by real women gifted with a capacity to select and -absorb the very best a man shows of himself. Natasha without knowing -it was all attention: she did not lose a word, no single quiver in -Pierre's voice, no look, no twitch of a muscle in his face, nor a -single gesture. She caught the unfinished word in its flight and -took it straight into her open heart, divining the secret meaning of -all Pierre's mental travail. - -Princess Mary understood his story and sympathized with him, but she -now saw something else that absorbed all her attention. She saw the -possibility of love and happiness between Natasha and Pierre, and -the first thought of this filled her heart with gladness. - -It was three o'clock in the morning. The footmen came in with sad -and stern faces to change the candles, but no one noticed them. - -Pierre finished his story. Natasha continued to look at him intently -with bright, attentive, and animated eyes, as if trying to -understand something more which he had perhaps left untold. Pierre -in shamefaced and happy confusion glanced occasionally at her, and -tried to think what to say next to introduce a fresh subject. Princess -Mary was silent. It occurred to none of them that it was three o'clock -and time to go to bed. - -"People speak of misfortunes and sufferings," remarked Pierre, -"but if at this moment I were asked: 'Would you rather be what you -were before you were taken prisoner, or go through all this again?' -then for heaven's sake let me again have captivity and horseflesh! -We imagine that when we are thrown out of our usual ruts all is -lost, but it is only then that what is new and good begins. While -there is life there is happiness. There is much, much before us. I say -this to you," he added, turning to Natasha. - -"Yes, yes," she said, answering something quite different. "I too -should wish nothing but to relive it all from the beginning." - -Pierre looked intently at her. - -"Yes, and nothing more." said Natasha. - -"It's not true, not true!" cried Pierre. "I am not to blame for -being alive and wishing to live--nor you either." - -Suddenly Natasha bent her head, covered her face with her hands, and -began to cry. - -"What is it, Natasha?" said Princess Mary. - -"Nothing, nothing." She smiled at Pierre through her tears. "Good -night! It is time for bed." - -Pierre rose and took his leave. - - -Princess Mary and Natasha met as usual in the bedroom. They talked -of what Pierre had told them. Princess Mary did not express her -opinion of Pierre nor did Natasha speak of him. - -"Well, good night, Mary!" said Natasha. "Do you know, I am often -afraid that by not speaking of him" (she meant Prince Andrew) "for -fear of not doing justice to our feelings, we forget him." - -Princess Mary sighed deeply and thereby acknowledged the justice -of Natasha's remark, but she did not express agreement in words. - -"Is it possible to forget?" said she. - -"It did me so much good to tell all about it today. It was hard -and painful, but good, very good!" said Natasha. "I am sure he -really loved him. That is why I told him... Was it all right?" she -added, suddenly blushing. - -"To tell Pierre? Oh, yes. What a splendid man he is!" said -Princess Mary. - -"Do you know, Mary..." Natasha suddenly said with a mischievous -smile such as Princess Mary had not seen on her face for a long -time, "he has somehow grown so clean, smooth, and fresh--as if he -had just come out of a Russian bath; do you understand? Out of a moral -bath. Isn't it true?" - -"Yes," replied Princess Mary. "He has greatly improved." - -"With a short coat and his hair cropped; just as if, well, just as -if he had come straight from the bath... Papa used to..." - -"I understand why he" (Prince Andrew) "liked no one so much as him," -said Princess Mary. - -"Yes, and yet he is quite different. They say men are friends when -they are quite different. That must be true. Really he is quite unlike -him--in everything." - -"Yes, but he's wonderful." - -"Well, good night," said Natasha. - -And the same mischievous smile lingered for a long time on her -face as if it had been forgotten there. - - - - -CHAPTER XVIII - - -It was a long time before Pierre could fall asleep that night. He -paced up and down his room, now turning his thoughts on a difficult -problem and frowning, now suddenly shrugging his shoulders and -wincing, and now smiling happily. - -He was thinking of Prince Andrew, of Natasha, and of their love, -at one moment jealous of her past, then reproaching himself for that -feeling. It was already six in the morning and he still paced up and -down the room. - -"Well, what's to be done if it cannot be avoided? What's to be done? -Evidently it has to be so," said he to himself, and hastily undressing -he got into bed, happy and agitated but free from hesitation or -indecision. - -"Strange and impossible as such happiness seems, I must do -everything that she and I may be man and wife," he told himself. - -A few days previously Pierre had decided to go to Petersburg on -the Friday. When he awoke on the Thursday, Savelich came to ask him -about packing for the journey. - -"What, to Petersburg? What is Petersburg? Who is there in -Petersburg?" he asked involuntarily, though only to himself. "Oh, yes, -long ago before this happened I did for some reason mean to go to -Petersburg," he reflected. "Why? But perhaps I shall go. What a good -fellow he is and how attentive, and how he remembers everything," he -thought, looking at Savelich's old face, "and what a pleasant smile he -has!" - -"Well, Savelich, do you still not wish to accept your freedom?" -Pierre asked him. - -"What's the good of freedom to me, your excellency? We lived under -the late count--the kingdom of heaven be his!--and we have lived under -you too, without ever being wronged." - -"And your children?" - -"The children will live just the same. With such masters one can -live." - -"But what about my heirs?" said Pierre. "Supposing I suddenly -marry... it might happen," he added with an involuntary smile. - -"If I may take the liberty, your excellency, it would be a good -thing." - -"How easy he thinks it," thought Pierre. "He doesn't know how -terrible it is and how dangerous. Too soon or too late... it is -terrible!" - -"So what are your orders? Are you starting tomorrow?" asked -Savelich. - -"No, I'll put it off for a bit. I'll tell you later. You must -forgive the trouble I have put you to," said Pierre, and seeing -Savelich smile, he thought: "But how strange it is that he should -not know that now there is no Petersburg for me, and that that must be -settled first of all! But probably he knows it well enough and is only -pretending. Shall I have a talk with him and see what he thinks?" -Pierre reflected. "No, another time." - -At breakfast Pierre told the princess, his cousin, that he had -been to see Princess Mary the day before and had there met--"Whom do -you think? Natasha Rostova!" - -The princess seemed to see nothing more extraordinary in that than -if he had seen Anna Semenovna. - -"Do you know her?" asked Pierre. - -"I have seen the princess," she replied. "I heard that they were -arranging a match for her with young Rostov. It would be a very good -thing for the Rostovs, they are said to be utterly ruined." - -"No; I mean do you know Natasha Rostova?" - -"I heard about that affair of hers at the time. It was a great -pity." - -"No, she either doesn't understand or is pretending," thought -Pierre. "Better not say anything to her either." - -The princess too had prepared provisions for Pierre's journey. - -"How kind they all are," thought Pierre. "What is surprising is that -they should trouble about these things now when it can no longer be of -interest to them. And all for me!" - -On the same day the Chief of Police came to Pierre, inviting him -to send a representative to the Faceted Palace to recover things -that were to be returned to their owners that day. - -"And this man too," thought Pierre, looking into the face of the -Chief of Police. "What a fine, good-looking officer and how kind. -Fancy bothering about such trifies now! And they actually say he is -not honest and takes bribes. What nonsense! Besides, why shouldn't -he take bribes? That's the way he was brought up, and everybody does -it. But what a kind, pleasant face and how he smiles as he looks at -me." - -Pierre went to Princess Mary's to dinner. - -As he drove through the streets past the houses that had been burned -down, he was surprised by the beauty of those ruins. The -picturesqueness of the chimney stacks and tumble-down walls of the -burned-out quarters of the town, stretching out and concealing one -another, reminded him of the Rhine and the Colosseum. The cabmen he -met and their passengers, the carpenters cutting the timber for new -houses with axes, the women hawkers, and the shopkeepers, all looked -at him with cheerful beaming eyes that seemed to say: "Ah, there he -is! Let's see what will come of it!" - -At the entrance to Princess Mary's house Pierre felt doubtful -whether he had really been there the night before and really seen -Natasha and talked to her. "Perhaps I imagined it; perhaps I shall -go in and find no one there." But he had hardly entered the room -before he felt her presence with his whole being by the loss of his -sense of freedom. She was in the same black dress with soft folds -and her hair was done the same way as the day before, yet she was -quite different. Had she been like this when he entered the day before -he could not for a moment have failed to recognize her. - -She was as he had known her almost as a child and later on as Prince -Andrew's fiancee. A bright questioning light shone in her eyes, and on -her face was a friendly and strangely roguish expression. - -Pierre dined with them and would have spent the whole evening there, -but Princess Mary was going to vespers and Pierre left the house -with her. - -Next day he came early, dined, and stayed the whole evening. -Though Princess Mary and Natasha were evidently glad to see their -visitor and though all Pierre's interest was now centered in that -house, by the evening they had talked over everything and the -conversation passed from one trivial topic to another and repeatedly -broke off. He stayed so long that Princess Mary and Natasha -exchanged glances, evidently wondering when he would go. Pierre -noticed this but could not go. He felt uneasy and embarrassed, but sat -on because he simply could not get up and take his leave. - -Princess Mary, foreseeing no end to this, rose first, and -complaining of a headache began to say good night. - -"So you are going to Petersburg tomorrow?" she asked. - -"No, I am not going," Pierre replied hastily, in a surprised tone -and as though offended. "Yes... no... to Petersburg? Tomorrow--but I -won't say good-by yet. I will call round in case you have any -commissions for me," said he, standing before Princess Mary and -turning red, but not taking his departure. - -Natasha gave him her hand and went out. Princess Mary on the other -hand instead of going away sank into an armchair, and looked sternly -and intently at him with her deep, radiant eyes. The weariness she had -plainly shown before had now quite passed off. With a deep and -long-drawn sigh she seemed to be prepared for a lengthy talk. - -When Natasha left the room Pierre's confusion and awkwardness -immediately vanished and were replaced by eager excitement. He quickly -moved an armchair toward Princess Mary. - -"Yes, I wanted to tell you," said he, answering her look as if she -had spoken. "Princess, help me! What am I to do? Can I hope? Princess, -my dear friend, listen! I know it all. I know I am not worthy of -her, I know it's impossible to speak of it now. But I want to be a -brother to her. No, not that, I don't, I can't..." - -He paused and rubbed his face and eyes with his hands. - -"Well," he went on with an evident effort at self-control and -coherence. "I don't know when I began to love her, but I have loved -her and her alone all my life, and I love her so that I cannot imagine -life without her. I cannot propose to her at present, but the -thought that perhaps she might someday be my wife and that I may be -missing that possibility... that possibility... is terrible. Tell -me, can I hope? Tell me what I am to do, dear princess!" he added -after a pause, and touched her hand as she did not reply. - -"I am thinking of what you have told me," answered Princess Mary. -"This is what I will say. You are right that to speak to her of love -at present..." - -Princess Mary stopped. She was going to say that to speak of love -was impossible, but she stopped because she had seen by the sudden -change in Natasha two days before that she would not only not be -hurt if Pierre spoke of his love, but that it was the very thing she -wished for. - -"To speak to her now wouldn't do," said the princess all the same. - -"But what am I to do?" - -"Leave it to me," said Princess Mary. "I know..." - -Pierre was looking into Princess Mary's eyes. - -"Well?... Well?..." he said. - -"I know that she loves... will love you," Princess Mary corrected -herself. - -Before her words were out, Pierre had sprung up and with a -frightened expression seized Princess Mary's hand. - -"What makes you think so? You think I may hope? You think...?" - -"Yes, I think so," said Princess Mary with a smile. "Write to her -parents, and leave it to me. I will tell her when I can. I wish it -to happen and my heart tells me it will." - -"No, it cannot be! How happy I am! But it can't be.... How happy I -am! No, it can't be!" Pierre kept saying as he kissed Princess -Mary's hands. - -"Go to Petersburg, that will be best. And I will write to you," -she said. - -"To Petersburg? Go there? Very well, I'll go. But I may come again -tomorrow?" - -Next day Pierre came to say good-by. Natasha was less animated -than she had been the day before; but that day as he looked at her -Pierre sometimes felt as if he was vanishing and that neither he nor -she existed any longer, that nothing existed but happiness. "Is it -possible? No, it can't be," he told himself at every look, gesture, -and word that filled his soul with joy. - -When on saying good-by he took her thin, slender hand, he could -not help holding it a little longer in his own. - -"Is it possible that this hand, that face, those eyes, all this -treasure of feminine charm so strange to me now, is it possible that -it will one day be mine forever, as familiar to me as I am to -myself?... No, that's impossible!..." - -"Good-by, Count," she said aloud. "I shall look forward very much to -your return," she added in a whisper. - -And these simple words, her look, and the expression on her face -which accompanied them, formed for two months the subject of -inexhaustible memories, interpretations, and happy meditations for -Pierre. "'I shall look forward very much to your return....' Yes, yes, -how did she say it? Yes, 'I shall look forward very much to your -return.' Oh, how happy I am! What is happening to me? How happy I am!" -said Pierre to himself. - - - - - -CHAPTER XIX - - -There was nothing in Pierre's soul now at all like what had troubled -it during his courtship of Helene. - -He did not repeat to himself with a sickening feeling of shame the -words he had spoken, or say: "Oh, why did I not say that?" and, -"Whatever made me say 'Je vous aime'?" On the contrary, he now -repeated in imagination every word that he or Natasha had spoken and -pictured every detail of her face and smile, and did not wish to -diminish or add anything, but only to repeat it again and again. There -was now not a shadow of doubt in his mind as to whether what he had -undertaken was right or wrong. Only one terrible doubt sometimes -crossed his mind: "Wasn't it all a dream? Isn't Princess Mary -mistaken? Am I not too conceited and self-confident? I believe all -this--and suddenly Princess Mary will tell her, and she will be sure -to smile and say: 'How strange! He must be deluding himself. Doesn't -he know that he is a man, just a man, while I...? I am something -altogether different and higher.'" - -That was the only doubt often troubling Pierre. He did not now -make any plans. The happiness before him appeared so inconceivable -that if only he could attain it, it would be the end of all things. -Everything ended with that. - -A joyful, unexpected frenzy, of which he had thought himself -incapable, possessed him. The whole meaning of life--not for him alone -but for the whole world--seemed to him centered in his love and the -possibility of being loved by her. At times everybody seemed to him to -be occupied with one thing only--his future happiness. Sometimes it -seemed to him that other people were all as pleased as he was -himself and merely tried to hide that pleasure by pretending to be -busy with other interests. In every word and gesture he saw -allusions to his happiness. He often surprised those he met by his -significantly happy looks and smiles which seemed to express a -secret understanding between him and them. And when he realized that -people might not be aware of his happiness, he pitied them with his -whole heart and felt a desire somehow to explain to them that all that -occupied them was a mere frivolous trifle unworthy of attention. - -When it was suggested to him that he should enter the civil service, -or when the war or any general political affairs were discussed on the -assumption that everybody's welfare depended on this or that issue -of events, he would listen with a mild and pitying smile and -surprise people by his strange comments. But at this time he saw -everybody--both those who, as he imagined, understood the real meaning -of life (that is, what he was feeling) and those unfortunates who -evidently did not understand it--in the bright light of the emotion -that shone within himself, and at once without any effort saw in -everyone he met everything that was good and worthy of being loved. - -When dealing with the affairs and papers of his dead wife, her -memory aroused in him no feeling but pity that she had not known the -bliss he now knew. Prince Vasili, who having obtained a new post and -some fresh decorations was particularly proud at this time, seemed -to him a pathetic, kindly old man much to be pitied. - -Often in afterlife Pierre recalled this period of blissful insanity. -All the views he formed of men and circumstances at this time remained -true for him always. He not only did not renounce them subsequently, -but when he was in doubt or inwardly at variance, he referred to the -views he had held at this time of his madness and they always proved -correct. - -"I may have appeared strange and queer then," he thought, "but I was -not so mad as I seemed. On the contrary I was then wiser and had -more insight than at any other time, and understood all that is -worth understanding in life, because... because I was happy." - -Pierre's insanity consisted in not waiting, as he used to do, to -discover personal attributes which he termed "good qualities" in -people before loving them; his heart was now overflowing with love, -and by loving people without cause he discovered indubitable causes -for loving them. - - - - - -CHAPTER XX - - -After Pierre's departure that first evening, when Natasha had said -to Princess Mary with a gaily mocking smile: "He looks just, yes, just -as if he had come out of a Russian bath--in a short coat and with -his hair cropped," something hidden and unknown to herself, but -irrepressible, awoke in Natasha's soul. - -Everything: her face, walk, look, and voice, was suddenly altered. -To her own surprise a power of life and hope of happiness rose to -the surface and demanded satisfaction. From that evening she seemed to -have forgotten all that had happened to her. She no longer -complained of her position, did not say a word about the past, and -no longer feared to make happy plans for the future. She spoke -little of Pierre, but when Princess Mary mentioned him a -long-extinguished light once more kindled in her eyes and her lips -curved with a strange smile. - -The change that took place in Natasha at first surprised Princess -Mary; but when she understood its meaning it grieved her. "Can she -have loved my brother so little as to be able to forget him so -soon?" she thought when she reflected on the change. But when she -was with Natasha she was not vexed with her and did not reproach -her. The reawakened power of life that had seized Natasha was so -evidently irrepressible and unexpected by her that in her presence -Princess Mary felt that she had no right to reproach her even in her -heart. - - Natasha gave herself up so fully and frankly to this new feeling -that she did not try to hide the fact that she was no longer sad, -but bright and cheerful. - -When Princess Mary returned to her room after her nocturnal talk -with Pierre, Natasha met her on the threshold. - -"He has spoken? Yes? He has spoken?" she repeated. - -And a joyful yet pathetic expression which seemed to beg forgiveness -for her joy settled on Natasha's face. - -"I wanted to listen at the door, but I knew you would tell me." - -Understandable and touching as the look with which Natasha gazed -at her seemed to Princess Mary, and sorry as she was to see her -agitation, these words pained her for a moment. She remembered her -brother and his love. - -"But what's to be done? She can't help it," thought the princess. - -And with a sad and rather stern look she told Natasha all that -Pierre had said. On hearing that he was going to Petersburg Natasha -was astounded. - -"To Petersburg!" she repeated as if unable to understand. - -But noticing the grieved expression on Princess Mary's face she -guessed the reason of that sadness and suddenly began to cry. - -"Mary," said she, "tell me what I should do! I am afraid of being -bad. Whatever you tell me, I will do. Tell me...." - -"You love him?" - -"Yes," whispered Natasha. - -"Then why are you crying? I am happy for your sake," said Princess -Mary, who because of those tears quite forgave Natasha's joy. - -"It won't be just yet--someday. Think what fun it will be when I -am his wife and you marry Nicholas!" - -"Natasha, I have asked you not to speak of that. Let us talk about -you." - -They were silent awhile. - -"But why go to Petersburg?" Natasha suddenly asked, and hastily -replied to her own question. "But no, no, he must... Yes, Mary, He -must...." - - - - - - -FIRST EPILOGUE: 1813 --20 - - - - - -CHAPTER I - - -Seven years had passed. The storm-tossed sea of European history had -subsided within its shores and seemed to have become calm. But the -mysterious forces that move humanity (mysterious because the laws of -their motion are unknown to us) continued to operate. - -Though the surface of the sea of history seemed motionless, the -movement of humanity went on as unceasingly as the flow of time. -Various groups of people formed and dissolved, the coming formation -and dissolution of kingdoms and displacement of peoples was in -course of preparation. - -The sea of history was not driven spasmodically from shore to -shore as previously. It was seething in its depths. Historic figures -were not borne by the waves from one shore to another as before. -They now seemed to rotate on one spot. The historical figures at the -head of armies, who formerly reflected the movement of the masses by -ordering wars, campaigns, and battles, now reflected the restless -movement by political and diplomatic combinations, laws, and treaties. - -The historians call this activity of the historical figures "the -reaction." - -In dealing with this period they sternly condemn the historical -personages who, in their opinion, caused what they describe as the -reaction. All the well-known people of that period, from Alexander and -Napoleon to Madame de Stael, Photius, Schelling, Fichte, -Chateaubriand, and the rest, pass before their stern judgment seat and -are acquitted or condemned according to whether they conduced to -progress or to reaction. - -According to their accounts a reaction took place at that time in -Russia also, and the chief culprit was Alexander I, the same man who -according to them was the chief cause of the liberal movement at the -commencement of his reign, being the savior of Russia. - -There is no one in Russian literature now, from schoolboy essayist -to learned historian, who does not throw his little stone at Alexander -for things he did wrong at this period of his reign. - -"He ought to have acted in this way and in that way. In this case he -did well and in that case badly. He behaved admirably at the beginning -of his reign and during 1812, but acted badly by giving a constitution -to Poland, forming the Holy Alliance, entrusting power to Arakcheev, -favoring Golitsyn and mysticism, and afterwards Shishkov and -Photius. He also acted badly by concerning himself with the active -army and disbanding the Semenov regiment." - -It would take a dozen pages to enumerate all the reproaches the -historians address to him, based on their knowledge of what is good -for humanity. - -What do these reproaches mean? - -Do not the very actions for which the historians praise Alexander -I (the liberal attempts at the beginning of his reign, his struggle -with Napoleon, the firmness he displayed in 1812 and the campaign of -1813) flow from the same sources--the circumstances of his birth, -education, and life--that made his personality what it was and from -which the actions for which \ No newline at end of file diff --git a/node_modules/readline/test/fixtures/file-in-win1251.txt b/node_modules/readline/test/fixtures/file-in-win1251.txt deleted file mode 100644 index 9094c9c2c..000000000 --- a/node_modules/readline/test/fixtures/file-in-win1251.txt +++ /dev/null @@ -1,14 +0,0 @@ -file n (folder for keeping information) ����� � -I have a file that I keep all my telephone bills in. -� ���� ���� �����, � ������� � ����� ��� ����� �� �������. -file n (tool) ��������� � -He used a file to smooth the corner of the wood. -�� �������� ����������� ���� ������. -file n (computer file) ���� � -Can you send me the file as an attachment in an email? -������ ������� ��� ���� ���� ��� ���������� � ������������ ������? -I file all my telephone bills together. -� �������� ��� ����� �� ������������� ������. -file vtr (smooth with a file) ���������, �������� ����� + ��� -He filed the wood. -�� �������� ������. \ No newline at end of file diff --git a/node_modules/readline/test/fixtures/nmbr.txt b/node_modules/readline/test/fixtures/nmbr.txt deleted file mode 100644 index 0bce9e3a3..000000000 --- a/node_modules/readline/test/fixtures/nmbr.txt +++ /dev/null @@ -1,7 +0,0 @@ -1 -2 -3 -4 -5 -6 -7 \ No newline at end of file diff --git a/node_modules/readline/test/test_readline.js b/node_modules/readline/test/test_readline.js deleted file mode 100644 index 807cf7225..000000000 --- a/node_modules/readline/test/test_readline.js +++ /dev/null @@ -1,138 +0,0 @@ -var fs = require('fs'); -var readLine = require('../readline.js'); -var test = require("tap").test; - -test("test reading lines",function(t){ - console.error("reading large file line by line asserts may take a while"); - var rl = readLine('./fixtures/afile.txt'); - rl.on("line", function (line,linecount){ - t.ok(null !== line && undefined !== line); - }); - rl.on("end",function (){ - t.end(); - }); - -}); - -test("numbers", function (t){ - var rl = readLine('./fixtures/nmbr.txt'); - var answer = 28; - var i=0; - rl.on("line", function (line){ - var num = Number(line); - console.error(num); - i+=num; - - }); - rl.on("end", function (){ - console.error(i,answer); - t.ok(answer === i, "answered"); - t.end(); - }); -}); - - -test("errors", function (t){ - var rl = readLine("./Idontexist"); - rl.on('error', function (e){ - t.ok(e); - t.end(); - }); - rl.on('end', function (){ - t.end(); - }); - rl.on('close', function(){ - t.end(); - }); -}); - - -test("line count", function(t){ - var rl = readLine('./fixtures/nmbr.txt'); - var expect = 7; - var actual = 0; - rl.on("line", function (line, ln){ - console.log("line",line,ln); - actual=ln; - }); - rl.on("end", function (){ - t.ok(actual === expect,"line count is correct"); - t.end(); - }); -}); - -test("byte count after first line", function(t){ - var rl = readLine('./fixtures/nmbr.txt'); - var actual = 0; - var expect; - rl.on("line", function (line, ln, byteCount){ - if (expect === undefined) { - expect = line.length; - console.log("byte count",byteCount); - actual=byteCount; - - t.ok(actual === expect,"byte count is correct"); - t.end(); - } - }); -}); - -test("byte count", function(t){ - var rl = readLine('./fixtures/nmbr.txt'); - var expect = fs.statSync('./fixtures/nmbr.txt').size; - var actual = 0; - rl.on("line", function (line, ln, byteCount){ - console.log("byte count",byteCount); - actual=byteCount; - }); - rl.on("end", function (){ - t.ok(actual === expect,"byte count is correct"); - t.end(); - }); -}); - -test("processing error passed on", function(t){ - var rl = readLine('./fixtures/nmbr.txt'); - var lastError; - var lineCalls = 0; - - rl.on("line", function (line, ln, byteCount){ - lineCalls++; - if (ln === 7) { - throw new Error('fake error'); - } - }); - rl.on("error", function (err){ - if (!lastError) { - lastError = err; - } - }); - - rl.on("end", function (){ - t.ok(lastError.message === 'fake error','error is passed on'); - t.ok(lineCalls === 7, 'line count ok'); - t.end(); - }); -}); - -test("test ascii file reading",function(t){ - var iconv = require('iconv-lite'); - var testFileValidationKeywords = { - 1: 'папка', - 3: 'телефон', - 11: 'электричество', - 14: 'дерево' - }; - - var rl = readLine('./fixtures/file-in-win1251.txt', { - retainBuffer: true - }); - rl.on("line", function (data,linecount){ - var line = iconv.decode(data, 'win1251'); - t.ok(!testFileValidationKeywords[linecount] || line.indexOf(testFileValidationKeywords[linecount]) > -1); - }); - rl.on("end",function (){ - t.end(); - }); - -}); \ No newline at end of file diff --git a/node_modules/set-function-length/.eslintrc b/node_modules/set-function-length/.eslintrc new file mode 100644 index 000000000..7cff50717 --- /dev/null +++ b/node_modules/set-function-length/.eslintrc @@ -0,0 +1,27 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": "off", + "new-cap": ["error", { + "capIsNewExceptions": [ + "GetIntrinsic" + ], + }], + "no-extra-parens": "off", + }, + + "overrides": [ + { + "files": ["test/**/*.js"], + "rules": { + "id-length": "off", + "max-lines-per-function": "off", + "multiline-comment-style": "off", + "no-empty-function": "off", + }, + }, + ], +} diff --git a/node_modules/set-function-length/.github/FUNDING.yml b/node_modules/set-function-length/.github/FUNDING.yml new file mode 100644 index 000000000..92feb6f9b --- /dev/null +++ b/node_modules/set-function-length/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/set-function-name +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/set-function-length/.nycrc b/node_modules/set-function-length/.nycrc new file mode 100644 index 000000000..1826526e0 --- /dev/null +++ b/node_modules/set-function-length/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/set-function-length/CHANGELOG.md b/node_modules/set-function-length/CHANGELOG.md new file mode 100644 index 000000000..bac439d87 --- /dev/null +++ b/node_modules/set-function-length/CHANGELOG.md @@ -0,0 +1,70 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.2.2](https://github.com/ljharb/set-function-length/compare/v1.2.1...v1.2.2) - 2024-03-09 + +### Commits + +- [types] use shared config [`027032f`](https://github.com/ljharb/set-function-length/commit/027032fe9cc439644a07248ea6a8d813fcc767cb) +- [actions] remove redundant finisher; use reusable workflow [`1fd4fb1`](https://github.com/ljharb/set-function-length/commit/1fd4fb1c58bd5170f0dcff7e320077c0aa2ffdeb) +- [types] use a handwritten d.ts file instead of emit [`01b9761`](https://github.com/ljharb/set-function-length/commit/01b9761742c95e1118e8c2d153ce2ae43d9731aa) +- [Deps] update `define-data-property`, `get-intrinsic`, `has-property-descriptors` [`bee8eaf`](https://github.com/ljharb/set-function-length/commit/bee8eaf7749f325357ade85cffeaeef679e513d4) +- [Dev Deps] update `call-bind`, `tape` [`5dae579`](https://github.com/ljharb/set-function-length/commit/5dae579fdc3aab91b14ebb58f9c19ee3f509d434) +- [Tests] use `@arethetypeswrong/cli` [`7e22425`](https://github.com/ljharb/set-function-length/commit/7e22425d15957fd3d6da0b6bca4afc0c8d255d2d) + +## [v1.2.1](https://github.com/ljharb/set-function-length/compare/v1.2.0...v1.2.1) - 2024-02-06 + +### Commits + +- [Dev Deps] update `call-bind`, `tape`, `typescript` [`d9a4601`](https://github.com/ljharb/set-function-length/commit/d9a460199c4c1fa37da9ebe055e2c884128f0738) +- [Deps] update `define-data-property`, `get-intrinsic` [`38d39ae`](https://github.com/ljharb/set-function-length/commit/38d39aed13a757ed36211d5b0437b88485090c6b) +- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`b4bfe5a`](https://github.com/ljharb/set-function-length/commit/b4bfe5ae0953b906d55b85f867eca5e7f673ebf4) + +## [v1.2.0](https://github.com/ljharb/set-function-length/compare/v1.1.1...v1.2.0) - 2024-01-14 + +### Commits + +- [New] add types [`f6d9088`](https://github.com/ljharb/set-function-length/commit/f6d9088b9283a3112b21c6776e8bef6d1f30558a) +- [Fix] ensure `env` properties are always booleans [`0c42f84`](https://github.com/ljharb/set-function-length/commit/0c42f84979086389b3229e1b4272697fd352275a) +- [Dev Deps] update `aud`, `call-bind`, `npmignore`, `tape` [`2b75f75`](https://github.com/ljharb/set-function-length/commit/2b75f75468093a4bb8ce8ca989b2edd2e80d95d1) +- [Deps] update `get-intrinsic`, `has-property-descriptors` [`19bf0fc`](https://github.com/ljharb/set-function-length/commit/19bf0fc4ffaa5ad425acbfa150516be9f3b6263a) +- [meta] add `sideEffects` flag [`8bb9b78`](https://github.com/ljharb/set-function-length/commit/8bb9b78c11c621123f725c9470222f43466c01d0) + +## [v1.1.1](https://github.com/ljharb/set-function-length/compare/v1.1.0...v1.1.1) - 2023-10-19 + +### Fixed + +- [Fix] move `define-data-property` to runtime deps [`#2`](https://github.com/ljharb/set-function-length/issues/2) + +### Commits + +- [Dev Deps] update `object-inspect`; add missing `call-bind` [`5aecf79`](https://github.com/ljharb/set-function-length/commit/5aecf79e7d6400957a5d9bd9ac20d4528908ca18) + +## [v1.1.0](https://github.com/ljharb/set-function-length/compare/v1.0.1...v1.1.0) - 2023-10-13 + +### Commits + +- [New] add `env` entry point [`475c87a`](https://github.com/ljharb/set-function-length/commit/475c87aa2f59b700aaed589d980624ec596acdcb) +- [Tests] add coverage with `nyc` [`14f0bf8`](https://github.com/ljharb/set-function-length/commit/14f0bf8c145ae60bf14a026420a06bb7be132c36) +- [eslint] fix linting failure [`fb516f9`](https://github.com/ljharb/set-function-length/commit/fb516f93c664057138c53559ef63c8622a093335) +- [Deps] update `define-data-property` [`d727e7c`](https://github.com/ljharb/set-function-length/commit/d727e7c6c9a40d7bf26797694e500ea68741feea) + +## [v1.0.1](https://github.com/ljharb/set-function-length/compare/v1.0.0...v1.0.1) - 2023-10-12 + +### Commits + +- [Refactor] use `get-intrinsic`, since it‘s in the dep graph anyways [`278a954`](https://github.com/ljharb/set-function-length/commit/278a954a06cd849051c569ff7aee56df6798933e) +- [meta] add `exports` [`72acfe5`](https://github.com/ljharb/set-function-length/commit/72acfe5a0310071fb205a72caba5ecbab24336a0) + +## v1.0.0 - 2023-10-12 + +### Commits + +- Initial implementation, tests, readme [`fce14e1`](https://github.com/ljharb/set-function-length/commit/fce14e17586460e4f294405173be72b6ffdf7e5f) +- Initial commit [`ca7ba85`](https://github.com/ljharb/set-function-length/commit/ca7ba857c7c283f9d26e21f14e71cd388f2cb722) +- npm init [`6a7e493`](https://github.com/ljharb/set-function-length/commit/6a7e493927736cebcaf5c1a84e69b8e6b7b744d8) +- Only apps should have lockfiles [`d2bf6c4`](https://github.com/ljharb/set-function-length/commit/d2bf6c43de8a51b02a0aa53e8d62cb50c4a2b0da) diff --git a/node_modules/set-function-length/LICENSE b/node_modules/set-function-length/LICENSE new file mode 100644 index 000000000..031492907 --- /dev/null +++ b/node_modules/set-function-length/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Jordan Harband and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/set-function-length/README.md b/node_modules/set-function-length/README.md new file mode 100644 index 000000000..15e3ac4b1 --- /dev/null +++ b/node_modules/set-function-length/README.md @@ -0,0 +1,56 @@ +# set-function-length [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Set a function’s length. + +Arguments: + - `fn`: the function + - `length`: the new length. Must be an integer between 0 and 2**32. + - `loose`: Optional. If true, and the length fails to be set, do not throw. Default false. + +Returns `fn`. + +## Usage + +```javascript +var setFunctionLength = require('set-function-length'); +var assert = require('assert'); + +function zero() {} +function one(_) {} +function two(_, __) {} + +assert.equal(zero.length, 0); +assert.equal(one.length, 1); +assert.equal(two.length, 2); + +assert.equal(setFunctionLength(zero, 10), zero); +assert.equal(setFunctionLength(one, 11), one); +assert.equal(setFunctionLength(two, 12), two); + +assert.equal(zero.length, 10); +assert.equal(one.length, 11); +assert.equal(two.length, 12); +``` + +[package-url]: https://npmjs.org/package/set-function-length +[npm-version-svg]: https://versionbadg.es/ljharb/set-function-length.svg +[deps-svg]: https://david-dm.org/ljharb/set-function-length.svg +[deps-url]: https://david-dm.org/ljharb/set-function-length +[dev-deps-svg]: https://david-dm.org/ljharb/set-function-length/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/set-function-length#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/set-function-length.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/set-function-length.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/set-function-length.svg +[downloads-url]: https://npm-stat.com/charts.html?package=set-function-length +[codecov-image]: https://codecov.io/gh/ljharb/set-function-length/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/set-function-length/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/set-function-length +[actions-url]: https://github.com/ljharb/set-function-length/actions diff --git a/node_modules/set-function-length/env.d.ts b/node_modules/set-function-length/env.d.ts new file mode 100644 index 000000000..970ea535b --- /dev/null +++ b/node_modules/set-function-length/env.d.ts @@ -0,0 +1,9 @@ +declare const env: { + __proto__: null, + boundFnsHaveConfigurableLengths: boolean; + boundFnsHaveWritableLengths: boolean; + functionsHaveConfigurableLengths: boolean; + functionsHaveWritableLengths: boolean; +}; + +export = env; \ No newline at end of file diff --git a/node_modules/set-function-length/env.js b/node_modules/set-function-length/env.js new file mode 100644 index 000000000..d9b0a2997 --- /dev/null +++ b/node_modules/set-function-length/env.js @@ -0,0 +1,25 @@ +'use strict'; + +var gOPD = require('gopd'); +var bind = require('function-bind'); + +var unbound = gOPD && gOPD(function () {}, 'length'); +// @ts-expect-error ts(2555) TS is overly strict with .call +var bound = gOPD && gOPD(bind.call(function () {}), 'length'); + +var functionsHaveConfigurableLengths = !!(unbound && unbound.configurable); + +var functionsHaveWritableLengths = !!(unbound && unbound.writable); + +var boundFnsHaveConfigurableLengths = !!(bound && bound.configurable); + +var boundFnsHaveWritableLengths = !!(bound && bound.writable); + +/** @type {import('./env')} */ +module.exports = { + __proto__: null, + boundFnsHaveConfigurableLengths: boundFnsHaveConfigurableLengths, + boundFnsHaveWritableLengths: boundFnsHaveWritableLengths, + functionsHaveConfigurableLengths: functionsHaveConfigurableLengths, + functionsHaveWritableLengths: functionsHaveWritableLengths +}; diff --git a/node_modules/set-function-length/index.d.ts b/node_modules/set-function-length/index.d.ts new file mode 100644 index 000000000..0451ecd39 --- /dev/null +++ b/node_modules/set-function-length/index.d.ts @@ -0,0 +1,7 @@ +declare namespace setFunctionLength { + type Func = (...args: unknown[]) => unknown; +} + +declare function setFunctionLength(fn: T, length: number, loose?: boolean): T; + +export = setFunctionLength; \ No newline at end of file diff --git a/node_modules/set-function-length/index.js b/node_modules/set-function-length/index.js new file mode 100644 index 000000000..14ce74dae --- /dev/null +++ b/node_modules/set-function-length/index.js @@ -0,0 +1,42 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var define = require('define-data-property'); +var hasDescriptors = require('has-property-descriptors')(); +var gOPD = require('gopd'); + +var $TypeError = require('es-errors/type'); +var $floor = GetIntrinsic('%Math.floor%'); + +/** @type {import('.')} */ +module.exports = function setFunctionLength(fn, length) { + if (typeof fn !== 'function') { + throw new $TypeError('`fn` is not a function'); + } + if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) { + throw new $TypeError('`length` must be a positive 32-bit integer'); + } + + var loose = arguments.length > 2 && !!arguments[2]; + + var functionLengthIsConfigurable = true; + var functionLengthIsWritable = true; + if ('length' in fn && gOPD) { + var desc = gOPD(fn, 'length'); + if (desc && !desc.configurable) { + functionLengthIsConfigurable = false; + } + if (desc && !desc.writable) { + functionLengthIsWritable = false; + } + } + + if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) { + if (hasDescriptors) { + define(/** @type {Parameters[0]} */ (fn), 'length', length, true, true); + } else { + define(/** @type {Parameters[0]} */ (fn), 'length', length); + } + } + return fn; +}; diff --git a/node_modules/set-function-length/package.json b/node_modules/set-function-length/package.json new file mode 100644 index 000000000..f6b88819a --- /dev/null +++ b/node_modules/set-function-length/package.json @@ -0,0 +1,102 @@ +{ + "name": "set-function-length", + "version": "1.2.2", + "description": "Set a function's length property", + "main": "index.js", + "exports": { + ".": "./index.js", + "./env": "./env.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "directories": { + "test": "test" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "tsc": "tsc -p .", + "posttsc": "attw -P", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "npm run tsc", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/set-function-length.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "set", + "function", + "length", + "function.length" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/set-function-length/issues" + }, + "homepage": "https://github.com/ljharb/set-function-length#readme", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.15.1", + "@ljharb/eslint-config": "^21.1.0", + "@ljharb/tsconfig": "^0.1.1", + "@types/call-bind": "^1.0.5", + "@types/define-properties": "^1.1.5", + "@types/es-value-fixtures": "^1.4.4", + "@types/for-each": "^0.3.3", + "@types/function-bind": "^1.1.10", + "@types/gopd": "^1.0.3", + "@types/has-property-descriptors": "^1.0.3", + "@types/object-inspect": "^1.8.4", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "call-bind": "^1.0.7", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.5", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "test" + ] + } +} diff --git a/node_modules/set-function-length/tsconfig.json b/node_modules/set-function-length/tsconfig.json new file mode 100644 index 000000000..d9a6668c3 --- /dev/null +++ b/node_modules/set-function-length/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/side-channel/.editorconfig b/node_modules/side-channel/.editorconfig new file mode 100644 index 000000000..72e0ebaa7 --- /dev/null +++ b/node_modules/side-channel/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = tab +indent_size = 2 +trim_trailing_whitespace = true diff --git a/node_modules/side-channel/.eslintrc b/node_modules/side-channel/.eslintrc new file mode 100644 index 000000000..93978e7d5 --- /dev/null +++ b/node_modules/side-channel/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-lines-per-function": 0, + "multiline-comment-style": 1, + "new-cap": [2, { "capIsNewExceptions": ["GetIntrinsic"] }], + }, +} diff --git a/node_modules/side-channel/.github/FUNDING.yml b/node_modules/side-channel/.github/FUNDING.yml new file mode 100644 index 000000000..2a94840c6 --- /dev/null +++ b/node_modules/side-channel/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/side-channel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/side-channel/.nycrc b/node_modules/side-channel/.nycrc new file mode 100644 index 000000000..1826526e0 --- /dev/null +++ b/node_modules/side-channel/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/side-channel/CHANGELOG.md b/node_modules/side-channel/CHANGELOG.md new file mode 100644 index 000000000..25369c5f2 --- /dev/null +++ b/node_modules/side-channel/CHANGELOG.md @@ -0,0 +1,95 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.6](https://github.com/ljharb/side-channel/compare/v1.0.5...v1.0.6) - 2024-02-29 + +### Commits + +- add types [`9beef66`](https://github.com/ljharb/side-channel/commit/9beef6643e6d717ea57bedabf86448123a7dd9e9) +- [meta] simplify `exports` [`4334cf9`](https://github.com/ljharb/side-channel/commit/4334cf9df654151504c383b62a2f9ebdc8d9d5ac) +- [Deps] update `call-bind` [`d6043c4`](https://github.com/ljharb/side-channel/commit/d6043c4d8f4d7be9037dd0f0419c7a2e0e39ec6a) +- [Dev Deps] update `tape` [`6aca376`](https://github.com/ljharb/side-channel/commit/6aca3761868dc8cd5ff7fd9799bf6b95e09a6eb0) + +## [v1.0.5](https://github.com/ljharb/side-channel/compare/v1.0.4...v1.0.5) - 2024-02-06 + +### Commits + +- [actions] reuse common workflows [`3d2e1ff`](https://github.com/ljharb/side-channel/commit/3d2e1ffd16dd6eaaf3e40ff57951f840d2d63c04) +- [meta] use `npmignore` to autogenerate an npmignore file [`04296ea`](https://github.com/ljharb/side-channel/commit/04296ea17d1544b0a5d20fd5bfb31aa4f6513eb9) +- [meta] add `.editorconfig`; add `eclint` [`130f0a6`](https://github.com/ljharb/side-channel/commit/130f0a6adbc04d385c7456a601d38344dce3d6a9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `safe-publish-latest`, `tape` [`d480c2f`](https://github.com/ljharb/side-channel/commit/d480c2fbe757489ae9b4275491ffbcc3ac4725e9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`ecbe70e`](https://github.com/ljharb/side-channel/commit/ecbe70e53a418234081a77971fec1fdfae20c841) +- [actions] update rebase action [`75240b9`](https://github.com/ljharb/side-channel/commit/75240b9963b816e8846400d2287cb68f88c7fba7) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `npmignore`, `tape` [`ae8d281`](https://github.com/ljharb/side-channel/commit/ae8d281572430099109870fd9430d2ca3f320b8d) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`7125b88`](https://github.com/ljharb/side-channel/commit/7125b885fd0eacad4fee9b073b72d14065ece278) +- [Deps] update `call-bind`, `get-intrinsic`, `object-inspect` [`82577c9`](https://github.com/ljharb/side-channel/commit/82577c9796304519139a570f82a317211b5f3b86) +- [Deps] update `call-bind`, `get-intrinsic`, `object-inspect` [`550aadf`](https://github.com/ljharb/side-channel/commit/550aadf20475a6081fd70304cc54f77259a5c8a8) +- [Tests] increase coverage [`5130877`](https://github.com/ljharb/side-channel/commit/5130877a7b27c862e64e6d1c12a178b28808859d) +- [Deps] update `get-intrinsic`, `object-inspect` [`ba0194c`](https://github.com/ljharb/side-channel/commit/ba0194c505b1a8a0427be14cadd5b8a46d4d01b8) +- [meta] add missing `engines.node` [`985fd24`](https://github.com/ljharb/side-channel/commit/985fd249663cb06617a693a94fe08cad12f5cb70) +- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`40227a8`](https://github.com/ljharb/side-channel/commit/40227a87b01709ad2c0eebf87eb4223a800099b9) +- [Deps] update `get-intrinsic` [`a989b40`](https://github.com/ljharb/side-channel/commit/a989b4024958737ae7be9fbffdeff2078f33a0fd) +- [Deps] update `object-inspect` [`aec42d2`](https://github.com/ljharb/side-channel/commit/aec42d2ec541a31aaa02475692c87d489237d9a3) + +## [v1.0.4](https://github.com/ljharb/side-channel/compare/v1.0.3...v1.0.4) - 2020-12-29 + +### Commits + +- [Tests] migrate tests to Github Actions [`10909cb`](https://github.com/ljharb/side-channel/commit/10909cbf8ce9c0bf96f604cf13d7ffd5a22c2d40) +- [Refactor] Use a linked list rather than an array, and move accessed nodes to the beginning [`195613f`](https://github.com/ljharb/side-channel/commit/195613f28b5c1e6072ef0b61b5beebaf2b6a304e) +- [meta] do not publish github action workflow files [`290ec29`](https://github.com/ljharb/side-channel/commit/290ec29cd21a60585145b4a7237ec55228c52c27) +- [Tests] run `nyc` on all tests; use `tape` runner [`ea6d030`](https://github.com/ljharb/side-channel/commit/ea6d030ff3fe6be2eca39e859d644c51ecd88869) +- [actions] add "Allow Edits" workflow [`d464d8f`](https://github.com/ljharb/side-channel/commit/d464d8fe52b5eddf1504a0ed97f0941a90f32c15) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog` [`02daca8`](https://github.com/ljharb/side-channel/commit/02daca87c6809821c97be468d1afa2f5ef447383) +- [Refactor] use `call-bind` and `get-intrinsic` instead of `es-abstract` [`e09d481`](https://github.com/ljharb/side-channel/commit/e09d481528452ebafa5cdeae1af665c35aa2deee) +- [Deps] update `object.assign` [`ee83aa8`](https://github.com/ljharb/side-channel/commit/ee83aa81df313b5e46319a63adb05cf0c179079a) +- [actions] update rebase action to use checkout v2 [`7726b0b`](https://github.com/ljharb/side-channel/commit/7726b0b058b632fccea709f58960871defaaa9d7) + +## [v1.0.3](https://github.com/ljharb/side-channel/compare/v1.0.2...v1.0.3) - 2020-08-23 + +### Commits + +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`1f10561`](https://github.com/ljharb/side-channel/commit/1f105611ef3acf32dec8032ae5c0baa5e56bb868) +- [Deps] update `es-abstract`, `object-inspect` [`bc20159`](https://github.com/ljharb/side-channel/commit/bc201597949a505e37cef9eaf24c7010831e6f03) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`b9b2b22`](https://github.com/ljharb/side-channel/commit/b9b2b225f9e0ea72a6ec2b89348f0bd690bc9ed1) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`7055ab4`](https://github.com/ljharb/side-channel/commit/7055ab4de0860606efd2003674a74f1fe6ebc07e) +- [Dev Deps] update `auto-changelog`; add `aud` [`d278c37`](https://github.com/ljharb/side-channel/commit/d278c37d08227be4f84aa769fcd919e73feeba40) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`3bcf982`](https://github.com/ljharb/side-channel/commit/3bcf982faa122745b39c33ce83d32fdf003741c6) +- [Tests] only audit prod deps [`18d01c4`](https://github.com/ljharb/side-channel/commit/18d01c4015b82a3d75044c4d5ba7917b2eac01ec) +- [Deps] update `es-abstract` [`6ab096d`](https://github.com/ljharb/side-channel/commit/6ab096d9de2b482cf5e0717e34e212f5b2b9bc9a) +- [Dev Deps] update `tape` [`9dc174c`](https://github.com/ljharb/side-channel/commit/9dc174cc651dfd300b4b72da936a0a7eda5f9452) +- [Deps] update `es-abstract` [`431d0f0`](https://github.com/ljharb/side-channel/commit/431d0f0ff11fbd2ae6f3115582a356d3a1cfce82) +- [Deps] update `es-abstract` [`49869fd`](https://github.com/ljharb/side-channel/commit/49869fd323bf4453f0ba515c0fb265cf5ab7b932) +- [meta] Add package.json to package's exports [`77d9cdc`](https://github.com/ljharb/side-channel/commit/77d9cdceb2a9e47700074f2ae0c0a202e7dac0d4) + +## [v1.0.2](https://github.com/ljharb/side-channel/compare/v1.0.1...v1.0.2) - 2019-12-20 + +### Commits + +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`4a526df`](https://github.com/ljharb/side-channel/commit/4a526df44e4701566ed001ec78546193f818b082) +- [Deps] update `es-abstract` [`d4f6e62`](https://github.com/ljharb/side-channel/commit/d4f6e629b6fb93a07415db7f30d3c90fd7f264fe) + +## [v1.0.1](https://github.com/ljharb/side-channel/compare/v1.0.0...v1.0.1) - 2019-12-01 + +### Commits + +- [Fix] add missing "exports" [`d212907`](https://github.com/ljharb/side-channel/commit/d2129073abf0701a5343bf28aa2145617604dc2e) + +## v1.0.0 - 2019-12-01 + +### Commits + +- Initial implementation [`dbebd3a`](https://github.com/ljharb/side-channel/commit/dbebd3a4b5ed64242f9a6810efe7c4214cd8cde4) +- Initial tests [`73bdefe`](https://github.com/ljharb/side-channel/commit/73bdefe568c9076cf8c0b8719bc2141aec0e19b8) +- Initial commit [`43c03e1`](https://github.com/ljharb/side-channel/commit/43c03e1c2849ec50a87b7a5cd76238a62b0b8770) +- npm init [`5c090a7`](https://github.com/ljharb/side-channel/commit/5c090a765d66a5527d9889b89aeff78dee91348c) +- [meta] add `auto-changelog` [`a5c4e56`](https://github.com/ljharb/side-channel/commit/a5c4e5675ec02d5eb4d84b4243aeea2a1d38fbec) +- [actions] add automatic rebasing / merge commit blocking [`bab1683`](https://github.com/ljharb/side-channel/commit/bab1683d8f9754b086e94397699fdc645e0d7077) +- [meta] add `funding` field; create FUNDING.yml [`63d7aea`](https://github.com/ljharb/side-channel/commit/63d7aeaf34f5650650ae97ca4b9fae685bd0937c) +- [Tests] add `npm run lint` [`46a5a81`](https://github.com/ljharb/side-channel/commit/46a5a81705cd2664f83df232c01dbbf2ee952885) +- Only apps should have lockfiles [`8b16b03`](https://github.com/ljharb/side-channel/commit/8b16b0305f00895d90c4e2e5773c854cfea0e448) +- [meta] add `safe-publish-latest` [`2f098ef`](https://github.com/ljharb/side-channel/commit/2f098ef092a39399cfe548b19a1fc03c2fd2f490) diff --git a/node_modules/side-channel/LICENSE b/node_modules/side-channel/LICENSE new file mode 100644 index 000000000..3900dd7e2 --- /dev/null +++ b/node_modules/side-channel/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/side-channel/README.md b/node_modules/side-channel/README.md new file mode 100644 index 000000000..7fa4f0680 --- /dev/null +++ b/node_modules/side-channel/README.md @@ -0,0 +1,2 @@ +# side-channel +Store information about any JS value in a side channel. Uses WeakMap if available. diff --git a/node_modules/side-channel/index.d.ts b/node_modules/side-channel/index.d.ts new file mode 100644 index 000000000..7cb112b90 --- /dev/null +++ b/node_modules/side-channel/index.d.ts @@ -0,0 +1,27 @@ +declare namespace getSideChannel { + type Key = unknown; + type ListNode = { + key: Key; + next: ListNode; + value: T; + }; + type RootNode = { + key: object; + next: null | ListNode; + }; + function listGetNode(list: RootNode, key: ListNode['key']): ListNode | void; + function listGet(objects: RootNode, key: ListNode['key']): T | void; + function listSet(objects: RootNode, key: ListNode['key'], value: T): void; + function listHas(objects: RootNode, key: ListNode['key']): boolean; + + type Channel = { + assert: (key: Key) => void; + has: (key: Key) => boolean; + get: (key: Key) => T; + set: (key: Key, value: T) => void; + } +} + +declare function getSideChannel(): getSideChannel.Channel; + +export = getSideChannel; diff --git a/node_modules/side-channel/index.js b/node_modules/side-channel/index.js new file mode 100644 index 000000000..6b6926e11 --- /dev/null +++ b/node_modules/side-channel/index.js @@ -0,0 +1,129 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var callBound = require('call-bind/callBound'); +var inspect = require('object-inspect'); + +var $TypeError = require('es-errors/type'); +var $WeakMap = GetIntrinsic('%WeakMap%', true); +var $Map = GetIntrinsic('%Map%', true); + +var $weakMapGet = callBound('WeakMap.prototype.get', true); +var $weakMapSet = callBound('WeakMap.prototype.set', true); +var $weakMapHas = callBound('WeakMap.prototype.has', true); +var $mapGet = callBound('Map.prototype.get', true); +var $mapSet = callBound('Map.prototype.set', true); +var $mapHas = callBound('Map.prototype.has', true); + +/* +* This function traverses the list returning the node corresponding to the given key. +* +* That node is also moved to the head of the list, so that if it's accessed again we don't need to traverse the whole list. By doing so, all the recently used nodes can be accessed relatively quickly. +*/ +/** @type {import('.').listGetNode} */ +var listGetNode = function (list, key) { // eslint-disable-line consistent-return + /** @type {typeof list | NonNullable<(typeof list)['next']>} */ + var prev = list; + /** @type {(typeof list)['next']} */ + var curr; + for (; (curr = prev.next) !== null; prev = curr) { + if (curr.key === key) { + prev.next = curr.next; + // eslint-disable-next-line no-extra-parens + curr.next = /** @type {NonNullable} */ (list.next); + list.next = curr; // eslint-disable-line no-param-reassign + return curr; + } + } +}; + +/** @type {import('.').listGet} */ +var listGet = function (objects, key) { + var node = listGetNode(objects, key); + return node && node.value; +}; +/** @type {import('.').listSet} */ +var listSet = function (objects, key, value) { + var node = listGetNode(objects, key); + if (node) { + node.value = value; + } else { + // Prepend the new node to the beginning of the list + objects.next = /** @type {import('.').ListNode} */ ({ // eslint-disable-line no-param-reassign, no-extra-parens + key: key, + next: objects.next, + value: value + }); + } +}; +/** @type {import('.').listHas} */ +var listHas = function (objects, key) { + return !!listGetNode(objects, key); +}; + +/** @type {import('.')} */ +module.exports = function getSideChannel() { + /** @type {WeakMap} */ var $wm; + /** @type {Map} */ var $m; + /** @type {import('.').RootNode} */ var $o; + + /** @type {import('.').Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + get: function (key) { // eslint-disable-line consistent-return + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapGet($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapGet($m, key); + } + } else { + if ($o) { // eslint-disable-line no-lonely-if + return listGet($o, key); + } + } + }, + has: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapHas($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapHas($m, key); + } + } else { + if ($o) { // eslint-disable-line no-lonely-if + return listHas($o, key); + } + } + return false; + }, + set: function (key, value) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key, value); + } else if ($Map) { + if (!$m) { + $m = new $Map(); + } + $mapSet($m, key, value); + } else { + if (!$o) { + // Initialize the linked list as an empty node, so that we don't have to special-case handling of the first node: we can always refer to it as (previous node).next, instead of something like (list).head + $o = { key: {}, next: null }; + } + listSet($o, key, value); + } + } + }; + return channel; +}; diff --git a/node_modules/side-channel/package.json b/node_modules/side-channel/package.json new file mode 100644 index 000000000..02cffca6c --- /dev/null +++ b/node_modules/side-channel/package.json @@ -0,0 +1,84 @@ +{ + "name": "side-channel", + "version": "1.0.6", + "description": "Store information about any JS value in a side channel. Uses WeakMap if available.", + "main": "index.js", + "exports": { + "./package.json": "./package.json", + ".": "./index.js" + }, + "types": "./index.d.ts", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/side-channel.git" + }, + "keywords": [ + "weakmap", + "map", + "side", + "channel", + "metadata" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/side-channel/issues" + }, + "homepage": "https://github.com/ljharb/side-channel#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "@types/call-bind": "^1.0.5", + "@types/get-intrinsic": "^1.2.2", + "@types/object-inspect": "^1.8.4", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "eclint": "^2.8.1", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.5", + "typescript": "next" + }, + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/side-channel/test/index.js b/node_modules/side-channel/test/index.js new file mode 100644 index 000000000..8da320073 --- /dev/null +++ b/node_modules/side-channel/test/index.js @@ -0,0 +1,83 @@ +'use strict'; + +var test = require('tape'); + +var getSideChannel = require('../'); + +test('export', function (t) { + t.equal(typeof getSideChannel, 'function', 'is a function'); + t.equal(getSideChannel.length, 0, 'takes no arguments'); + + var channel = getSideChannel(); + t.ok(channel, 'is truthy'); + t.equal(typeof channel, 'object', 'is an object'); + + t.end(); +}); + +test('assert', function (t) { + var channel = getSideChannel(); + t['throws']( + function () { channel.assert({}); }, + TypeError, + 'nonexistent value throws' + ); + + var o = {}; + channel.set(o, 'data'); + t.doesNotThrow(function () { channel.assert(o); }, 'existent value noops'); + + t.end(); +}); + +test('has', function (t) { + var channel = getSideChannel(); + /** @type {unknown[]} */ var o = []; + + t.equal(channel.has(o), false, 'nonexistent value yields false'); + + channel.set(o, 'foo'); + t.equal(channel.has(o), true, 'existent value yields true'); + + t.equal(channel.has('abc'), false, 'non object value non existent yields false'); + + channel.set('abc', 'foo'); + t.equal(channel.has('abc'), true, 'non object value that exists yields true'); + + t.end(); +}); + +test('get', function (t) { + var channel = getSideChannel(); + var o = {}; + t.equal(channel.get(o), undefined, 'nonexistent value yields undefined'); + + var data = {}; + channel.set(o, data); + t.equal(channel.get(o), data, '"get" yields data set by "set"'); + + t.end(); +}); + +test('set', function (t) { + var channel = getSideChannel(); + var o = function () {}; + t.equal(channel.get(o), undefined, 'value not set'); + + channel.set(o, 42); + t.equal(channel.get(o), 42, 'value was set'); + + channel.set(o, Infinity); + t.equal(channel.get(o), Infinity, 'value was set again'); + + var o2 = {}; + channel.set(o2, 17); + t.equal(channel.get(o), Infinity, 'o is not modified'); + t.equal(channel.get(o2), 17, 'o2 is set'); + + channel.set(o, 14); + t.equal(channel.get(o), 14, 'o is modified'); + t.equal(channel.get(o2), 17, 'o2 is not modified'); + + t.end(); +}); diff --git a/node_modules/side-channel/tsconfig.json b/node_modules/side-channel/tsconfig.json new file mode 100644 index 000000000..fdfa1550d --- /dev/null +++ b/node_modules/side-channel/tsconfig.json @@ -0,0 +1,50 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Projects */ + + /* Language and Environment */ + "target": "es2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": ["types"], /* Specify multiple folders that act like `./node_modules/@types`. */ + "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declarationMap": true, /* Create sourcemaps for d.ts files. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + + /* Interop Constraints */ + "allowSyntheticDefaultImports": true, /* Allow `import x from y` when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + + /* Completeness */ + // "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "exclude": [ + "coverage", + "test/list-exports" + ], +} diff --git a/node_modules/string_decoder/LICENSE b/node_modules/string_decoder/LICENSE new file mode 100644 index 000000000..778edb207 --- /dev/null +++ b/node_modules/string_decoder/LICENSE @@ -0,0 +1,48 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + diff --git a/node_modules/string_decoder/README.md b/node_modules/string_decoder/README.md new file mode 100644 index 000000000..5fd58315e --- /dev/null +++ b/node_modules/string_decoder/README.md @@ -0,0 +1,47 @@ +# string_decoder + +***Node-core v8.9.4 string_decoder for userland*** + + +[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) +[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) + + +```bash +npm install --save string_decoder +``` + +***Node-core string_decoder for userland*** + +This package is a mirror of the string_decoder implementation in Node-core. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). + +As of version 1.0.0 **string_decoder** uses semantic versioning. + +## Previous versions + +Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. + +## Update + +The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. + +## Streams Working Group + +`string_decoder` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + +See [readable-stream](https://github.com/nodejs/readable-stream) for +more details. diff --git a/node_modules/string_decoder/lib/string_decoder.js b/node_modules/string_decoder/lib/string_decoder.js new file mode 100644 index 000000000..2e89e63f7 --- /dev/null +++ b/node_modules/string_decoder/lib/string_decoder.js @@ -0,0 +1,296 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +/**/ + +var Buffer = require('safe-buffer').Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} \ No newline at end of file diff --git a/node_modules/bluebird/LICENSE b/node_modules/string_decoder/node_modules/safe-buffer/LICENSE similarity index 89% rename from node_modules/bluebird/LICENSE rename to node_modules/string_decoder/node_modules/safe-buffer/LICENSE index b24e6350c..0c068ceec 100644 --- a/node_modules/bluebird/LICENSE +++ b/node_modules/string_decoder/node_modules/safe-buffer/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2013-2018 Petka Antonov +Copyright (c) Feross Aboukhadijeh Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -14,7 +14,7 @@ all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN diff --git a/node_modules/string_decoder/node_modules/safe-buffer/README.md b/node_modules/string_decoder/node_modules/safe-buffer/README.md new file mode 100644 index 000000000..e9a81afd0 --- /dev/null +++ b/node_modules/string_decoder/node_modules/safe-buffer/README.md @@ -0,0 +1,584 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/node_modules/string_decoder/node_modules/safe-buffer/index.d.ts b/node_modules/string_decoder/node_modules/safe-buffer/index.d.ts new file mode 100644 index 000000000..e9fed809a --- /dev/null +++ b/node_modules/string_decoder/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/node_modules/string_decoder/node_modules/safe-buffer/index.js b/node_modules/string_decoder/node_modules/safe-buffer/index.js new file mode 100644 index 000000000..f8d3ec988 --- /dev/null +++ b/node_modules/string_decoder/node_modules/safe-buffer/index.js @@ -0,0 +1,65 @@ +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/node_modules/string_decoder/node_modules/safe-buffer/package.json b/node_modules/string_decoder/node_modules/safe-buffer/package.json new file mode 100644 index 000000000..f2869e256 --- /dev/null +++ b/node_modules/string_decoder/node_modules/safe-buffer/package.json @@ -0,0 +1,51 @@ +{ + "name": "safe-buffer", + "description": "Safer Node.js Buffer API", + "version": "5.2.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "devDependencies": { + "standard": "*", + "tape": "^5.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/node_modules/string_decoder/package.json b/node_modules/string_decoder/package.json new file mode 100644 index 000000000..b2bb14116 --- /dev/null +++ b/node_modules/string_decoder/package.json @@ -0,0 +1,34 @@ +{ + "name": "string_decoder", + "version": "1.3.0", + "description": "The string_decoder module from Node core", + "main": "lib/string_decoder.js", + "files": [ + "lib" + ], + "dependencies": { + "safe-buffer": "~5.2.0" + }, + "devDependencies": { + "babel-polyfill": "^6.23.0", + "core-util-is": "^1.0.2", + "inherits": "^2.0.3", + "tap": "~0.4.8" + }, + "scripts": { + "test": "tap test/parallel/*.js && node test/verify-dependencies", + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/string_decoder.git" + }, + "homepage": "https://github.com/nodejs/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT" +} diff --git a/node_modules/superagent/.browserslistrc b/node_modules/superagent/.browserslistrc new file mode 100644 index 000000000..31f0e385b --- /dev/null +++ b/node_modules/superagent/.browserslistrc @@ -0,0 +1,5 @@ +# Browsers that we support + +> 1% +last 2 versions +ie 9 diff --git a/node_modules/superagent/.dist.babelrc b/node_modules/superagent/.dist.babelrc new file mode 100644 index 000000000..a5c452249 --- /dev/null +++ b/node_modules/superagent/.dist.babelrc @@ -0,0 +1,10 @@ +{ + "presets": [ + ["@babel/env", { + "targets": { + "browsers": [ "> 1%", "last 2 versions", "ie 9" ] + } + }] + ], + "sourceMaps": "inline" +} diff --git a/node_modules/superagent/.dist.eslintrc b/node_modules/superagent/.dist.eslintrc new file mode 100644 index 000000000..428058969 --- /dev/null +++ b/node_modules/superagent/.dist.eslintrc @@ -0,0 +1,35 @@ +{ + "extends": ["eslint:recommended"], + "env": { + "node": false, + "browser": true, + "amd": true, + "es6": true + }, + "plugins": ["compat"], + "rules": { + "compat/compat": "error", + "no-console": "off", + "no-empty": "off", + "no-extra-semi": "off", + "no-func-assign": "off", + "no-undef": "off", + "no-unused-vars": "off", + "no-useless-escape": "off", + "no-cond-assign": "off", + "no-redeclare": "off", + "node/no-exports-assign": "off" + }, + "globals": { + "regeneratorRuntime": "writable" + }, + "settings": { + "polyfills": [ + "Promise", + "Array.from", + "Symbol", + "Object.getOwnPropertySymbols", + "Object.setPrototypeOf" + ] + } +} diff --git a/node_modules/function-bind/.editorconfig b/node_modules/superagent/.editorconfig similarity index 51% rename from node_modules/function-bind/.editorconfig rename to node_modules/superagent/.editorconfig index ac29adef0..c6c8b3621 100644 --- a/node_modules/function-bind/.editorconfig +++ b/node_modules/superagent/.editorconfig @@ -1,20 +1,9 @@ root = true [*] -indent_style = tab -indent_size = 4 +indent_style = space +indent_size = 2 end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true -max_line_length = 120 - -[CHANGELOG.md] -indent_style = space -indent_size = 2 - -[*.json] -max_line_length = off - -[Makefile] -max_line_length = off diff --git a/node_modules/superagent/.gitattributes b/node_modules/superagent/.gitattributes new file mode 100644 index 000000000..176a458f9 --- /dev/null +++ b/node_modules/superagent/.gitattributes @@ -0,0 +1 @@ +* text=auto diff --git a/node_modules/superagent/.lib.babelrc b/node_modules/superagent/.lib.babelrc new file mode 100644 index 000000000..1e8c9e5ea --- /dev/null +++ b/node_modules/superagent/.lib.babelrc @@ -0,0 +1,11 @@ +{ + "presets": [ + ["@babel/env", { + "targets": { + "node": "6.4.0", + "browsers": [ "> 1%", "last 2 versions", "ie 9" ] + } + }] + ], + "sourceMaps": "inline" +} diff --git a/node_modules/superagent/.lib.eslintrc b/node_modules/superagent/.lib.eslintrc new file mode 100644 index 000000000..78f041df8 --- /dev/null +++ b/node_modules/superagent/.lib.eslintrc @@ -0,0 +1,24 @@ +{ + "extends": ["eslint:recommended", "plugin:node/recommended"], + "env": { + "browser": true + }, + "rules": { + "node/no-deprecated-api": "off", + "no-console": "off", + "no-unused-vars": "off", + "no-empty": "off", + "node/no-unsupported-features/node-builtins": "off", + "no-func-assign": "off", + "no-global-assign": ["error", {"exceptions": ["exports"]}], + "node/no-exports-assign": "off" + }, + "overrides": [ + { + "files": [ "lib/client.js" ], + "globals": { + "ActiveXObject": "readable" + } + } + ] +} diff --git a/node_modules/superagent/.remarkignore b/node_modules/superagent/.remarkignore new file mode 100644 index 000000000..9e60a0859 --- /dev/null +++ b/node_modules/superagent/.remarkignore @@ -0,0 +1,3 @@ +CONTRIBUTING.md +HISTORY.md +docs diff --git a/node_modules/superagent/.zuul.yml b/node_modules/superagent/.zuul.yml new file mode 100644 index 000000000..8b229ec5f --- /dev/null +++ b/node_modules/superagent/.zuul.yml @@ -0,0 +1,16 @@ +ui: mocha-bdd +server: ./test/support/server.js +tunnel_host: http://focusaurus.com +browsers: + - name: chrome + version: latest + - name: firefox + version: latest + - name: safari + version: latest + - name: ie + version: 9..latest +browserify: + - transform: + name: babelify + configFile: './.dist.babelrc' diff --git a/node_modules/superagent/CONTRIBUTING.md b/node_modules/superagent/CONTRIBUTING.md new file mode 100644 index 000000000..1eca59265 --- /dev/null +++ b/node_modules/superagent/CONTRIBUTING.md @@ -0,0 +1,7 @@ +When submitting a PR, your chance of acceptance increases if you do the following: + +* Code style is consistent with existing in the file. +* Tests are passing (client and server). +* You add a test for the failing issue you are fixing. +* Code changes are focused on the area of discussion. +* Do not rebuild the distribution files or increment version numbers. diff --git a/node_modules/superagent/HISTORY.md b/node_modules/superagent/HISTORY.md new file mode 100644 index 000000000..0eef03c98 --- /dev/null +++ b/node_modules/superagent/HISTORY.md @@ -0,0 +1,692 @@ +# This HISTORY log is deprecated + +Please see [GitHub releases page](https://github.com/visionmedia/superagent/releases) for the current changelog. + +# 4.1.0 (2018-12-26) + + * `.connect()` IP/DNS override option (Kornel) + * `.trustLocalhost()` option for allowing broken HTTPS on `localhost` + * `.abort()` used with promises rejects the promise. + +# 4.0.0 (2018-11-17) + +## Breaking changes + +* Node.js v4 has reached it's end of life, so we no longer support it. It's v6+ or later. We recommend Node.js 10. +* We now use ES6 in the browser code, too. + * If you're using Browserify or Webpack to package code for Internet Explorer, you will also have to use Babel. + * The pre-built node_modules/superagent.js is still ES5-compatible. +* `.end(…)` returns `undefined` instead of the request. If you need the request object after calling `.end()` (and you probably don't), save it in a variable and call `request.end(…)`. Consider not using `.end()` at all, and migrating to promises by calling `.then()` instead. +* In Node, responses with unknown MIME type are buffered by default. To get old behavior, if you use custom _unbuffered_ parsers, add `.buffer(false)` to requests or set `superagent.buffer[yourMimeType] = false`. +* Invalid uses of `.pipe()` throw. + + +## Minor changes + +* Throw if `req.abort().end()` is called +* Throw if using unsupported mix of send and field +* Reject `.end()` promise on all error events (Kornel Lesiński) +* Set `https.servername` from the `Host` header (Kornel Lesiński) +* Leave backticks unencoded in query strings where possible (Ethan Resnick) +* Update node-mime to 2.x (Alexey Kucherenko) +* Allow default buffer settings based on response-type (shrey) +* `response.buffered` is more accurate. + +# 3.8.3 (2018-04-29) + +* Add flags for 201 & 422 responses (Nikhil Fadnis) +* Emit progress event while uploading Node `Buffer` via send method (Sergey Akhalkov) +* Fixed setting correct cookies for redirects (Damien Clark) +* Replace .catch with ['catch'] for IE9 Support (Miguel Stevens) + +# 3.8.2 (2017-12-09) + +* Fixed handling of exceptions thrown from callbacks +* Stricter matching of `+json` MIME types. + +# 3.8.1 (2017-11-08) + +* Clear authorization header on cross-domain redirect + +# 3.8.0 + +* Added support for "globally" defined headers and event handlers via `superagent.agent()`. It now remembers default settings for all its requests. +* Added optional callback to `.retry()` (Alexander Murphy) +* Unified auth args handling in node/browser (Edmundo Alvarez) +* Fixed error handling in zlib pipes (Kornel) +* Documented that 3xx status codes are errors (Mickey Reiss) + +# 3.7.0 (2017-10-17) + +* Limit maximum response size. Prevents zip bombs (Kornel) +* Catch and pass along errors in `.ok()` callback (Jeremy Ruppel) +* Fixed parsing of XHR headers without a newline (nsf) + +# 3.6.2 (2017-10-02) + +* Upgrade MIME type dependency to a newer, secure version +* Recognize PDF MIME as binary +* Fix for error in subsequent require() calls (Steven de Salas) + +# 3.6.0 (2017-08-20) + +* Support disabling TCP_NODELAY option ([#1240](https://github.com/visionmedia/superagent/issues/1240)) (xiamengyu) +* Send payload in query string for GET and HEAD shorthand API (Peter Lyons) +* Support passphrase with pfx certificate (Paul Westerdale (ABRS Limited)) +* Documentation improvements (Peter Lyons) +* Fixed duplicated query string params ([#1200](https://github.com/visionmedia/superagent/issues/1200)) (Kornel) + +# 3.5.1 (2017-03-18) + +* Allow crossDomain errors to be retried ([#1194](https://github.com/visionmedia/superagent/issues/1194)) (Michael Olson) +* Read responseType property from the correct object (Julien Dupouy) +* Check for ownProperty before adding header (Lucas Vieira) + +# 3.5.0 (2017-02-23) + +* Add errno to distinguish between request timeout and body download timeout ([#1184](https://github.com/visionmedia/superagent/issues/1184)) (Kornel Lesiński) +* Warn about bogus timeout options ([#1185](https://github.com/visionmedia/superagent/issues/1185)) (Kornel Lesiński) + +# 3.4.4 (2017-02-17) + +* Treat videos like images (Kornel Lesiński) +* Avoid renaming module (Kornel Lesiński) + +# 3.4.3 (2017-02-14) + +* Fixed being able to define own parsers when their mime type starts with `text/` (Damien Clark) +* `withCredentials(false)` (Andy Woods) +* Use `formData.on` instead of `.once` (Kornel Lesiński) +* Ignore `attach("file",null)` (Kornel Lesiński) + +# 3.4.1 (2017-01-29) + +* Allow `retry()` and `retry(0)` (Alexander Pope) +* Allow optional body/data in DELETE requests (Alpha Shuro) +* Fixed query string on retried requests (Kornel Lesiński) + +# 3.4.0 (2017-01-25) + +* New `.retry(n)` method and `err.retries` (Alexander Pope) +* Docs for HTTPS request (Jun Wan Goh) + +# 3.3.1 (2016-12-17) + +* Fixed "double callback bug" warning on timeouts of gzipped responses + +# 3.3.0 (2016-12-14) + +* Added `.ok(callback)` that allows customizing which responses are errors (Kornel Lesiński) +* Added `.responseType()` to Node version (Kornel Lesiński) +* Added `.parse()` to browser version (jakepearson) +* Fixed parse error when using `responseType('blob')` (Kornel Lesiński) + +# 3.2.0 (2016-12-11) + +* Added `.timeout({response:ms})`, which allows limiting maximum response time independently from total download time (Kornel Lesiński) +* Added warnings when `.end()` is called more than once (Kornel Lesiński) +* Added `response.links` to browser version (Lukas Eipert) +* `btoa` is no longer required in IE9 (Kornel Lesiński) +* Fixed `.sortQuery()` on URLs without query strings (Kornel Lesiński) +* Refactored common response code into `ResponseBase` (Lukas Eipert) + +# 3.1.0 (2016-11-28) + +* Added `.sortQuery()` (vicanso) +* Added support for arrays and bools in `.field()` (Kornel Lesiński) +* Made `superagent.Request` subclassable without need to patch all static methods (Kornel Lesiński) + +# 3.0.0 (2016-11-19) + +* Dropped support for Node 0.x. Please upgrade to at least Node 4. +* Dropped support for componentjs (Damien Caselli) +* Removed deprecated `.part()`/`superagent.Part` APIs. +* Removed unreliable `.body` property on internal response object used by unbuffered parsers. + Note: the normal `response.body` is unaffected. +* Multiple `.send()` calls mixing `Buffer`/`Blob` and JSON data are not possible and will now throw instead of messing up the data. +* Improved `.send()` data object type check (Fernando Mendes) +* Added common prototype for Node and browser versions (Andreas Helmberger) +* Added `http+unix:` schema to support Unix sockets (Yuki KAN) +* Added full `attach` options parameter in the Node version (Lapo Luchini) +* Added `pfx` TLS option with new `pfx()` method. (Reid Burke) +* Internally changed `.on` to `.once` to prevent possible memory leaks (Matt Blair) +* Made all errors reported as an event (Kornel Lesiński) + +# 2.3.0 (2016-09-20) + +* Enabled `.field()` to handle objects (Affan Shahid) +* Added authentication with client certificates (terusus) +* Added `.catch()` for more Promise-like interface (Maxim Samoilov, Kornel Lesiński) +* Silenced errors from incomplete gzip streams for compatibility with web browsers (Kornel Lesiński) +* Fixed `event.direction` in uploads (Kornel Lesiński) +* Fixed returned value of overwritten response object's `on()` method (Juan Dopazo) + +# 2.2.0 (2016-08-13) + +* Added `timedout` property to node Request instance (Alexander Pope) +* Unified `null` querystring values in node and browser environments. (George Chung) + +# 2.1.0 (2016-06-14) + +* Refactored async parsers. Now the `end` callback waits for async parsers to finish (Kornel Lesiński) +* Errors thrown in `.end()` callback don't cause the callback to be called twice (Kornel Lesiński) +* Added `headers` to `toJSON()` (Tao) + +# 2.0.0 (2016-05-29) + + +## Breaking changes + +Breaking changes are in rarely used functionality, so we hope upgrade will be smooth for most users. + +* Browser: The `.parse()` method has been renamed to `.serialize()` for consistency with NodeJS version. +* Browser: Query string keys without a value used to be parsed as `'undefined'`, now their value is `''` (empty string) (shura, Kornel Lesiński). +* NodeJS: The `redirect` event is called after new query string and headers have been set and is allowed to override the request URL (Kornel Lesiński) +* `.then()` returns a real `Promise`. Note that use of superagent with promises now requires a global `Promise` object. + If you target Internet Explorer or Node 0.10, you'll need `require('es6-promise').polyfill()` or similar. +* Upgraded all dependencies (Peter Lyons) +* Renamed properties documented as `@api private` to have `_prefixed` names (Kornel Lesiński) + + +## Probably not breaking changes: + +* Extracted common functions to request-base (Peter Lyons) +* Fixed race condition in pipe tests (Peter Lyons) +* Handle `FormData` error events (scriptype) +* Fixed wrong jsdoc of Request#attach (George Chung) +* Updated and improved tests (Peter Lyons) +* `request.head()` supports `.redirects(5)` call (Kornel Lesiński) +* `response` event is also emitted when using `.pipe()` + +# 1.8.2 (2016-03-20) + +* Fixed handling of HTTP status 204 with content-encoding: gzip (Andrew Shelton) +* Handling of FormData error events (scriptype) +* Fixed parsing of `vnd+json` MIME types (Kornel Lesiński) +* Aliased browser implementation of `.parse()` as `.serialize()` for forward compatibility + +# 1.8.1 (2016-03-14) + +* Fixed form-data incompatibility with IE9 + +# 1.8.0 (2016-03-09) + +* Extracted common code into request-base class (Peter Lyons) + * It does not affect the public API, but please let us know if you notice any plugins/subclasses breaking! +* Added option `{type:'auto'}` to `auth` method, which enables browser-native auth types (Jungle, Askar Yusupov) +* Added `responseType()` to set XHR `responseType` (chris) +* Switched to form-data for browserify-compatible `FormData` (Peter Lyons) +* Added `statusCode` to error response when JSON response is malformed (mattdell) +* Prevented TCP port conflicts in all tests (Peter Lyons) +* Updated form-data dependency + +# 1.7.2 (2016-01-26) + +* Fix case-sensitivity of header fields introduced by [`a4ddd6a`](https://github.com/visionmedia/superagent/commit/a4ddd6a). (Edward J. Jinotti) +* bump extend dependency, as former version did not contain any license information (Lukas Eipert) + +# 1.7.1 (2016-01-21) + +* Fixed a conflict with express when using npm 3.x (Glenn) +* Fixed redirects after a multipart/form-data POST request (cyclist2) + +# 1.7.0 (2016-01-18) + +* When attaching files, read default filename from the `File` object (JD Isaacks) +* Add `direction` property to `progress` events (Joseph Dykstra) +* Update component-emitter & formidable (Kornel Lesiński) +* Don't re-encode query string needlessly (Ruben Verborgh) +* ensure querystring is appended when doing `stream.pipe(request)` (Keith Grennan) +* change set header function, not call `this.request()` until call `this.end()` (vicanso) +* Add no-op `withCredentials` to Node API (markdalgleish) +* fix `delete` breaking on ie8 (kenjiokabe) +* Don't let request error override responses (Clay Reimann) +* Increased number of tests shared between node and client (Kornel Lesiński) + +# 1.6.0/1.6.1 (2015-12-09) + +* avoid misleading CORS error message +* added 'progress' event on file/form upload in Node (Olivier Lalonde) +* return raw response if the response parsing fails (Rei Colina) +* parse content-types ending with `+json` as JSON (Eiryyy) +* fix to avoid throwing errors on aborted requests (gjurgens) +* retain cookies on redirect when hosts match (Tom Conroy) +* added Bower manifest (Johnny Freeman) +* upgrade to latest cookiejar (Andy Burke) + +# 1.5.0 (2015-11-30) + +* encode array values as `key=1&key=2&key=3` etc... (aalpern, Davis Kim) +* avoid the error which is omitted from 'socket hang up' +* faster JSON parsing, handling of zlib errors (jbellenger) +* fix IE11 sends 'undefined' string if data was undefined (Vadim Goncharov) +* alias `del()` method as `delete()` (Aaron Krause) +* revert Request#parse since it was actually Response#parse + +# 1.4.0 (2015-09-14) + +* add Request#parse method to client library +* add missing statusCode in client response +* don't apply JSON heuristics if a valid parser is found +* fix detection of root object for webworkers + +# 1.3.0 (2015-08-05) + +* fix incorrect content-length of data set to buffer +* serialize request data takes into account charsets +* add basic promise support via a `then` function + +# 1.2.0 (2015-04-13) + +* add progress events to downlodas +* make usable in webworkers +* add support for 308 redirects +* update node-form-data dependency +* update to work in react native +* update node-mime dependency + +# 1.1.0 (2015-03-13) + +* Fix responseType checks without xhr2 and ie9 tests (rase-) +* errors have .status and .response fields if applicable (defunctzombie) +* fix end callback called before saving cookies (rase-) + +# 1.0.0 / 2015-03-08 + +* All non-200 responses are treated as errors now. (The callback is called with an error when the response has a status < 200 or >= 300 now. In previous versions this would not have raised an error and the client would have to check the `res` object. See [#283](https://github.com/visionmedia/superagent/issues/283). +* keep timeouts intact across redirects (hopkinsth) +* handle falsy json values (themaarten) +* fire response events in browser version (Schoonology) +* getXHR exported in client version (KidsKilla) +* remove arity check on `.end()` callbacks (defunctzombie) +* avoid setting content-type for host objects (rexxars) +* don't index array strings in querystring (travisjeffery) +* fix pipe() with redirects (cyrilis) +* add xhr2 file download (vstirbu) +* set default response type to text/plain if not specified (warrenseine) + +# 0.21.0 / 2014-11-11 + +* Trim text before parsing json (gjohnson) +* Update tests to express 4 (gaastonsr) +* Prevent double callback when error is thrown (pgn-vole) +* Fix missing clearTimeout (nickdima) +* Update debug (TooTallNate) + +# 0.20.0 / 2014-10-02 + +* Add toJSON() to request and response instances. (yields) +* Prevent HEAD requests from getting parsed. (gjohnson) +* Update debug. (TooTallNate) + +# 0.19.1 / 2014-09-24 + +* Fix basic auth issue when password is falsey value. (gjohnson) + +# 0.19.0 / 2014-09-24 + +* Add unset() to browser. (shesek) +* Prefer XHR over ActiveX. (omeid) +* Catch parse errors. (jacwright) +* Update qs dependency. (wercker) +* Add use() to node. (Financial-Times) +* Add response text to errors. (yields) +* Don't send empty cookie headers. (undoZen) +* Don't parse empty response bodies. (DveMac) +* Use hostname when setting cookie host. (prasunsultania) + +# 0.18.2 / 2014-07-12 + +* Handle parser errors. (kof) +* Ensure not to use default parsers when there is a user defined one. (kof) + +# 0.18.1 / 2014-07-05 + +* Upgrade cookiejar dependency (juanpin) +* Support image mime types (nebulade) +* Make .agent chainable (kof) +* Upgrade debug (TooTallNate) +* Fix docs (aheckmann) + +# 0.18.0 / 2014-04-29 + +* Use "form-data" module for the multipart/form-data implementation. (TooTallNate) +* Add basic `field()` and `attach()` functions for HTML5 FormData. (TooTallNate) +* Deprecate `part()`. (TooTallNate) +* Set default user-agent header. (bevacqua) +* Add `unset()` method for removing headers. (bevacqua) +* Update cookiejar. (missinglink) +* Fix response error formatting. (shesek) + +# 0.17.0 / 2014-03-06 + +* supply uri malformed error to the callback (yields) +* add request event (yields) +* allow simple auth (yields) +* add request event (yields) +* switch to component/reduce (visionmedia) +* fix part content-disposition (mscdex) +* add browser testing via zuul (defunctzombie) +* adds request.use() (johntron) + +# 0.16.0 / 2014-01-07 + +* remove support for 0.6 (superjoe30) +* fix CORS withCredentials (wejendorp) +* add "test" script (superjoe30) +* add request .accept() method (nickl-) +* add xml to mime types mappings (nickl-) +* fix parse body error on HEAD requests (gjohnson) +* fix documentation typos (matteofigus) +* fix content-type + charset (bengourley) +* fix null values on query parameters (cristiandouce) + +# 0.15.7 / 2013-10-19 + +* pin should.js to 1.3.0 due to breaking change in 2.0.x +* fix browserify regression + +# 0.15.5 / 2013-10-09 + +* add browser field to support browserify +* fix .field() value number support + +# 0.15.4 / 2013-07-09 + +* node: add a Request#agent() function to set the http Agent to use + +# 0.15.3 / 2013-07-05 + +* fix .pipe() unzipping on more recent nodes. Closes [#240](https://github.com/visionmedia/superagent/issues/240) +* fix passing an empty object to .query() no longer appends "?" +* fix formidable error handling +* update formidable + +# 0.15.2 / 2013-07-02 + +* fix: emit 'end' when piping. + +# 0.15.1 / 2013-06-26 + +* add try/catch around parseLinks + +# 0.15.0 / 2013-06-25 + +* make `Response#toError()` have a more meaningful `message` + +# 0.14.9 / 2013-06-15 + +* add debug()s to the node client +* add .abort() method to node client + +# 0.14.8 / 2013-06-13 + +* set .agent = false always +* remove X-Requested-With. Closes [#189](https://github.com/visionmedia/superagent/issues/189) + +# 0.14.7 / 2013-06-06 + +* fix unzip error handling + +# 0.14.6 / 2013-05-23 + +* fix HEAD unzip bug + +# 0.14.5 / 2013-05-23 + +* add flag to ensure the callback is **never** invoked twice + +# 0.14.4 / 2013-05-22 + +* add superagent.js build output +* update qs +* update emitter-component +* revert "add browser field to support browserify" see [GH-221](https://github.com/visionmedia/superagent/issues/221) + +# 0.14.3 / 2013-05-18 + +* add browser field to support browserify + +# 0.14.2/ 2013-05-07 + +* add host object check to fix serialization of File/Blobs etc as json + +# 0.14.1 / 2013-04-09 + +* update qs + +# 0.14.0 / 2013-04-02 + +* add client-side basic auth +* fix retaining of .set() header field case + +# 0.13.0 / 2013-03-13 + +* add progress events to client +* add simple example +* add res.headers as alias of res.header for browser client +* add res.get(field) to node/client + +# 0.12.4 / 2013-02-11 + +* fix get content-type even if can't get other headers in firefox. fixes [#181](https://github.com/visionmedia/superagent/issues/181) + +# 0.12.3 / 2013-02-11 + +* add quick "progress" event support + +# 0.12.2 / 2013-02-04 + +* add test to check if response acts as a readable stream +* add ReadableStream in the Response prototype. +* add test to assert correct redirection when the host changes in the location header. +* add default Accept-Encoding. Closes [#155](https://github.com/visionmedia/superagent/issues/155) +* fix req.pipe() return value of original stream for node parity. Closes [#171](https://github.com/visionmedia/superagent/issues/171) +* remove the host header when cleaning headers to properly follow the redirection. + +# 0.12.1 / 2013-01-10 + +* add x-domain error handling + +# 0.12.0 / 2013-01-04 + +* add header persistence on redirects + +# 0.11.0 / 2013-01-02 + +* add .error Error object. Closes [#156](https://github.com/visionmedia/superagent/issues/156) +* add forcing of res.text removal for FF HEAD responses. Closes [#162](https://github.com/visionmedia/superagent/issues/162) +* add reduce component usage. Closes [#90](https://github.com/visionmedia/superagent/issues/90) +* move better-assert dep to development deps + +# 0.10.0 / 2012-11-14 + +* add req.timeout(ms) support for the client + +# 0.9.10 / 2012-11-14 + +* fix client-side .query(str) support + +# 0.9.9 / 2012-11-14 + +* add .parse(fn) support +* fix socket hangup with dates in querystring. Closes [#146](https://github.com/visionmedia/superagent/issues/146) +* fix socket hangup "error" event when a callback of arity 2 is provided + +# 0.9.8 / 2012-11-03 + +* add emission of error from `Request#callback()` +* add a better fix for nodes weird socket hang up error +* add PUT/POST/PATCH data support to client short-hand functions +* add .license property to component.json +* change client portion to build using component(1) +* fix GET body support [guille] + +# 0.9.7 / 2012-10-19 + +* fix `.buffer()` `res.text` when no parser matches + +# 0.9.6 / 2012-10-17 + +* change: use `this` when `window` is undefined +* update to new component spec [juliangruber] +* fix emission of "data" events for compressed responses without encoding. Closes [#125](https://github.com/visionmedia/superagent/issues/125) + +# 0.9.5 / 2012-10-01 + +* add field name to .attach() +* add text "parser" +* refactor isObject() +* remove wtf isFunction() helper + +# 0.9.4 / 2012-09-20 + +* fix `Buffer` responses [TooTallNate] +* fix `res.type` when a "type" param is present [TooTallNate] + +# 0.9.3 / 2012-09-18 + +* remove **GET** `.send()` == `.query()` special-case (**API** change !!!) + +# 0.9.2 / 2012-09-17 + +* add `.aborted` prop +* add `.abort()`. Closes [#115](https://github.com/visionmedia/superagent/issues/115) + +# 0.9.1 / 2012-09-07 + +* add `.forbidden` response property +* add component.json +* change emitter-component to 0.0.5 +* fix client-side tests + +# 0.9.0 / 2012-08-28 + +* add `.timeout(ms)`. Closes [#17](https://github.com/visionmedia/superagent/issues/17) + +# 0.8.2 / 2012-08-28 + +* fix pathname relative redirects. Closes [#112](https://github.com/visionmedia/superagent/issues/112) + +# 0.8.1 / 2012-08-21 + +* fix redirects when schema is specified + +# 0.8.0 / 2012-08-19 + +* add `res.buffered` flag +* add buffering of text/\*, json and forms only by default. Closes [#61](https://github.com/visionmedia/superagent/issues/61) +* add `.buffer(false)` cancellation +* add cookie jar support [hunterloftis] +* add agent functionality [hunterloftis] + +# 0.7.0 / 2012-08-03 + +* allow `query()` to be called after the internal `req` has been created [tootallnate] + +# 0.6.0 / 2012-07-17 + +* add `res.send('foo=bar')` default of "application/x-www-form-urlencoded" + +# 0.5.1 / 2012-07-16 + +* add "methods" dep +* add `.end()` arity check to node callbacks +* fix unzip support due to weird node internals + +# 0.5.0 / 2012-06-16 + +* Added "Link" response header field parsing, exposing `res.links` + +# 0.4.3 / 2012-06-15 + +* Added 303, 305 and 307 as redirect status codes [slaskis] +* Fixed passing an object as the url + +# 0.4.2 / 2012-06-02 + +* Added component support +* Fixed redirect data + +# 0.4.1 / 2012-04-13 + +* Added HTTP PATCH support +* Fixed: GET / HEAD when following redirects. Closes [#86](https://github.com/visionmedia/superagent/issues/86) +* Fixed Content-Length detection for multibyte chars + +# 0.4.0 / 2012-03-04 + +* Added `.head()` method [browser]. Closes [#78](https://github.com/visionmedia/superagent/issues/78) +* Added `make test-cov` support +* Added multipart request support. Closes [#11](https://github.com/visionmedia/superagent/issues/11) +* Added all methods that node supports. Closes [#71](https://github.com/visionmedia/superagent/issues/71) +* Added "response" event providing a Response object. Closes [#28](https://github.com/visionmedia/superagent/issues/28) +* Added `.query(obj)`. Closes [#59](https://github.com/visionmedia/superagent/issues/59) +* Added `res.type` (browser). Closes [#54](https://github.com/visionmedia/superagent/issues/54) +* Changed: default `res.body` and `res.files` to {} +* Fixed: port existing query-string fix (browser). Closes [#57](https://github.com/visionmedia/superagent/issues/57) + +# 0.3.0 / 2012-01-24 + +* Added deflate/gzip support [guillermo] +* Added `res.type` (Content-Type void of params) +* Added `res.statusCode` to mirror node +* Added `res.headers` to mirror node +* Changed: parsers take callbacks +* Fixed optional schema support. Closes [#49](https://github.com/visionmedia/superagent/issues/49) + +# 0.2.0 / 2012-01-05 + +* Added url auth support +* Added `.auth(username, password)` +* Added basic auth support [node]. Closes [#41](https://github.com/visionmedia/superagent/issues/41) +* Added `make test-docs` +* Added guillermo's EventEmitter. Closes [#16](https://github.com/visionmedia/superagent/issues/16) +* Removed `Request#data()` for SS, renamed to `send()` +* Removed `Request#data()` from client, renamed to `send()` +* Fixed array support. [browser] +* Fixed array support. Closes [#35](https://github.com/visionmedia/superagent/issues/35) [node] +* Fixed `EventEmitter#emit()` + +# 0.1.3 / 2011-10-25 + +* Added error to callback +* Bumped node dep for 0.5.x + +# 0.1.2 / 2011-09-24 + +* Added markdown documentation +* Added `request(url[, fn])` support to the client +* Added `qs` dependency to package.json +* Added options for `Request#pipe()` +* Added support for `request(url, callback)` +* Added `request(url)` as shortcut for `request.get(url)` +* Added `Request#pipe(stream)` +* Added inherit from `Stream` +* Added multipart support +* Added ssl support (node) +* Removed Content-Length field from client +* Fixed buffering, `setEncoding()` to utf8 [reported by stagas] +* Fixed "end" event when piping + +# 0.1.1 / 2011-08-20 + +* Added `res.redirect` flag (node) +* Added redirect support (node) +* Added `Request#redirects(n)` (node) +* Added `.set(object)` header field support +* Fixed `Content-Length` support + +# 0.1.0 / 2011-08-09 + +* Added support for multiple calls to `.data()` +* Added support for `.get(uri, obj)` +* Added GET `.data()` querystring support +* Added IE{6,7,8} support [alexyoung] + +# 0.0.1 / 2011-08-05 + +* Initial commit + + + diff --git a/node_modules/superagent/LICENSE b/node_modules/superagent/LICENSE new file mode 100644 index 000000000..1b188ba5d --- /dev/null +++ b/node_modules/superagent/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2016 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/superagent/Makefile b/node_modules/superagent/Makefile new file mode 100644 index 000000000..587aef12f --- /dev/null +++ b/node_modules/superagent/Makefile @@ -0,0 +1,60 @@ + +NODETESTS ?= test/*.js test/node/*.js +BROWSERTESTS ?= test/*.js test/client/*.js +REPORTER = spec + +test: + @if [ "x$(BROWSER)" = "x" ]; then make test-node; else make test-browser; fi + +test-node: + @NODE_ENV=test ./node_modules/.bin/mocha \ + --require should \ + --trace-warnings \ + --throw-deprecation \ + --reporter $(REPORTER) \ + --timeout 5000 \ + $(NODETESTS) + +test-node-http2: + @NODE_ENV=test HTTP2_TEST=1 node ./node_modules/.bin/mocha \ + --require should \ + --trace-warnings \ + --throw-deprecation \ + --reporter $(REPORTER) \ + --timeout 5000 \ + $(NODETESTS) + +test-cov: lib-cov + SUPERAGENT_COV=1 $(MAKE) test REPORTER=html-cov > coverage.html + +test-browser: + SAUCE_APPIUM_VERSION=1.7 ./node_modules/.bin/zuul -- $(BROWSERTESTS) + +test-browser-local: + ./node_modules/.bin/zuul --no-coverage --local 4000 -- $(BROWSERTESTS) + +lib-cov: + jscoverage lib lib-cov + +test-server: + @node test/server + +docs: index.html test-docs docs/index.md + +index.html: docs/index.md docs/head.html docs/tail.html + marked < $< \ + | cat docs/head.html - docs/tail.html \ + > $@ + +docclean: + rm -f index.html docs/test.html + +test-docs: docs/head.html docs/tail.html + make test REPORTER=doc \ + | cat docs/head.html - docs/tail.html \ + > docs/test.html + +clean: + rm -fr components + +.PHONY: test-cov test docs test-docs clean test-browser-local diff --git a/node_modules/superagent/README.md b/node_modules/superagent/README.md new file mode 100644 index 000000000..88246631c --- /dev/null +++ b/node_modules/superagent/README.md @@ -0,0 +1,266 @@ +# superagent + +[![build status](https://img.shields.io/travis/visionmedia/superagent.svg)](https://travis-ci.org/visionmedia/superagent) +[![code coverage](https://img.shields.io/codecov/c/github/visionmedia/superagent.svg)](https://codecov.io/gh/visionmedia/superagent) +[![code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo) +[![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier) +[![made with lass](https://img.shields.io/badge/made_with-lass-95CC28.svg)](https://lass.js.org) +[![license](https://img.shields.io/github/license/visionmedia/superagent.svg)](LICENSE) + +> Small progressive client-side HTTP request library, and Node.js module with the same API, supporting many high-level HTTP client features + + +## Table of Contents + +* [Install](#install) +* [Usage](#usage) + * [Node](#node) + * [Browser](#browser) +* [Supported Platforms](#supported-platforms) + * [Required Browser Features](#required-browser-features) +* [Plugins](#plugins) +* [Upgrading from previous versions](#upgrading-from-previous-versions) +* [Contributors](#contributors) +* [License](#license) + + +## Install + +[npm][]: + +```sh +npm install superagent +``` + +[yarn][]: + +```sh +yarn add superagent +``` + + +## Usage + +### Node + +```js +const superagent = require('superagent'); + +// callback +superagent + .post('/api/pet') + .send({ name: 'Manny', species: 'cat' }) // sends a JSON post body + .set('X-API-Key', 'foobar') + .set('accept', 'json') + .end((err, res) => { + // Calling the end function will send the request + }); + +// promise with then/catch +superagent.post('/api/pet').then(console.log).catch(console.error); + +// promise with async/await +(async () => { + try { + const res = await superagent.post('/api/pet'); + console.log(res); + } catch (err) { + console.error(err); + } +})(); +``` + +### Browser + +**The browser-ready, minified version of `superagent` is only 6 KB (minified and gzipped)!** + +Browser-ready versions of this module are available via [jsdelivr][], [unpkg][], and also in the `node_modules/superagent/dist` folder in downloads of the `superagent` package. + +> Note that we also provide unminified versions with `.js` instead of `.min.js` file extensions. + +#### VanillaJS + +This is the solution for you if you're just using ` + + + + +``` + +#### Bundler + +If you are using [browserify][], [webpack][], [rollup][], or another bundler, then you can follow the same usage as [Node](#node) above. + + +## Supported Platforms + +* Node: v6.x+ +* Browsers (see [.browserslistrc](.browserslistrc)): + + ```sh + npx browserslist + ``` + + ```sh + and_chr 71 + and_ff 64 + and_qq 1.2 + and_uc 11.8 + android 67 + android 4.4.3-4.4.4 + baidu 7.12 + bb 10 + bb 7 + chrome 73 + chrome 72 + chrome 71 + edge 18 + edge 17 + firefox 66 + firefox 65 + ie 11 + ie 10 + ie 9 + ie_mob 11 + ie_mob 10 + ios_saf 12.0-12.1 + ios_saf 11.3-11.4 + op_mini all + op_mob 46 + op_mob 12.1 + opera 58 + opera 57 + safari 12 + safari 11.1 + samsung 8.2 + samsung 7.2-7.4 + ``` + +### Required Browser Features + +We recommend using (specifically with the bundle mentioned in [VanillaJS](#vanillajs) above): + +```html + +``` + +* IE 9-10 requires a polyfill for `Promise`, `Array.from`, `Symbol`, `Object.getOwnPropertySymbols`, and `Object.setPrototypeOf` +* IE 9 requires a polyfill for `window.FormData` (we recommend [formdata-polyfill][]) + + +## Plugins + +SuperAgent is easily extended via plugins. + +```js +const nocache = require('superagent-no-cache'); +const superagent = require('superagent'); +const prefix = require('superagent-prefix')('/static'); + +superagent + .get('/some-url') + .query({ action: 'edit', city: 'London' }) // query string + .use(prefix) // Prefixes *only* this request + .use(nocache) // Prevents caching of *only* this request + .end((err, res) => { + // Do something + }); +``` + +Existing plugins: + +* [superagent-no-cache](https://github.com/johntron/superagent-no-cache) - prevents caching by including Cache-Control header +* [superagent-prefix](https://github.com/johntron/superagent-prefix) - prefixes absolute URLs (useful in test environment) +* [superagent-suffix](https://github.com/timneutkens1/superagent-suffix) - suffix URLs with a given path +* [superagent-mock](https://github.com/M6Web/superagent-mock) - simulate HTTP calls by returning data fixtures based on the requested URL +* [superagent-mocker](https://github.com/shuvalov-anton/superagent-mocker) — simulate REST API +* [superagent-cache](https://github.com/jpodwys/superagent-cache) - A global SuperAgent patch with built-in, flexible caching +* [superagent-cache-plugin](https://github.com/jpodwys/superagent-cache-plugin) - A SuperAgent plugin with built-in, flexible caching +* [superagent-jsonapify](https://github.com/alex94puchades/superagent-jsonapify) - A lightweight [json-api](http://jsonapi.org/format/) client addon for superagent +* [superagent-serializer](https://github.com/zzarcon/superagent-serializer) - Converts server payload into different cases +* [superagent-httpbackend](https://www.npmjs.com/package/superagent-httpbackend) - stub out requests using AngularJS' $httpBackend syntax +* [superagent-throttle](https://github.com/leviwheatcroft/superagent-throttle) - queues and intelligently throttles requests +* [superagent-charset](https://github.com/magicdawn/superagent-charset) - add charset support for node's SuperAgent +* [superagent-verbose-errors](https://github.com/jcoreio/superagent-verbose-errors) - include response body in error messages for failed requests +* [superagent-declare](https://github.com/damoclark/superagent-declare) - A simple [declarative](https://en.wikipedia.org/wiki/Declarative_programming) API for SuperAgent +* [superagent-node-http-timings](https://github.com/webuniverseio/superagent-node-http-timings) - measure http timings in node.js + +Please prefix your plugin with `superagent-*` so that it can easily be found by others. + +For SuperAgent extensions such as couchdb and oauth visit the [wiki](https://github.com/visionmedia/superagent/wiki). + + +## Upgrading from previous versions + +Our breaking changes are mostly in rarely used functionality and from stricter error handling. + +* [4.x to 5.x](https://github.com/visionmedia/superagent/releases/tag/v5.0.0): + * We've implemented the build setup of [Lass](https://lass.js.org) to simplify our stack and linting + * Unminified browserified build size has been reduced from 48KB to 20KB (via `tinyify` and the latest version of Babel using `@babel/preset-env` and `.browserslistrc`) + * Linting support has been added using `caniuse-lite` and `eslint-plugin-compat` + * We can now target what versions of Node we wish to support more easily using `.babelrc` +* [3.x to 4.x](https://github.com/visionmedia/superagent/releases/tag/v4.0.0-alpha.1): + * Ensure you're running Node 6 or later. We've dropped support for Node 4. + * We've started using ES6 and for compatibility with Internet Explorer you may need to use Babel. + * We suggest migrating from `.end()` callbacks to `.then()` or `await`. +* [2.x to 3.x](https://github.com/visionmedia/superagent/releases/tag/v3.0.0): + * Ensure you're running Node 4 or later. We've dropped support for Node 0.x. + * Test code that calls `.send()` multiple times. Invalid calls to `.send()` will now throw instead of sending garbage. +* [1.x to 2.x](https://github.com/visionmedia/superagent/releases/tag/v2.0.0): + * If you use `.parse()` in the _browser_ version, rename it to `.serialize()`. + * If you rely on `undefined` in query-string values being sent literally as the text "undefined", switch to checking for missing value instead. `?key=undefined` is now `?key` (without a value). + * If you use `.then()` in Internet Explorer, ensure that you have a polyfill that adds a global `Promise` object. +* 0.x to 1.x: + * Instead of 1-argument callback `.end(function(res){})` use `.then(res => {})`. + + +## Contributors + +| Name | +| ------------------- | +| **Kornel Lesiński** | +| **Peter Lyons** | +| **Hunter Loftis** | +| **Nick Baugh** | + + +## License + +[MIT](LICENSE) © TJ Holowaychuk + + +## + +[npm]: https://www.npmjs.com/ + +[yarn]: https://yarnpkg.com/ + +[formdata-polyfill]: https://www.npmjs.com/package/formdata-polyfill + +[jsdelivr]: https://www.jsdelivr.com/ + +[unpkg]: https://unpkg.com/ + +[browserify]: https://github.com/browserify/browserify + +[webpack]: https://github.com/webpack/webpack + +[rollup]: https://github.com/rollup/rollup diff --git a/node_modules/superagent/dist/superagent.js b/node_modules/superagent/dist/superagent.js new file mode 100644 index 000000000..6db6a19f4 --- /dev/null +++ b/node_modules/superagent/dist/superagent.js @@ -0,0 +1,2418 @@ +(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.superagent = 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 b) { + return 1; + } + + return 0; +} + +function deterministicStringify(obj, replacer, spacer) { + var tmp = deterministicDecirc(obj, '', [], undefined) || obj; + var res; + + if (replacerStack.length === 0) { + res = JSON.stringify(tmp, replacer, spacer); + } else { + res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer); + } + + while (arr.length !== 0) { + var part = arr.pop(); + + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]); + } else { + part[0][part[1]] = part[2]; + } + } + + return res; +} + +function deterministicDecirc(val, k, stack, parent) { + var i; + + if (_typeof(val) === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); + + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { + value: '[Circular]' + }); + arr.push([parent, k, val, propertyDescriptor]); + } else { + replacerStack.push([val, k]); + } + } else { + parent[k] = '[Circular]'; + arr.push([parent, k, val]); + } + + return; + } + } + + if (typeof val.toJSON === 'function') { + return; + } + + stack.push(val); // Optimize for Arrays. Big arrays could kill the performance otherwise! + + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + deterministicDecirc(val[i], i, stack, val); + } + } else { + // Create a temporary object in the required way + var tmp = {}; + var keys = Object.keys(val).sort(compareFunction); + + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + deterministicDecirc(val[key], key, stack, val); + tmp[key] = val[key]; + } + + if (parent !== undefined) { + arr.push([parent, k, val]); + parent[k] = tmp; + } else { + return tmp; + } + } + + stack.pop(); + } +} // wraps replacer function to handle values we couldn't replace +// and mark them as [Circular] + + +function replaceGetterValues(replacer) { + replacer = replacer !== undefined ? replacer : function (k, v) { + return v; + }; + return function (key, val) { + if (replacerStack.length > 0) { + for (var i = 0; i < replacerStack.length; i++) { + var part = replacerStack[i]; + + if (part[1] === key && part[0] === val) { + val = '[Circular]'; + replacerStack.splice(i, 1); + break; + } + } + } + + return replacer.call(this, key, val); + }; +} + +},{}],3:[function(require,module,exports){ +"use strict"; + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + +function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } + +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + +function Agent() { + this._defaults = []; +} + +['use', 'on', 'once', 'set', 'query', 'type', 'accept', 'auth', 'withCredentials', 'sortQuery', 'retry', 'ok', 'redirects', 'timeout', 'buffer', 'serialize', 'parse', 'ca', 'key', 'pfx', 'cert', 'disableTLSCerts'].forEach(function (fn) { + // Default setting for all requests from this agent + Agent.prototype[fn] = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + this._defaults.push({ + fn: fn, + args: args + }); + + return this; + }; +}); + +Agent.prototype._setDefaults = function (req) { + this._defaults.forEach(function (def) { + req[def.fn].apply(req, _toConsumableArray(def.args)); + }); +}; + +module.exports = Agent; + +},{}],4:[function(require,module,exports){ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Check if `obj` is an object. + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ +function isObject(obj) { + return obj !== null && _typeof(obj) === 'object'; +} + +module.exports = isObject; + +},{}],5:[function(require,module,exports){ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Root reference for iframes. + */ +var root; + +if (typeof window !== 'undefined') { + // Browser window + root = window; +} else if (typeof self === 'undefined') { + // Other environments + console.warn('Using browser-only version of superagent in non-browser environment'); + root = void 0; +} else { + // Web Worker + root = self; +} + +var Emitter = require('component-emitter'); + +var safeStringify = require('fast-safe-stringify'); + +var RequestBase = require('./request-base'); + +var isObject = require('./is-object'); + +var ResponseBase = require('./response-base'); + +var Agent = require('./agent-base'); +/** + * Noop. + */ + + +function noop() {} +/** + * Expose `request`. + */ + + +module.exports = function (method, url) { + // callback + if (typeof url === 'function') { + return new exports.Request('GET', method).end(url); + } // url first + + + if (arguments.length === 1) { + return new exports.Request('GET', method); + } + + return new exports.Request(method, url); +}; + +exports = module.exports; +var request = exports; +exports.Request = Request; +/** + * Determine XHR. + */ + +request.getXHR = function () { + if (root.XMLHttpRequest && (!root.location || root.location.protocol !== 'file:' || !root.ActiveXObject)) { + return new XMLHttpRequest(); + } + + try { + return new ActiveXObject('Microsoft.XMLHTTP'); + } catch (_unused) {} + + try { + return new ActiveXObject('Msxml2.XMLHTTP.6.0'); + } catch (_unused2) {} + + try { + return new ActiveXObject('Msxml2.XMLHTTP.3.0'); + } catch (_unused3) {} + + try { + return new ActiveXObject('Msxml2.XMLHTTP'); + } catch (_unused4) {} + + throw new Error('Browser-only version of superagent could not find XHR'); +}; +/** + * Removes leading and trailing whitespace, added to support IE. + * + * @param {String} s + * @return {String} + * @api private + */ + + +var trim = ''.trim ? function (s) { + return s.trim(); +} : function (s) { + return s.replace(/(^\s*|\s*$)/g, ''); +}; +/** + * Serialize the given `obj`. + * + * @param {Object} obj + * @return {String} + * @api private + */ + +function serialize(obj) { + if (!isObject(obj)) return obj; + var pairs = []; + + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) pushEncodedKeyValuePair(pairs, key, obj[key]); + } + + return pairs.join('&'); +} +/** + * Helps 'serialize' with serializing arrays. + * Mutates the pairs array. + * + * @param {Array} pairs + * @param {String} key + * @param {Mixed} val + */ + + +function pushEncodedKeyValuePair(pairs, key, val) { + if (val === undefined) return; + + if (val === null) { + pairs.push(encodeURI(key)); + return; + } + + if (Array.isArray(val)) { + val.forEach(function (v) { + pushEncodedKeyValuePair(pairs, key, v); + }); + } else if (isObject(val)) { + for (var subkey in val) { + if (Object.prototype.hasOwnProperty.call(val, subkey)) pushEncodedKeyValuePair(pairs, "".concat(key, "[").concat(subkey, "]"), val[subkey]); + } + } else { + pairs.push(encodeURI(key) + '=' + encodeURIComponent(val)); + } +} +/** + * Expose serialization method. + */ + + +request.serializeObject = serialize; +/** + * Parse the given x-www-form-urlencoded `str`. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function parseString(str) { + var obj = {}; + var pairs = str.split('&'); + var pair; + var pos; + + for (var i = 0, len = pairs.length; i < len; ++i) { + pair = pairs[i]; + pos = pair.indexOf('='); + + if (pos === -1) { + obj[decodeURIComponent(pair)] = ''; + } else { + obj[decodeURIComponent(pair.slice(0, pos))] = decodeURIComponent(pair.slice(pos + 1)); + } + } + + return obj; +} +/** + * Expose parser. + */ + + +request.parseString = parseString; +/** + * Default MIME type map. + * + * superagent.types.xml = 'application/xml'; + * + */ + +request.types = { + html: 'text/html', + json: 'application/json', + xml: 'text/xml', + urlencoded: 'application/x-www-form-urlencoded', + form: 'application/x-www-form-urlencoded', + 'form-data': 'application/x-www-form-urlencoded' +}; +/** + * Default serialization map. + * + * superagent.serialize['application/xml'] = function(obj){ + * return 'generated xml here'; + * }; + * + */ + +request.serialize = { + 'application/x-www-form-urlencoded': serialize, + 'application/json': safeStringify +}; +/** + * Default parsers. + * + * superagent.parse['application/xml'] = function(str){ + * return { object parsed from str }; + * }; + * + */ + +request.parse = { + 'application/x-www-form-urlencoded': parseString, + 'application/json': JSON.parse +}; +/** + * Parse the given header `str` into + * an object containing the mapped fields. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function parseHeader(str) { + var lines = str.split(/\r?\n/); + var fields = {}; + var index; + var line; + var field; + var val; + + for (var i = 0, len = lines.length; i < len; ++i) { + line = lines[i]; + index = line.indexOf(':'); + + if (index === -1) { + // could be empty line, just skip it + continue; + } + + field = line.slice(0, index).toLowerCase(); + val = trim(line.slice(index + 1)); + fields[field] = val; + } + + return fields; +} +/** + * Check if `mime` is json or has +json structured syntax suffix. + * + * @param {String} mime + * @return {Boolean} + * @api private + */ + + +function isJSON(mime) { + // should match /json or +json + // but not /json-seq + return /[/+]json($|[^-\w])/.test(mime); +} +/** + * Initialize a new `Response` with the given `xhr`. + * + * - set flags (.ok, .error, etc) + * - parse header + * + * Examples: + * + * Aliasing `superagent` as `request` is nice: + * + * request = superagent; + * + * We can use the promise-like API, or pass callbacks: + * + * request.get('/').end(function(res){}); + * request.get('/', function(res){}); + * + * Sending data can be chained: + * + * request + * .post('/user') + * .send({ name: 'tj' }) + * .end(function(res){}); + * + * Or passed to `.send()`: + * + * request + * .post('/user') + * .send({ name: 'tj' }, function(res){}); + * + * Or passed to `.post()`: + * + * request + * .post('/user', { name: 'tj' }) + * .end(function(res){}); + * + * Or further reduced to a single call for simple cases: + * + * request + * .post('/user', { name: 'tj' }, function(res){}); + * + * @param {XMLHTTPRequest} xhr + * @param {Object} options + * @api private + */ + + +function Response(req) { + this.req = req; + this.xhr = this.req.xhr; // responseText is accessible only if responseType is '' or 'text' and on older browsers + + this.text = this.req.method !== 'HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text') || typeof this.xhr.responseType === 'undefined' ? this.xhr.responseText : null; + this.statusText = this.req.xhr.statusText; + var status = this.xhr.status; // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + + if (status === 1223) { + status = 204; + } + + this._setStatusProperties(status); + + this.headers = parseHeader(this.xhr.getAllResponseHeaders()); + this.header = this.headers; // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but + // getResponseHeader still works. so we get content-type even if getting + // other headers fails. + + this.header['content-type'] = this.xhr.getResponseHeader('content-type'); + + this._setHeaderProperties(this.header); + + if (this.text === null && req._responseType) { + this.body = this.xhr.response; + } else { + this.body = this.req.method === 'HEAD' ? null : this._parseBody(this.text ? this.text : this.xhr.response); + } +} // eslint-disable-next-line new-cap + + +ResponseBase(Response.prototype); +/** + * Parse the given body `str`. + * + * Used for auto-parsing of bodies. Parsers + * are defined on the `superagent.parse` object. + * + * @param {String} str + * @return {Mixed} + * @api private + */ + +Response.prototype._parseBody = function (str) { + var parse = request.parse[this.type]; + + if (this.req._parser) { + return this.req._parser(this, str); + } + + if (!parse && isJSON(this.type)) { + parse = request.parse['application/json']; + } + + return parse && str && (str.length > 0 || str instanceof Object) ? parse(str) : null; +}; +/** + * Return an `Error` representative of this response. + * + * @return {Error} + * @api public + */ + + +Response.prototype.toError = function () { + var req = this.req; + var method = req.method; + var url = req.url; + var msg = "cannot ".concat(method, " ").concat(url, " (").concat(this.status, ")"); + var err = new Error(msg); + err.status = this.status; + err.method = method; + err.url = url; + return err; +}; +/** + * Expose `Response`. + */ + + +request.Response = Response; +/** + * Initialize a new `Request` with the given `method` and `url`. + * + * @param {String} method + * @param {String} url + * @api public + */ + +function Request(method, url) { + var self = this; + this._query = this._query || []; + this.method = method; + this.url = url; + this.header = {}; // preserves header name case + + this._header = {}; // coerces header names to lowercase + + this.on('end', function () { + var err = null; + var res = null; + + try { + res = new Response(self); + } catch (err_) { + err = new Error('Parser is unable to parse the response'); + err.parse = true; + err.original = err_; // issue #675: return the raw response if the response parsing fails + + if (self.xhr) { + // ie9 doesn't have 'response' property + err.rawResponse = typeof self.xhr.responseType === 'undefined' ? self.xhr.responseText : self.xhr.response; // issue #876: return the http status code if the response parsing fails + + err.status = self.xhr.status ? self.xhr.status : null; + err.statusCode = err.status; // backwards-compat only + } else { + err.rawResponse = null; + err.status = null; + } + + return self.callback(err); + } + + self.emit('response', res); + var new_err; + + try { + if (!self._isResponseOK(res)) { + new_err = new Error(res.statusText || res.text || 'Unsuccessful HTTP response'); + } + } catch (err_) { + new_err = err_; // ok() callback can throw + } // #1000 don't catch errors from the callback to avoid double calling it + + + if (new_err) { + new_err.original = err; + new_err.response = res; + new_err.status = res.status; + self.callback(new_err, res); + } else { + self.callback(null, res); + } + }); +} +/** + * Mixin `Emitter` and `RequestBase`. + */ +// eslint-disable-next-line new-cap + + +Emitter(Request.prototype); // eslint-disable-next-line new-cap + +RequestBase(Request.prototype); +/** + * Set Content-Type to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.xml = 'application/xml'; + * + * request.post('/') + * .type('xml') + * .send(xmlstring) + * .end(callback); + * + * request.post('/') + * .type('application/xml') + * .send(xmlstring) + * .end(callback); + * + * @param {String} type + * @return {Request} for chaining + * @api public + */ + +Request.prototype.type = function (type) { + this.set('Content-Type', request.types[type] || type); + return this; +}; +/** + * Set Accept to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.json = 'application/json'; + * + * request.get('/agent') + * .accept('json') + * .end(callback); + * + * request.get('/agent') + * .accept('application/json') + * .end(callback); + * + * @param {String} accept + * @return {Request} for chaining + * @api public + */ + + +Request.prototype.accept = function (type) { + this.set('Accept', request.types[type] || type); + return this; +}; +/** + * Set Authorization field value with `user` and `pass`. + * + * @param {String} user + * @param {String} [pass] optional in case of using 'bearer' as type + * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic') + * @return {Request} for chaining + * @api public + */ + + +Request.prototype.auth = function (user, pass, options) { + if (arguments.length === 1) pass = ''; + + if (_typeof(pass) === 'object' && pass !== null) { + // pass is optional and can be replaced with options + options = pass; + pass = ''; + } + + if (!options) { + options = { + type: typeof btoa === 'function' ? 'basic' : 'auto' + }; + } + + var encoder = function encoder(string) { + if (typeof btoa === 'function') { + return btoa(string); + } + + throw new Error('Cannot use basic auth, btoa is not a function'); + }; + + return this._auth(user, pass, options, encoder); +}; +/** + * Add query-string `val`. + * + * Examples: + * + * request.get('/shoes') + * .query('size=10') + * .query({ color: 'blue' }) + * + * @param {Object|String} val + * @return {Request} for chaining + * @api public + */ + + +Request.prototype.query = function (val) { + if (typeof val !== 'string') val = serialize(val); + if (val) this._query.push(val); + return this; +}; +/** + * Queue the given `file` as an attachment to the specified `field`, + * with optional `options` (or filename). + * + * ``` js + * request.post('/upload') + * .attach('content', new Blob(['hey!'], { type: "text/html"})) + * .end(callback); + * ``` + * + * @param {String} field + * @param {Blob|File} file + * @param {String|Object} options + * @return {Request} for chaining + * @api public + */ + + +Request.prototype.attach = function (field, file, options) { + if (file) { + if (this._data) { + throw new Error("superagent can't mix .send() and .attach()"); + } + + this._getFormData().append(field, file, options || file.name); + } + + return this; +}; + +Request.prototype._getFormData = function () { + if (!this._formData) { + this._formData = new root.FormData(); + } + + return this._formData; +}; +/** + * Invoke the callback with `err` and `res` + * and handle arity check. + * + * @param {Error} err + * @param {Response} res + * @api private + */ + + +Request.prototype.callback = function (err, res) { + if (this._shouldRetry(err, res)) { + return this._retry(); + } + + var fn = this._callback; + this.clearTimeout(); + + if (err) { + if (this._maxRetries) err.retries = this._retries - 1; + this.emit('error', err); + } + + fn(err, res); +}; +/** + * Invoke callback with x-domain error. + * + * @api private + */ + + +Request.prototype.crossDomainError = function () { + var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); + err.crossDomain = true; + err.status = this.status; + err.method = this.method; + err.url = this.url; + this.callback(err); +}; // This only warns, because the request is still likely to work + + +Request.prototype.agent = function () { + console.warn('This is not supported in browser version of superagent'); + return this; +}; + +Request.prototype.ca = Request.prototype.agent; +Request.prototype.buffer = Request.prototype.ca; // This throws, because it can't send/receive data as expected + +Request.prototype.write = function () { + throw new Error('Streaming is not supported in browser version of superagent'); +}; + +Request.prototype.pipe = Request.prototype.write; +/** + * Check if `obj` is a host object, + * we don't want to serialize these :) + * + * @param {Object} obj host object + * @return {Boolean} is a host object + * @api private + */ + +Request.prototype._isHost = function (obj) { + // Native objects stringify to [object File], [object Blob], [object FormData], etc. + return obj && _typeof(obj) === 'object' && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]'; +}; +/** + * Initiate request, invoking callback `fn(res)` + * with an instanceof `Response`. + * + * @param {Function} fn + * @return {Request} for chaining + * @api public + */ + + +Request.prototype.end = function (fn) { + if (this._endCalled) { + console.warn('Warning: .end() was called twice. This is not supported in superagent'); + } + + this._endCalled = true; // store callback + + this._callback = fn || noop; // querystring + + this._finalizeQueryString(); + + this._end(); +}; + +Request.prototype._setUploadTimeout = function () { + var self = this; // upload timeout it's wokrs only if deadline timeout is off + + if (this._uploadTimeout && !this._uploadTimeoutTimer) { + this._uploadTimeoutTimer = setTimeout(function () { + self._timeoutError('Upload timeout of ', self._uploadTimeout, 'ETIMEDOUT'); + }, this._uploadTimeout); + } +}; // eslint-disable-next-line complexity + + +Request.prototype._end = function () { + if (this._aborted) return this.callback(new Error('The request has been aborted even before .end() was called')); + var self = this; + this.xhr = request.getXHR(); + var xhr = this.xhr; + var data = this._formData || this._data; + + this._setTimeouts(); // state change + + + xhr.onreadystatechange = function () { + var readyState = xhr.readyState; + + if (readyState >= 2 && self._responseTimeoutTimer) { + clearTimeout(self._responseTimeoutTimer); + } + + if (readyState !== 4) { + return; + } // In IE9, reads to any property (e.g. status) off of an aborted XHR will + // result in the error "Could not complete the operation due to error c00c023f" + + + var status; + + try { + status = xhr.status; + } catch (_unused5) { + status = 0; + } + + if (!status) { + if (self.timedout || self._aborted) return; + return self.crossDomainError(); + } + + self.emit('end'); + }; // progress + + + var handleProgress = function handleProgress(direction, e) { + if (e.total > 0) { + e.percent = e.loaded / e.total * 100; + + if (e.percent === 100) { + clearTimeout(self._uploadTimeoutTimer); + } + } + + e.direction = direction; + self.emit('progress', e); + }; + + if (this.hasListeners('progress')) { + try { + xhr.addEventListener('progress', handleProgress.bind(null, 'download')); + + if (xhr.upload) { + xhr.upload.addEventListener('progress', handleProgress.bind(null, 'upload')); + } + } catch (_unused6) {// Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. + // Reported here: + // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context + } + } + + if (xhr.upload) { + this._setUploadTimeout(); + } // initiate request + + + try { + if (this.username && this.password) { + xhr.open(this.method, this.url, true, this.username, this.password); + } else { + xhr.open(this.method, this.url, true); + } + } catch (err) { + // see #1149 + return this.callback(err); + } // CORS + + + if (this._withCredentials) xhr.withCredentials = true; // body + + if (!this._formData && this.method !== 'GET' && this.method !== 'HEAD' && typeof data !== 'string' && !this._isHost(data)) { + // serialize stuff + var contentType = this._header['content-type']; + + var _serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : '']; + + if (!_serialize && isJSON(contentType)) { + _serialize = request.serialize['application/json']; + } + + if (_serialize) data = _serialize(data); + } // set header fields + + + for (var field in this.header) { + if (this.header[field] === null) continue; + if (Object.prototype.hasOwnProperty.call(this.header, field)) xhr.setRequestHeader(field, this.header[field]); + } + + if (this._responseType) { + xhr.responseType = this._responseType; + } // send stuff + + + this.emit('request', this); // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing) + // We need null here if data is undefined + + xhr.send(typeof data === 'undefined' ? null : data); +}; + +request.agent = function () { + return new Agent(); +}; + +['GET', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE'].forEach(function (method) { + Agent.prototype[method.toLowerCase()] = function (url, fn) { + var req = new request.Request(method, url); + + this._setDefaults(req); + + if (fn) { + req.end(fn); + } + + return req; + }; +}); +Agent.prototype.del = Agent.prototype.delete; +/** + * GET `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.get = function (url, data, fn) { + var req = request('GET', url); + + if (typeof data === 'function') { + fn = data; + data = null; + } + + if (data) req.query(data); + if (fn) req.end(fn); + return req; +}; +/** + * HEAD `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + + +request.head = function (url, data, fn) { + var req = request('HEAD', url); + + if (typeof data === 'function') { + fn = data; + data = null; + } + + if (data) req.query(data); + if (fn) req.end(fn); + return req; +}; +/** + * OPTIONS query to `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + + +request.options = function (url, data, fn) { + var req = request('OPTIONS', url); + + if (typeof data === 'function') { + fn = data; + data = null; + } + + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; +/** + * DELETE `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + + +function del(url, data, fn) { + var req = request('DELETE', url); + + if (typeof data === 'function') { + fn = data; + data = null; + } + + if (data) req.send(data); + if (fn) req.end(fn); + return req; +} + +request.del = del; +request.delete = del; +/** + * PATCH `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.patch = function (url, data, fn) { + var req = request('PATCH', url); + + if (typeof data === 'function') { + fn = data; + data = null; + } + + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; +/** + * POST `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + + +request.post = function (url, data, fn) { + var req = request('POST', url); + + if (typeof data === 'function') { + fn = data; + data = null; + } + + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; +/** + * PUT `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + + +request.put = function (url, data, fn) { + var req = request('PUT', url); + + if (typeof data === 'function') { + fn = data; + data = null; + } + + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +},{"./agent-base":3,"./is-object":4,"./request-base":6,"./response-base":7,"component-emitter":1,"fast-safe-stringify":2}],6:[function(require,module,exports){ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Module of mixed-in functions shared between node and client code + */ +var isObject = require('./is-object'); +/** + * Expose `RequestBase`. + */ + + +module.exports = RequestBase; +/** + * Initialize a new `RequestBase`. + * + * @api public + */ + +function RequestBase(obj) { + if (obj) return mixin(obj); +} +/** + * Mixin the prototype properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + + +function mixin(obj) { + for (var key in RequestBase.prototype) { + if (Object.prototype.hasOwnProperty.call(RequestBase.prototype, key)) obj[key] = RequestBase.prototype[key]; + } + + return obj; +} +/** + * Clear previous timeout. + * + * @return {Request} for chaining + * @api public + */ + + +RequestBase.prototype.clearTimeout = function () { + clearTimeout(this._timer); + clearTimeout(this._responseTimeoutTimer); + clearTimeout(this._uploadTimeoutTimer); + delete this._timer; + delete this._responseTimeoutTimer; + delete this._uploadTimeoutTimer; + return this; +}; +/** + * Override default response body parser + * + * This function will be called to convert incoming data into request.body + * + * @param {Function} + * @api public + */ + + +RequestBase.prototype.parse = function (fn) { + this._parser = fn; + return this; +}; +/** + * Set format of binary response body. + * In browser valid formats are 'blob' and 'arraybuffer', + * which return Blob and ArrayBuffer, respectively. + * + * In Node all values result in Buffer. + * + * Examples: + * + * req.get('/') + * .responseType('blob') + * .end(callback); + * + * @param {String} val + * @return {Request} for chaining + * @api public + */ + + +RequestBase.prototype.responseType = function (val) { + this._responseType = val; + return this; +}; +/** + * Override default request body serializer + * + * This function will be called to convert data set via .send or .attach into payload to send + * + * @param {Function} + * @api public + */ + + +RequestBase.prototype.serialize = function (fn) { + this._serializer = fn; + return this; +}; +/** + * Set timeouts. + * + * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time. + * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections. + * - upload is the time since last bit of data was sent or received. This timeout works only if deadline timeout is off + * + * Value of 0 or false means no timeout. + * + * @param {Number|Object} ms or {response, deadline} + * @return {Request} for chaining + * @api public + */ + + +RequestBase.prototype.timeout = function (options) { + if (!options || _typeof(options) !== 'object') { + this._timeout = options; + this._responseTimeout = 0; + this._uploadTimeout = 0; + return this; + } + + for (var option in options) { + if (Object.prototype.hasOwnProperty.call(options, option)) { + switch (option) { + case 'deadline': + this._timeout = options.deadline; + break; + + case 'response': + this._responseTimeout = options.response; + break; + + case 'upload': + this._uploadTimeout = options.upload; + break; + + default: + console.warn('Unknown timeout option', option); + } + } + } + + return this; +}; +/** + * Set number of retry attempts on error. + * + * Failed requests will be retried 'count' times if timeout or err.code >= 500. + * + * @param {Number} count + * @param {Function} [fn] + * @return {Request} for chaining + * @api public + */ + + +RequestBase.prototype.retry = function (count, fn) { + // Default to 1 if no count passed or true + if (arguments.length === 0 || count === true) count = 1; + if (count <= 0) count = 0; + this._maxRetries = count; + this._retries = 0; + this._retryCallback = fn; + return this; +}; + +var ERROR_CODES = ['ECONNRESET', 'ETIMEDOUT', 'EADDRINFO', 'ESOCKETTIMEDOUT']; +/** + * Determine if a request should be retried. + * (Borrowed from segmentio/superagent-retry) + * + * @param {Error} err an error + * @param {Response} [res] response + * @returns {Boolean} if segment should be retried + */ + +RequestBase.prototype._shouldRetry = function (err, res) { + if (!this._maxRetries || this._retries++ >= this._maxRetries) { + return false; + } + + if (this._retryCallback) { + try { + var override = this._retryCallback(err, res); + + if (override === true) return true; + if (override === false) return false; // undefined falls back to defaults + } catch (err_) { + console.error(err_); + } + } + + if (res && res.status && res.status >= 500 && res.status !== 501) return true; + + if (err) { + if (err.code && ERROR_CODES.includes(err.code)) return true; // Superagent timeout + + if (err.timeout && err.code === 'ECONNABORTED') return true; + if (err.crossDomain) return true; + } + + return false; +}; +/** + * Retry request + * + * @return {Request} for chaining + * @api private + */ + + +RequestBase.prototype._retry = function () { + this.clearTimeout(); // node + + if (this.req) { + this.req = null; + this.req = this.request(); + } + + this._aborted = false; + this.timedout = false; + this.timedoutError = null; + return this._end(); +}; +/** + * Promise support + * + * @param {Function} resolve + * @param {Function} [reject] + * @return {Request} + */ + + +RequestBase.prototype.then = function (resolve, reject) { + var _this = this; + + if (!this._fullfilledPromise) { + var self = this; + + if (this._endCalled) { + console.warn('Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises'); + } + + this._fullfilledPromise = new Promise(function (resolve, reject) { + self.on('abort', function () { + if (_this._maxRetries && _this._maxRetries > _this._retries) { + return; + } + + if (_this.timedout && _this.timedoutError) { + reject(_this.timedoutError); + return; + } + + var err = new Error('Aborted'); + err.code = 'ABORTED'; + err.status = _this.status; + err.method = _this.method; + err.url = _this.url; + reject(err); + }); + self.end(function (err, res) { + if (err) reject(err);else resolve(res); + }); + }); + } + + return this._fullfilledPromise.then(resolve, reject); +}; + +RequestBase.prototype.catch = function (cb) { + return this.then(undefined, cb); +}; +/** + * Allow for extension + */ + + +RequestBase.prototype.use = function (fn) { + fn(this); + return this; +}; + +RequestBase.prototype.ok = function (cb) { + if (typeof cb !== 'function') throw new Error('Callback required'); + this._okCallback = cb; + return this; +}; + +RequestBase.prototype._isResponseOK = function (res) { + if (!res) { + return false; + } + + if (this._okCallback) { + return this._okCallback(res); + } + + return res.status >= 200 && res.status < 300; +}; +/** + * Get request header `field`. + * Case-insensitive. + * + * @param {String} field + * @return {String} + * @api public + */ + + +RequestBase.prototype.get = function (field) { + return this._header[field.toLowerCase()]; +}; +/** + * Get case-insensitive header `field` value. + * This is a deprecated internal API. Use `.get(field)` instead. + * + * (getHeader is no longer used internally by the superagent code base) + * + * @param {String} field + * @return {String} + * @api private + * @deprecated + */ + + +RequestBase.prototype.getHeader = RequestBase.prototype.get; +/** + * Set header `field` to `val`, or multiple fields with one object. + * Case-insensitive. + * + * Examples: + * + * req.get('/') + * .set('Accept', 'application/json') + * .set('X-API-Key', 'foobar') + * .end(callback); + * + * req.get('/') + * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) + * .end(callback); + * + * @param {String|Object} field + * @param {String} val + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.set = function (field, val) { + if (isObject(field)) { + for (var key in field) { + if (Object.prototype.hasOwnProperty.call(field, key)) this.set(key, field[key]); + } + + return this; + } + + this._header[field.toLowerCase()] = val; + this.header[field] = val; + return this; +}; +/** + * Remove header `field`. + * Case-insensitive. + * + * Example: + * + * req.get('/') + * .unset('User-Agent') + * .end(callback); + * + * @param {String} field field name + */ + + +RequestBase.prototype.unset = function (field) { + delete this._header[field.toLowerCase()]; + delete this.header[field]; + return this; +}; +/** + * Write the field `name` and `val`, or multiple fields with one object + * for "multipart/form-data" request bodies. + * + * ``` js + * request.post('/upload') + * .field('foo', 'bar') + * .end(callback); + * + * request.post('/upload') + * .field({ foo: 'bar', baz: 'qux' }) + * .end(callback); + * ``` + * + * @param {String|Object} name name of field + * @param {String|Blob|File|Buffer|fs.ReadStream} val value of field + * @return {Request} for chaining + * @api public + */ + + +RequestBase.prototype.field = function (name, val) { + // name should be either a string or an object. + if (name === null || undefined === name) { + throw new Error('.field(name, val) name can not be empty'); + } + + if (this._data) { + throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()"); + } + + if (isObject(name)) { + for (var key in name) { + if (Object.prototype.hasOwnProperty.call(name, key)) this.field(key, name[key]); + } + + return this; + } + + if (Array.isArray(val)) { + for (var i in val) { + if (Object.prototype.hasOwnProperty.call(val, i)) this.field(name, val[i]); + } + + return this; + } // val should be defined now + + + if (val === null || undefined === val) { + throw new Error('.field(name, val) val can not be empty'); + } + + if (typeof val === 'boolean') { + val = String(val); + } + + this._getFormData().append(name, val); + + return this; +}; +/** + * Abort the request, and clear potential timeout. + * + * @return {Request} request + * @api public + */ + + +RequestBase.prototype.abort = function () { + if (this._aborted) { + return this; + } + + this._aborted = true; + if (this.xhr) this.xhr.abort(); // browser + + if (this.req) this.req.abort(); // node + + this.clearTimeout(); + this.emit('abort'); + return this; +}; + +RequestBase.prototype._auth = function (user, pass, options, base64Encoder) { + switch (options.type) { + case 'basic': + this.set('Authorization', "Basic ".concat(base64Encoder("".concat(user, ":").concat(pass)))); + break; + + case 'auto': + this.username = user; + this.password = pass; + break; + + case 'bearer': + // usage would be .auth(accessToken, { type: 'bearer' }) + this.set('Authorization', "Bearer ".concat(user)); + break; + + default: + break; + } + + return this; +}; +/** + * Enable transmission of cookies with x-domain requests. + * + * Note that for this to work the origin must not be + * using "Access-Control-Allow-Origin" with a wildcard, + * and also must set "Access-Control-Allow-Credentials" + * to "true". + * + * @api public + */ + + +RequestBase.prototype.withCredentials = function (on) { + // This is browser-only functionality. Node side is no-op. + if (on === undefined) on = true; + this._withCredentials = on; + return this; +}; +/** + * Set the max redirects to `n`. Does nothing in browser XHR implementation. + * + * @param {Number} n + * @return {Request} for chaining + * @api public + */ + + +RequestBase.prototype.redirects = function (n) { + this._maxRedirects = n; + return this; +}; +/** + * Maximum size of buffered response body, in bytes. Counts uncompressed size. + * Default 200MB. + * + * @param {Number} n number of bytes + * @return {Request} for chaining + */ + + +RequestBase.prototype.maxResponseSize = function (n) { + if (typeof n !== 'number') { + throw new TypeError('Invalid argument'); + } + + this._maxResponseSize = n; + return this; +}; +/** + * Convert to a plain javascript object (not JSON string) of scalar properties. + * Note as this method is designed to return a useful non-this value, + * it cannot be chained. + * + * @return {Object} describing method, url, and data of this request + * @api public + */ + + +RequestBase.prototype.toJSON = function () { + return { + method: this.method, + url: this.url, + data: this._data, + headers: this._header + }; +}; +/** + * Send `data` as the request body, defaulting the `.type()` to "json" when + * an object is given. + * + * Examples: + * + * // manual json + * request.post('/user') + * .type('json') + * .send('{"name":"tj"}') + * .end(callback) + * + * // auto json + * request.post('/user') + * .send({ name: 'tj' }) + * .end(callback) + * + * // manual x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send('name=tj') + * .end(callback) + * + * // auto x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send({ name: 'tj' }) + * .end(callback) + * + * // defaults to x-www-form-urlencoded + * request.post('/user') + * .send('name=tobi') + * .send('species=ferret') + * .end(callback) + * + * @param {String|Object} data + * @return {Request} for chaining + * @api public + */ +// eslint-disable-next-line complexity + + +RequestBase.prototype.send = function (data) { + var isObj = isObject(data); + var type = this._header['content-type']; + + if (this._formData) { + throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()"); + } + + if (isObj && !this._data) { + if (Array.isArray(data)) { + this._data = []; + } else if (!this._isHost(data)) { + this._data = {}; + } + } else if (data && this._data && this._isHost(this._data)) { + throw new Error("Can't merge these send calls"); + } // merge + + + if (isObj && isObject(this._data)) { + for (var key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) this._data[key] = data[key]; + } + } else if (typeof data === 'string') { + // default to x-www-form-urlencoded + if (!type) this.type('form'); + type = this._header['content-type']; + + if (type === 'application/x-www-form-urlencoded') { + this._data = this._data ? "".concat(this._data, "&").concat(data) : data; + } else { + this._data = (this._data || '') + data; + } + } else { + this._data = data; + } + + if (!isObj || this._isHost(data)) { + return this; + } // default to json + + + if (!type) this.type('json'); + return this; +}; +/** + * Sort `querystring` by the sort function + * + * + * Examples: + * + * // default order + * request.get('/user') + * .query('name=Nick') + * .query('search=Manny') + * .sortQuery() + * .end(callback) + * + * // customized sort function + * request.get('/user') + * .query('name=Nick') + * .query('search=Manny') + * .sortQuery(function(a, b){ + * return a.length - b.length; + * }) + * .end(callback) + * + * + * @param {Function} sort + * @return {Request} for chaining + * @api public + */ + + +RequestBase.prototype.sortQuery = function (sort) { + // _sort default to true but otherwise can be a function or boolean + this._sort = typeof sort === 'undefined' ? true : sort; + return this; +}; +/** + * Compose querystring to append to req.url + * + * @api private + */ + + +RequestBase.prototype._finalizeQueryString = function () { + var query = this._query.join('&'); + + if (query) { + this.url += (this.url.includes('?') ? '&' : '?') + query; + } + + this._query.length = 0; // Makes the call idempotent + + if (this._sort) { + var index = this.url.indexOf('?'); + + if (index >= 0) { + var queryArr = this.url.slice(index + 1).split('&'); + + if (typeof this._sort === 'function') { + queryArr.sort(this._sort); + } else { + queryArr.sort(); + } + + this.url = this.url.slice(0, index) + '?' + queryArr.join('&'); + } + } +}; // For backwards compat only + + +RequestBase.prototype._appendQueryString = function () { + console.warn('Unsupported'); +}; +/** + * Invoke callback with timeout error. + * + * @api private + */ + + +RequestBase.prototype._timeoutError = function (reason, timeout, errno) { + if (this._aborted) { + return; + } + + var err = new Error("".concat(reason + timeout, "ms exceeded")); + err.timeout = timeout; + err.code = 'ECONNABORTED'; + err.errno = errno; + this.timedout = true; + this.timedoutError = err; + this.abort(); + this.callback(err); +}; + +RequestBase.prototype._setTimeouts = function () { + var self = this; // deadline + + if (this._timeout && !this._timer) { + this._timer = setTimeout(function () { + self._timeoutError('Timeout of ', self._timeout, 'ETIME'); + }, this._timeout); + } // response timeout + + + if (this._responseTimeout && !this._responseTimeoutTimer) { + this._responseTimeoutTimer = setTimeout(function () { + self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT'); + }, this._responseTimeout); + } +}; + +},{"./is-object":4}],7:[function(require,module,exports){ +"use strict"; + +/** + * Module dependencies. + */ +var utils = require('./utils'); +/** + * Expose `ResponseBase`. + */ + + +module.exports = ResponseBase; +/** + * Initialize a new `ResponseBase`. + * + * @api public + */ + +function ResponseBase(obj) { + if (obj) return mixin(obj); +} +/** + * Mixin the prototype properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + + +function mixin(obj) { + for (var key in ResponseBase.prototype) { + if (Object.prototype.hasOwnProperty.call(ResponseBase.prototype, key)) obj[key] = ResponseBase.prototype[key]; + } + + return obj; +} +/** + * Get case-insensitive `field` value. + * + * @param {String} field + * @return {String} + * @api public + */ + + +ResponseBase.prototype.get = function (field) { + return this.header[field.toLowerCase()]; +}; +/** + * Set header related properties: + * + * - `.type` the content type without params + * + * A response of "Content-Type: text/plain; charset=utf-8" + * will provide you with a `.type` of "text/plain". + * + * @param {Object} header + * @api private + */ + + +ResponseBase.prototype._setHeaderProperties = function (header) { + // TODO: moar! + // TODO: make this a util + // content-type + var ct = header['content-type'] || ''; + this.type = utils.type(ct); // params + + var params = utils.params(ct); + + for (var key in params) { + if (Object.prototype.hasOwnProperty.call(params, key)) this[key] = params[key]; + } + + this.links = {}; // links + + try { + if (header.link) { + this.links = utils.parseLinks(header.link); + } + } catch (_unused) {// ignore + } +}; +/** + * Set flags such as `.ok` based on `status`. + * + * For example a 2xx response will give you a `.ok` of __true__ + * whereas 5xx will be __false__ and `.error` will be __true__. The + * `.clientError` and `.serverError` are also available to be more + * specific, and `.statusType` is the class of error ranging from 1..5 + * sometimes useful for mapping respond colors etc. + * + * "sugar" properties are also defined for common cases. Currently providing: + * + * - .noContent + * - .badRequest + * - .unauthorized + * - .notAcceptable + * - .notFound + * + * @param {Number} status + * @api private + */ + + +ResponseBase.prototype._setStatusProperties = function (status) { + var type = status / 100 | 0; // status / class + + this.statusCode = status; + this.status = this.statusCode; + this.statusType = type; // basics + + this.info = type === 1; + this.ok = type === 2; + this.redirect = type === 3; + this.clientError = type === 4; + this.serverError = type === 5; + this.error = type === 4 || type === 5 ? this.toError() : false; // sugar + + this.created = status === 201; + this.accepted = status === 202; + this.noContent = status === 204; + this.badRequest = status === 400; + this.unauthorized = status === 401; + this.notAcceptable = status === 406; + this.forbidden = status === 403; + this.notFound = status === 404; + this.unprocessableEntity = status === 422; +}; + +},{"./utils":8}],8:[function(require,module,exports){ +"use strict"; + +/** + * Return the mime type for the given `str`. + * + * @param {String} str + * @return {String} + * @api private + */ +exports.type = function (str) { + return str.split(/ *; */).shift(); +}; +/** + * Return header field parameters. + * + * @param {String} str + * @return {Object} + * @api private + */ + + +exports.params = function (str) { + return str.split(/ *; */).reduce(function (obj, str) { + var parts = str.split(/ *= */); + var key = parts.shift(); + var val = parts.shift(); + if (key && val) obj[key] = val; + return obj; + }, {}); +}; +/** + * Parse Link header fields. + * + * @param {String} str + * @return {Object} + * @api private + */ + + +exports.parseLinks = function (str) { + return str.split(/ *, */).reduce(function (obj, str) { + var parts = str.split(/ *; */); + var url = parts[0].slice(1, -1); + var rel = parts[1].split(/ *= */)[1].slice(1, -1); + obj[rel] = url; + return obj; + }, {}); +}; +/** + * Strip content related fields from `header`. + * + * @param {Object} header + * @return {Object} header + * @api private + */ + + +exports.cleanHeader = function (header, changesOrigin) { + delete header['content-type']; + delete header['content-length']; + delete header['transfer-encoding']; + delete header.host; // secuirty + + if (changesOrigin) { + delete header.authorization; + delete header.cookie; + } + + return header; +}; + +},{}]},{},[5])(5) +}); diff --git a/node_modules/superagent/dist/superagent.min.js b/node_modules/superagent/dist/superagent.min.js new file mode 100644 index 000000000..a11497c4a --- /dev/null +++ b/node_modules/superagent/dist/superagent.min.js @@ -0,0 +1 @@ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).superagent=t()}}(function(){var t={exports:{}};function e(t){if(t)return function(t){for(var r in e.prototype)t[r]=e.prototype[r];return t}(t)}t.exports=e,e.prototype.on=e.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},e.prototype.once=function(t,e){function r(){this.off(t,r),e.apply(this,arguments)}return r.fn=e,this.on(t,r),this},e.prototype.off=e.prototype.removeListener=e.prototype.removeAllListeners=e.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,o=this._callbacks["$"+t];if(!o)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var n=0;ne?1:0}function u(t,e,r){var s,u=function t(e,r,s,u){var p;if("object"==o(e)&&null!==e){for(p=0;p0)for(var o=0;o=this._maxRetries)return!1;if(this._retryCallback)try{var r=this._retryCallback(t,e);if(!0===r)return!0;if(!1===r)return!1}catch(o){console.error(o)}if(e&&e.status&&e.status>=500&&501!==e.status)return!0;if(t){if(t.code&&y.includes(t.code))return!0;if(t.timeout&&"ECONNABORTED"===t.code)return!0;if(t.crossDomain)return!0}return!1},d.prototype._retry=function(){return this.clearTimeout(),this.req&&(this.req=null,this.req=this.request()),this._aborted=!1,this.timedout=!1,this.timedoutError=null,this._end()},d.prototype.then=function(t,e){var r=this;if(!this._fullfilledPromise){var o=this;this._endCalled&&console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises"),this._fullfilledPromise=new Promise(function(t,e){o.on("abort",function(){if(!(r._maxRetries&&r._maxRetries>r._retries))if(r.timedout&&r.timedoutError)e(r.timedoutError);else{var t=new Error("Aborted");t.code="ABORTED",t.status=r.status,t.method=r.method,t.url=r.url,e(t)}}),o.end(function(r,o){r?e(r):t(o)})})}return this._fullfilledPromise.then(t,e)},d.prototype.catch=function(t){return this.then(void 0,t)},d.prototype.use=function(t){return t(this),this},d.prototype.ok=function(t){if("function"!=typeof t)throw new Error("Callback required");return this._okCallback=t,this},d.prototype._isResponseOK=function(t){return!!t&&(this._okCallback?this._okCallback(t):t.status>=200&&t.status<300)},d.prototype.get=function(t){return this._header[t.toLowerCase()]},d.prototype.getHeader=d.prototype.get,d.prototype.set=function(t,e){if(c(t)){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&this.set(r,t[r]);return this}return this._header[t.toLowerCase()]=e,this.header[t]=e,this},d.prototype.unset=function(t){return delete this._header[t.toLowerCase()],delete this.header[t],this},d.prototype.field=function(t,e){if(null==t)throw new Error(".field(name, val) name can not be empty");if(this._data)throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()");if(c(t)){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&this.field(r,t[r]);return this}if(Array.isArray(e)){for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&this.field(t,e[o]);return this}if(null==e)throw new Error(".field(name, val) val can not be empty");return"boolean"==typeof e&&(e=String(e)),this._getFormData().append(t,e),this},d.prototype.abort=function(){return this._aborted?this:(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req&&this.req.abort(),this.clearTimeout(),this.emit("abort"),this)},d.prototype._auth=function(t,e,r,o){switch(r.type){case"basic":this.set("Authorization","Basic ".concat(o("".concat(t,":").concat(e))));break;case"auto":this.username=t,this.password=e;break;case"bearer":this.set("Authorization","Bearer ".concat(t))}return this},d.prototype.withCredentials=function(t){return void 0===t&&(t=!0),this._withCredentials=t,this},d.prototype.redirects=function(t){return this._maxRedirects=t,this},d.prototype.maxResponseSize=function(t){if("number"!=typeof t)throw new TypeError("Invalid argument");return this._maxResponseSize=t,this},d.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},d.prototype.send=function(t){var e=c(t),r=this._header["content-type"];if(this._formData)throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()");if(e&&!this._data)Array.isArray(t)?this._data=[]:this._isHost(t)||(this._data={});else if(t&&this._data&&this._isHost(this._data))throw new Error("Can't merge these send calls");if(e&&c(this._data))for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(this._data[o]=t[o]);else"string"==typeof t?(r||this.type("form"),r=this._header["content-type"],this._data="application/x-www-form-urlencoded"===r?this._data?"".concat(this._data,"&").concat(t):t:(this._data||"")+t):this._data=t;return!e||this._isHost(t)?this:(r||this.type("json"),this)},d.prototype.sortQuery=function(t){return this._sort=void 0===t||t,this},d.prototype._finalizeQueryString=function(){var t=this._query.join("&");if(t&&(this.url+=(this.url.includes("?")?"&":"?")+t),this._query.length=0,this._sort){var e=this.url.indexOf("?");if(e>=0){var r=this.url.slice(e+1).split("&");"function"==typeof this._sort?r.sort(this._sort):r.sort(),this.url=this.url.slice(0,e)+"?"+r.join("&")}}},d.prototype._appendQueryString=function(){console.warn("Unsupported")},d.prototype._timeoutError=function(t,e,r){if(!this._aborted){var o=new Error("".concat(t+e,"ms exceeded"));o.timeout=e,o.code="ECONNABORTED",o.errno=r,this.timedout=!0,this.timedoutError=o,this.abort(),this.callback(o)}},d.prototype._setTimeouts=function(){var t=this;this._timeout&&!this._timer&&(this._timer=setTimeout(function(){t._timeoutError("Timeout of ",t._timeout,"ETIME")},this._timeout)),this._responseTimeout&&!this._responseTimeoutTimer&&(this._responseTimeoutTimer=setTimeout(function(){t._timeoutError("Response timeout of ",t._responseTimeout,"ETIMEDOUT")},this._responseTimeout))};var m={type:function(t){return t.split(/ *; */).shift()},params:function(t){return t.split(/ *; */).reduce(function(t,e){var r=e.split(/ *= */),o=r.shift(),n=r.shift();return o&&n&&(t[o]=n),t},{})},parseLinks:function(t){return t.split(/ *, */).reduce(function(t,e){var r=e.split(/ *; */),o=r[0].slice(1,-1);return t[r[1].split(/ *= */)[1].slice(1,-1)]=o,t},{})}},b={};function _(t){if(t)return function(t){for(var e in _.prototype)Object.prototype.hasOwnProperty.call(_.prototype,e)&&(t[e]=_.prototype[e]);return t}(t)}b=_,_.prototype.get=function(t){return this.header[t.toLowerCase()]},_.prototype._setHeaderProperties=function(t){var e=t["content-type"]||"";this.type=m.type(e);var r=m.params(e);for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(this[o]=r[o]);this.links={};try{t.link&&(this.links=m.parseLinks(t.link))}catch(n){}},_.prototype._setStatusProperties=function(t){var e=t/100|0;this.statusCode=t,this.status=this.statusCode,this.statusType=e,this.info=1===e,this.ok=2===e,this.redirect=3===e,this.clientError=4===e,this.serverError=5===e,this.error=(4===e||5===e)&&this.toError(),this.created=201===t,this.accepted=202===t,this.noContent=204===t,this.badRequest=400===t,this.unauthorized=401===t,this.notAcceptable=406===t,this.forbidden=403===t,this.notFound=404===t,this.unprocessableEntity=422===t};var w={};function v(t){return function(t){if(Array.isArray(t))return T(t)}(t)||function(t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t))return Array.from(t)}(t)||function(t,e){if(!t)return;if("string"==typeof t)return T(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);"Object"===r&&t.constructor&&(r=t.constructor.name);if("Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return T(t,e)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function T(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,o=new Array(e);r0||t instanceof Object)?e(t):null)},q.prototype.toError=function(){var t=this.req,e=t.method,r=t.url,o="cannot ".concat(e," ").concat(r," (").concat(this.status,")"),n=new Error(o);return n.status=this.status,n.method=e,n.url=r,n},S.Response=q,t(D.prototype),l(D.prototype),D.prototype.type=function(t){return this.set("Content-Type",S.types[t]||t),this},D.prototype.accept=function(t){return this.set("Accept",S.types[t]||t),this},D.prototype.auth=function(t,e,r){return 1===arguments.length&&(e=""),"object"==x(e)&&null!==e&&(r=e,e=""),r||(r={type:"function"==typeof btoa?"basic":"auto"}),this._auth(t,e,r,function(t){if("function"==typeof btoa)return btoa(t);throw new Error("Cannot use basic auth, btoa is not a function")})},D.prototype.query=function(t){return"string"!=typeof t&&(t=C(t)),t&&this._query.push(t),this},D.prototype.attach=function(t,e,r){if(e){if(this._data)throw new Error("superagent can't mix .send() and .attach()");this._getFormData().append(t,e,r||e.name)}return this},D.prototype._getFormData=function(){return this._formData||(this._formData=new E.FormData),this._formData},D.prototype.callback=function(t,e){if(this._shouldRetry(t,e))return this._retry();var r=this._callback;this.clearTimeout(),t&&(this._maxRetries&&(t.retries=this._retries-1),this.emit("error",t)),r(t,e)},D.prototype.crossDomainError=function(){var t=new Error("Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.");t.crossDomain=!0,t.status=this.status,t.method=this.method,t.url=this.url,this.callback(t)},D.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},D.prototype.ca=D.prototype.agent,D.prototype.buffer=D.prototype.ca,D.prototype.write=function(){throw new Error("Streaming is not supported in browser version of superagent")},D.prototype.pipe=D.prototype.write,D.prototype._isHost=function(t){return t&&"object"==x(t)&&!Array.isArray(t)&&"[object Object]"!==Object.prototype.toString.call(t)},D.prototype.end=function(t){this._endCalled&&console.warn("Warning: .end() was called twice. This is not supported in superagent"),this._endCalled=!0,this._callback=t||k,this._finalizeQueryString(),this._end()},D.prototype._setUploadTimeout=function(){var t=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout(function(){t._timeoutError("Upload timeout of ",t._uploadTimeout,"ETIMEDOUT")},this._uploadTimeout))},D.prototype._end=function(){if(this._aborted)return this.callback(new Error("The request has been aborted even before .end() was called"));var t=this;this.xhr=S.getXHR();var e=this.xhr,r=this._formData||this._data;this._setTimeouts(),e.onreadystatechange=function(){var r=e.readyState;if(r>=2&&t._responseTimeoutTimer&&clearTimeout(t._responseTimeoutTimer),4===r){var o;try{o=e.status}catch(n){o=0}if(!o){if(t.timedout||t._aborted)return;return t.crossDomainError()}t.emit("end")}};var o=function(e,r){r.total>0&&(r.percent=r.loaded/r.total*100,100===r.percent&&clearTimeout(t._uploadTimeoutTimer)),r.direction=e,t.emit("progress",r)};if(this.hasListeners("progress"))try{e.addEventListener("progress",o.bind(null,"download")),e.upload&&e.upload.addEventListener("progress",o.bind(null,"upload"))}catch(a){}e.upload&&this._setUploadTimeout();try{this.username&&this.password?e.open(this.method,this.url,!0,this.username,this.password):e.open(this.method,this.url,!0)}catch(u){return this.callback(u)}if(this._withCredentials&&(e.withCredentials=!0),!this._formData&&"GET"!==this.method&&"HEAD"!==this.method&&"string"!=typeof r&&!this._isHost(r)){var n=this._header["content-type"],i=this._serializer||S.serialize[n?n.split(";")[0]:""];!i&&P(n)&&(i=S.serialize["application/json"]),i&&(r=i(r))}for(var s in this.header)null!==this.header[s]&&Object.prototype.hasOwnProperty.call(this.header,s)&&e.setRequestHeader(s,this.header[s]);this._responseType&&(e.responseType=this._responseType),this.emit("request",this),e.send(void 0===r?null:r)},S.agent=function(){return new w},["GET","POST","OPTIONS","PATCH","PUT","DELETE"].forEach(function(t){w.prototype[t.toLowerCase()]=function(e,r){var o=new S.Request(t,e);return this._setDefaults(o),r&&o.end(r),o}}),w.prototype.del=w.prototype.delete,S.get=function(t,e,r){var o=S("GET",t);return"function"==typeof e&&(r=e,e=null),e&&o.query(e),r&&o.end(r),o},S.head=function(t,e,r){var o=S("HEAD",t);return"function"==typeof e&&(r=e,e=null),e&&o.query(e),r&&o.end(r),o},S.options=function(t,e,r){var o=S("OPTIONS",t);return"function"==typeof e&&(r=e,e=null),e&&o.send(e),r&&o.end(r),o},S.del=H,S.delete=H,S.patch=function(t,e,r){var o=S("PATCH",t);return"function"==typeof e&&(r=e,e=null),e&&o.send(e),r&&o.end(r),o},S.post=function(t,e,r){var o=S("POST",t);return"function"==typeof e&&(r=e,e=null),e&&o.send(e),r&&o.end(r),o},S.put=function(t,e,r){var o=S("PUT",t);return"function"==typeof e&&(r=e,e=null),e&&o.send(e),r&&o.end(r),o},O}); \ No newline at end of file diff --git a/node_modules/superagent/docs/head.html b/node_modules/superagent/docs/head.html new file mode 100644 index 000000000..8a2d2d2a7 --- /dev/null +++ b/node_modules/superagent/docs/head.html @@ -0,0 +1,11 @@ + + + + + SuperAgent — elegant API for AJAX in Node and browsers + + + + + +
diff --git a/node_modules/superagent/docs/images/bg.png b/node_modules/superagent/docs/images/bg.png new file mode 100644 index 000000000..ca3d2679c Binary files /dev/null and b/node_modules/superagent/docs/images/bg.png differ diff --git a/node_modules/superagent/docs/index.md b/node_modules/superagent/docs/index.md new file mode 100644 index 000000000..90d7d0356 --- /dev/null +++ b/node_modules/superagent/docs/index.md @@ -0,0 +1,736 @@ + +# SuperAgent + +SuperAgent is light-weight progressive ajax API crafted for flexibility, readability, and a low learning curve after being frustrated with many of the existing request APIs. It also works with Node.js! + + request + .post('/api/pet') + .send({ name: 'Manny', species: 'cat' }) + .set('X-API-Key', 'foobar') + .set('Accept', 'application/json') + .then(res => { + alert('yay got ' + JSON.stringify(res.body)); + }); + +## Test documentation + +The following [test documentation](docs/test.html) was generated with [Mocha's](https://mochajs.org/) "doc" reporter, and directly reflects the test suite. This provides an additional source of documentation. + +## Request basics + +A request can be initiated by invoking the appropriate method on the `request` object, then calling `.then()` (or `.end()` [or `await`](#promise-and-generator-support)) to send the request. For example a simple __GET__ request: + + request + .get('/search') + .then(res => { + // res.body, res.headers, res.status + }) + .catch(err => { + // err.message, err.response + }); + +HTTP method may also be passed as a string: + + request('GET', '/search').then(success, failure); + +Old-style callbacks are also supported, but not recommended. *Instead of* `.then()` you can call `.end()`: + + request('GET', '/search').end(function(err, res){ + if (res.ok) {} + }); + +Absolute URLs can be used. In web browsers absolute URLs work only if the server implements [CORS](#cors). + + request + .get('https://example.com/search') + .then(res => { + + }); + +The __Node__ client supports making requests to [Unix Domain Sockets](https://en.wikipedia.org/wiki/Unix_domain_socket): + + // pattern: https?+unix://SOCKET_PATH/REQUEST_PATH + // Use `%2F` as `/` in SOCKET_PATH + try { + const res = await request + .get('http+unix://%2Fabsolute%2Fpath%2Fto%2Funix.sock/search'); + // res.body, res.headers, res.status + } catch(err) { + // err.message, err.response + } + +__DELETE__, __HEAD__, __PATCH__, __POST__, and __PUT__ requests can also be used, simply change the method name: + + request + .head('/favicon.ico') + .then(res => { + + }); + +__DELETE__ can be also called as `.del()` for compatibility with old IE where `delete` is a reserved word. + +The HTTP method defaults to __GET__, so if you wish, the following is valid: + + request('/search', (err, res) => { + + }); + +## Setting header fields + +Setting header fields is simple, invoke `.set()` with a field name and value: + + request + .get('/search') + .set('API-Key', 'foobar') + .set('Accept', 'application/json') + .then(callback); + +You may also pass an object to set several fields in a single call: + + request + .get('/search') + .set({ 'API-Key': 'foobar', Accept: 'application/json' }) + .then(callback); + +## `GET` requests + +The `.query()` method accepts objects, which when used with the __GET__ method will form a query-string. The following will produce the path `/search?query=Manny&range=1..5&order=desc`. + + request + .get('/search') + .query({ query: 'Manny' }) + .query({ range: '1..5' }) + .query({ order: 'desc' }) + .then(res => { + + }); + +Or as a single object: + + request + .get('/search') + .query({ query: 'Manny', range: '1..5', order: 'desc' }) + .then(res => { + + }); + +The `.query()` method accepts strings as well: + + request + .get('/querystring') + .query('search=Manny&range=1..5') + .then(res => { + + }); + +Or joined: + + request + .get('/querystring') + .query('search=Manny') + .query('range=1..5') + .then(res => { + + }); + +## `HEAD` requests + +You can also use the `.query()` method for HEAD requests. The following will produce the path `/users?email=joe@smith.com`. + + request + .head('/users') + .query({ email: 'joe@smith.com' }) + .then(res => { + + }); + +## `POST` / `PUT` requests + +A typical JSON __POST__ request might look a little like the following, where we set the Content-Type header field appropriately, and "write" some data, in this case just a JSON string. + + request.post('/user') + .set('Content-Type', 'application/json') + .send('{"name":"tj","pet":"tobi"}') + .then(callback) + .catch(errorCallback) + +Since JSON is undoubtedly the most common, it's the _default_! The following example is equivalent to the previous. + + request.post('/user') + .send({ name: 'tj', pet: 'tobi' }) + .then(callback, errorCallback) + +Or using multiple `.send()` calls: + + request.post('/user') + .send({ name: 'tj' }) + .send({ pet: 'tobi' }) + .then(callback, errorCallback) + +By default sending strings will set the `Content-Type` to `application/x-www-form-urlencoded`, + multiple calls will be concatenated with `&`, here resulting in `name=tj&pet=tobi`: + + request.post('/user') + .send('name=tj') + .send('pet=tobi') + .then(callback, errorCallback); + +SuperAgent formats are extensible, however by default "json" and "form" are supported. To send the data as `application/x-www-form-urlencoded` simply invoke `.type()` with "form", where the default is "json". This request will __POST__ the body "name=tj&pet=tobi". + + request.post('/user') + .type('form') + .send({ name: 'tj' }) + .send({ pet: 'tobi' }) + .then(callback, errorCallback) + +Sending a [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData) object is also supported. The following example will __POST__ the content of the HTML form identified by id="myForm": + + request.post('/user') + .send(new FormData(document.getElementById('myForm'))) + .then(callback, errorCallback) + +## Setting the `Content-Type` + +The obvious solution is to use the `.set()` method: + + request.post('/user') + .set('Content-Type', 'application/json') + +As a short-hand the `.type()` method is also available, accepting +the canonicalized MIME type name complete with type/subtype, or +simply the extension name such as "xml", "json", "png", etc: + + request.post('/user') + .type('application/json') + + request.post('/user') + .type('json') + + request.post('/user') + .type('png') + +## Serializing request body + +SuperAgent will automatically serialize JSON and forms. +You can setup automatic serialization for other types as well: + +```js +request.serialize['application/xml'] = function (obj) { + return 'string generated from obj'; +}; + +// going forward, all requests with a Content-type of +// 'application/xml' will be automatically serialized +``` +If you want to send the payload in a custom format, you can replace +the built-in serialization with the `.serialize()` method on a per-request basis: + +```js +request + .post('/user') + .send({foo: 'bar'}) + .serialize(obj => { + return 'string generated from obj'; + }); +``` +## Retrying requests + +When given the `.retry()` method, SuperAgent will automatically retry requests, if they fail in a way that is transient or could be due to a flaky Internet connection. + +This method has two optional arguments: number of retries (default 1) and a callback. It calls `callback(err, res)` before each retry. The callback may return `true`/`false` to control whether the request should be retried (but the maximum number of retries is always applied). + + request + .get('https://example.com/search') + .retry(2) // or: + .retry(2, callback) + .then(finished); + .catch(failed); + +Use `.retry()` only with requests that are *idempotent* (i.e. multiple requests reaching the server won't cause undesirable side effects like duplicate purchases). + +## Setting Accept + +In a similar fashion to the `.type()` method it is also possible to set the `Accept` header via the short hand method `.accept()`. Which references `request.types` as well allowing you to specify either the full canonicalized MIME type name as `type/subtype`, or the extension suffix form as "xml", "json", "png", etc. for convenience: + + request.get('/user') + .accept('application/json') + + request.get('/user') + .accept('json') + + request.post('/user') + .accept('png') + +### Facebook and Accept JSON + +If you are calling Facebook's API, be sure to send an `Accept: application/json` header in your request. If you don't do this, Facebook will respond with `Content-Type: text/javascript; charset=UTF-8`, which SuperAgent will not parse and thus `res.body` will be undefined. You can do this with either `req.accept('json')` or `req.header('Accept', 'application/json')`. See [issue 1078](https://github.com/visionmedia/superagent/issues/1078) for details. + +## Query strings + + `req.query(obj)` is a method which may be used to build up a query-string. For example populating `?format=json&dest=/login` on a __POST__: + + request + .post('/') + .query({ format: 'json' }) + .query({ dest: '/login' }) + .send({ post: 'data', here: 'wahoo' }) + .then(callback); + +By default the query string is not assembled in any particular order. An asciibetically-sorted query string can be enabled with `req.sortQuery()`. You may also provide a custom sorting comparison function with `req.sortQuery(myComparisonFn)`. The comparison function should take 2 arguments and return a negative/zero/positive integer. + +```js + // default order + request.get('/user') + .query('name=Nick') + .query('search=Manny') + .sortQuery() + .then(callback) + + // customized sort function + request.get('/user') + .query('name=Nick') + .query('search=Manny') + .sortQuery((a, b) => a.length - b.length) + .then(callback) +``` + +## TLS options + +In Node.js SuperAgent supports methods to configure HTTPS requests: + +- `.ca()`: Set the CA certificate(s) to trust +- `.cert()`: Set the client certificate chain(s) +- `.key()`: Set the client private key(s) +- `.pfx()`: Set the client PFX or PKCS12 encoded private key and certificate chain +- `.disableTLSCerts()`: Does not reject expired or invalid TLS certs. Sets internally `rejectUnauthorized=true`. *Be warned, this method allows MITM attacks.* + +For more information, see Node.js [https.request docs](https://nodejs.org/api/https.html#https_https_request_options_callback). + +```js +var key = fs.readFileSync('key.pem'), + cert = fs.readFileSync('cert.pem'); + +request + .post('/client-auth') + .key(key) + .cert(cert) + .then(callback); +``` + +```js +var ca = fs.readFileSync('ca.cert.pem'); + +request + .post('https://localhost/private-ca-server') + .ca(ca) + .then(res => {}); +``` + +## Parsing response bodies + +SuperAgent will parse known response-body data for you, +currently supporting `application/x-www-form-urlencoded`, +`application/json`, and `multipart/form-data`. You can setup +automatic parsing for other response-body data as well: + +```js +//browser +request.parse['application/xml'] = function (str) { + return {'object': 'parsed from str'}; +}; + +//node +request.parse['application/xml'] = function (res, cb) { + //parse response text and set res.body here + + cb(null, res); +}; + +//going forward, responses of type 'application/xml' +//will be parsed automatically +``` + +You can set a custom parser (that takes precedence over built-in parsers) with the `.buffer(true).parse(fn)` method. If response buffering is not enabled (`.buffer(false)`) then the `response` event will be emitted without waiting for the body parser to finish, so `response.body` won't be available. + +### JSON / Urlencoded + +The property `res.body` is the parsed object, for example if a request responded with the JSON string '{"user":{"name":"tobi"}}', `res.body.user.name` would be "tobi". Likewise the x-www-form-urlencoded value of "user[name]=tobi" would yield the same result. Only one level of nesting is supported. If you need more complex data, send JSON instead. + +Arrays are sent by repeating the key. `.send({color: ['red','blue']})` sends `color=red&color=blue`. If you want the array keys to contain `[]` in their name, you must add it yourself, as SuperAgent doesn't add it automatically. + +### Multipart + +The Node client supports _multipart/form-data_ via the [Formidable](https://github.com/felixge/node-formidable) module. When parsing multipart responses, the object `res.files` is also available to you. Suppose for example a request responds with the following multipart body: + + --whoop + Content-Disposition: attachment; name="image"; filename="tobi.png" + Content-Type: image/png + + ... data here ... + --whoop + Content-Disposition: form-data; name="name" + Content-Type: text/plain + + Tobi + --whoop-- + +You would have the values `res.body.name` provided as "Tobi", and `res.files.image` as a `File` object containing the path on disk, filename, and other properties. + +### Binary + +In browsers, you may use `.responseType('blob')` to request handling of binary response bodies. This API is unnecessary when running in node.js. The supported argument values for this method are + +- `'blob'` passed through to the XmlHTTPRequest `responseType` property +- `'arraybuffer'` passed through to the XmlHTTPRequest `responseType` property + +```js +req.get('/binary.data') + .responseType('blob') + .then(res => { + // res.body will be a browser native Blob type here + }); +``` + +For more information, see the Mozilla Developer Network [xhr.responseType docs](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType). + +## Response properties + +Many helpful flags and properties are set on the `Response` object, ranging from the response text, parsed response body, header fields, status flags and more. + +### Response text + +The `res.text` property contains the unparsed response body string. This property is always present for the client API, and only when the mime type matches "text/*", "*/json", or "x-www-form-urlencoded" by default for node. The reasoning is to conserve memory, as buffering text of large bodies such as multipart files or images is extremely inefficient. To force buffering see the "Buffering responses" section. + +### Response body + +Much like SuperAgent can auto-serialize request data, it can also automatically parse it. When a parser is defined for the Content-Type, it is parsed, which by default includes "application/json" and "application/x-www-form-urlencoded". The parsed object is then available via `res.body`. + +### Response header fields + +The `res.header` contains an object of parsed header fields, lowercasing field names much like node does. For example `res.header['content-length']`. + +### Response Content-Type + +The Content-Type response header is special-cased, providing `res.type`, which is void of the charset (if any). For example the Content-Type of "text/html; charset=utf8" will provide "text/html" as `res.type`, and the `res.charset` property would then contain "utf8". + +### Response status + +The response status flags help determine if the request was a success, among other useful information, making SuperAgent ideal for interacting with RESTful web services. These flags are currently defined as: + + var type = status / 100 | 0; + + // status / class + res.status = status; + res.statusType = type; + + // basics + res.info = 1 == type; + res.ok = 2 == type; + res.clientError = 4 == type; + res.serverError = 5 == type; + res.error = 4 == type || 5 == type; + + // sugar + res.accepted = 202 == status; + res.noContent = 204 == status || 1223 == status; + res.badRequest = 400 == status; + res.unauthorized = 401 == status; + res.notAcceptable = 406 == status; + res.notFound = 404 == status; + res.forbidden = 403 == status; + +## Aborting requests + +To abort requests simply invoke the `req.abort()` method. + +## Timeouts + +Sometimes networks and servers get "stuck" and never respond after accepting a request. Set timeouts to avoid requests waiting forever. + + * `req.timeout({deadline:ms})` or `req.timeout(ms)` (where `ms` is a number of milliseconds > 0) sets a deadline for the entire request (including all uploads, redirects, server processing time) to complete. If the response isn't fully downloaded within that time, the request will be aborted. + + * `req.timeout({response:ms})` sets maximum time to wait for the first byte to arrive from the server, but it does not limit how long the entire download can take. Response timeout should be at least few seconds longer than just the time it takes the server to respond, because it also includes time to make DNS lookup, TCP/IP and TLS connections, and time to upload request data. + +You should use both `deadline` and `response` timeouts. This way you can use a short response timeout to detect unresponsive networks quickly, and a long deadline to give time for downloads on slow, but reliable, networks. Note that both of these timers limit how long *uploads* of attached files are allowed to take. Use long timeouts if you're uploading files. + + request + .get('/big-file?network=slow') + .timeout({ + response: 5000, // Wait 5 seconds for the server to start sending, + deadline: 60000, // but allow 1 minute for the file to finish loading. + }) + .then(res => { + /* responded in time */ + }, err => { + if (err.timeout) { /* timed out! */ } else { /* other error */ } + }); + +Timeout errors have a `.timeout` property. + +## Authentication + +In both Node and browsers auth available via the `.auth()` method: + + request + .get('http://local') + .auth('tobi', 'learnboost') + .then(callback); + + +In the _Node_ client Basic auth can be in the URL as "user:pass": + + request.get('http://tobi:learnboost@local').then(callback); + +By default only `Basic` auth is used. In browser you can add `{type:'auto'}` to enable all methods built-in in the browser (Digest, NTLM, etc.): + + request.auth('digest', 'secret', {type:'auto'}) + +## Following redirects + +By default up to 5 redirects will be followed, however you may specify this with the `res.redirects(n)` method: + + const response = await request.get('/some.png').redirects(2); + +Redirects exceeding the limit are treated as errors. Use `.ok(res => res.status < 400)` to read them as successful responses. + +## Agents for global state + +### Saving cookies + +In Node SuperAgent does not save cookies by default, but you can use the `.agent()` method to create a copy of SuperAgent that saves cookies. Each copy has a separate cookie jar. + + const agent = request.agent(); + agent + .post('/login') + .then(() => { + return agent.get('/cookied-page'); + }); + +In browsers cookies are managed automatically by the browser, so the `.agent()` does not isolate cookies. + +### Default options for multiple requests + +Regular request methods called on the agent will be used as defaults for all requests made by that agent. + + const agent = request.agent() + .use(plugin) + .auth(shared); + + await agent.get('/with-plugin-and-auth'); + await agent.get('/also-with-plugin-and-auth'); + +The complete list of methods that the agent can use to set defaults is: `use`, `on`, `once`, `set`, `query`, `type`, `accept`, `auth`, `withCredentials`, `sortQuery`, `retry`, `ok`, `redirects`, `timeout`, `buffer`, `serialize`, `parse`, `ca`, `key`, `pfx`, `cert`. + +## Piping data + +The Node client allows you to pipe data to and from the request. Please note that `.pipe()` is used **instead of** `.end()`/`.then()` methods. + +For example piping a file's contents as the request: + + const request = require('superagent'); + const fs = require('fs'); + + const stream = fs.createReadStream('path/to/my.json'); + const req = request.post('/somewhere'); + req.type('json'); + stream.pipe(req); + +Note that when you pipe to a request, superagent sends the piped data with [chunked transfer encoding](https://en.wikipedia.org/wiki/Chunked_transfer_encoding), which isn't supported by all servers (for instance, Python WSGI servers). + +Or piping the response to a file: + + const stream = fs.createWriteStream('path/to/my.json'); + const req = request.get('/some.json'); + req.pipe(stream); + + It's not possible to mix pipes and callbacks or promises. Note that you should **NOT** attempt to pipe the result of `.end()` or the `Response` object: + + // Don't do either of these: + const stream = getAWritableStream(); + const req = request + .get('/some.json') + // BAD: this pipes garbage to the stream and fails in unexpected ways + .end((err, this_does_not_work) => this_does_not_work.pipe(stream)) + const req = request + .get('/some.json') + .end() + // BAD: this is also unsupported, .pipe calls .end for you. + .pipe(nope_its_too_late); + +In a [future version](https://github.com/visionmedia/superagent/issues/1188) of superagent, improper calls to `pipe()` will fail. + +## Multipart requests + +SuperAgent is also great for _building_ multipart requests for which it provides methods `.attach()` and `.field()`. + +When you use `.field()` or `.attach()` you can't use `.send()` and you *must not* set `Content-Type` (the correct type will be set for you). + +### Attaching files + +To send a file use `.attach(name, [file], [options])`. You can attach multiple files by calling `.attach` multiple times. The arguments are: + + * `name` — field name in the form. + * `file` — either string with file path or `Blob`/`Buffer` object. + * `options` — (optional) either string with custom file name or `{filename: string}` object. In Node also `{contentType: 'mime/type'}` is supported. In browser create a `Blob` with an appropriate type instead. + +
+ + request + .post('/upload') + .attach('image1', 'path/to/felix.jpeg') + .attach('image2', imageBuffer, 'luna.jpeg') + .field('caption', 'My cats') + .then(callback); + +### Field values + +Much like form fields in HTML, you can set field values with `.field(name, value)` and `.field({name: value})`. Suppose you want to upload a few images with your name and email, your request might look something like this: + + request + .post('/upload') + .field('user[name]', 'Tobi') + .field('user[email]', 'tobi@learnboost.com') + .field('friends[]', ['loki', 'jane']) + .attach('image', 'path/to/tobi.png') + .then(callback); + +## Compression + +The node client supports compressed responses, best of all, you don't have to do anything! It just works. + +## Buffering responses + +To force buffering of response bodies as `res.text` you may invoke `req.buffer()`. To undo the default of buffering for text responses such as "text/plain", "text/html" etc you may invoke `req.buffer(false)`. + +When buffered the `res.buffered` flag is provided, you may use this to handle both buffered and unbuffered responses in the same callback. + +## CORS + +For security reasons, browsers will block cross-origin requests unless the server opts-in using CORS headers. Browsers will also make extra __OPTIONS__ requests to check what HTTP headers and methods are allowed by the server. [Read more about CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS). + +The `.withCredentials()` method enables the ability to send cookies from the origin, however only when `Access-Control-Allow-Origin` is _not_ a wildcard ("*"), and `Access-Control-Allow-Credentials` is "true". + + request + .get('https://api.example.com:4001/') + .withCredentials() + .then(res => { + assert.equal(200, res.status); + assert.equal('tobi', res.text); + }) + +## Error handling + +Your callback function will always be passed two arguments: error and response. If no error occurred, the first argument will be null: + + request + .post('/upload') + .attach('image', 'path/to/tobi.png') + .then(res => { + + }); + +An "error" event is also emitted, with you can listen for: + + request + .post('/upload') + .attach('image', 'path/to/tobi.png') + .on('error', handle) + .then(res => { + + }); + +Note that **superagent considers 4xx and 5xx responses (as well as unhandled 3xx responses) errors by default**. For example, if you get a `304 Not modified`, `403 Forbidden` or `500 Internal server error` response, this status information will be available via `err.status`. Errors from such responses also contain an `err.response` field with all of the properties mentioned in "[Response properties](#response-properties)". The library behaves in this way to handle the common case of wanting success responses and treating HTTP error status codes as errors while still allowing for custom logic around specific error conditions. + +Network failures, timeouts, and other errors that produce no response will contain no `err.status` or `err.response` fields. + +If you wish to handle 404 or other HTTP error responses, you can query the `err.status` property. When an HTTP error occurs (4xx or 5xx response) the `res.error` property is an `Error` object, this allows you to perform checks such as: + + if (err && err.status === 404) { + alert('oh no ' + res.body.message); + } + else if (err) { + // all other error types we handle generically + } + +Alternatively, you can use the `.ok(callback)` method to decide whether a response is an error or not. The callback to the `ok` function gets a response and returns `true` if the response should be interpreted as success. + + request.get('/404') + .ok(res => res.status < 500) + .then(response => { + // reads 404 page as a successful response + }) + +## Progress tracking + +SuperAgent fires `progress` events on upload and download of large files. + + request.post(url) + .attach('field_name', file) + .on('progress', event => { + /* the event is: + { + direction: "upload" or "download" + percent: 0 to 100 // may be missing if file size is unknown + total: // total file size, may be missing + loaded: // bytes downloaded or uploaded so far + } */ + }) + .then() + + +## Testing on localhost + +### Forcing specific connection IP address + +In Node.js it's possible to ignore DNS resolution and direct all requests to a specific IP address using `.connect()` method. For example, this request will go to localhost instead of `example.com`: + + const res = await request.get("http://example.com").connect("127.0.0.1"); + +Because the request may be redirected, it's possible to specify multiple hostnames and multiple IPs, as well as a special `*` as the fallback (note: other wildcards are not supported). The requests will keep their `Host` header with the original value. `.connect(undefined)` turns off the feature. + + const res = await request.get("http://redir.example.com:555") + .connect({ + "redir.example.com": "127.0.0.1", // redir.example.com:555 will use 127.0.0.1:555 + "www.example.com": false, // don't override this one; use DNS as normal + "mapped.example.com": { host: "127.0.0.1", port: 8080}, // mapped.example.com:* will use 127.0.0.1:8080 + "*": "proxy.example.com", // all other requests will go to this host + }); + +### Ignoring broken/insecure HTTPS on localhost + +In Node.js, when HTTPS is misconfigured and insecure (e.g. using self-signed certificate *without* specifying own `.ca()`), it's still possible to permit requests to `localhost` by calling `.trustLocalhost()`: + + const res = await request.get("https://localhost").trustLocalhost() + +Together with `.connect("127.0.0.1")` this may be used to force HTTPS requests to any domain to be re-routed to `localhost` instead. + +It's generally safe to ignore broken HTTPS on `localhost`, because the loopback interface is not exposed to untrusted networks. Trusting `localhost` may become the default in the future. Use `.trustLocalhost(false)` to force check of `127.0.0.1`'s authenticity. + +We intentionally don't support disabling of HTTPS security when making requests to any other IP, because such options end up abused as a quick "fix" for HTTPS problems. You can get free HTTPS certificates from [Let's Encrypt](https://certbot.eff.org) or set your own CA (`.ca(ca_public_pem)`) to make your self-signed certificates trusted. + +## Promise and Generator support + +SuperAgent's request is a "thenable" object that's compatible with JavaScript promises and the `async`/`await` syntax. + + const res = await request.get(url); + +If you're using promises, **do not** call `.end()` or `.pipe()`. Any use of `.then()` or `await` disables all other ways of using the request. + +Libraries like [co](https://github.com/tj/co) or a web framework like [koa](https://github.com/koajs/koa) can `yield` on any SuperAgent method: + + const req = request + .get('http://local') + .auth('tobi', 'learnboost'); + const res = yield req; + +Note that SuperAgent expects the global `Promise` object to be present. You'll need a polyfill to use promises in Internet Explorer or Node.js 0.10. + +## Browser and node versions + +SuperAgent has two implementations: one for web browsers (using XHR) and one for Node.JS (using core http module). By default Browserify and WebPack will pick the browser version. + +If want to use WebPack to compile code for Node.JS, you *must* specify [node target](https://webpack.github.io/docs/configuration.html#target) in its configuration. + +### Using browser version in electron + +[Electron](https://electron.atom.io/) developers report if you would prefer to use the browser version of SuperAgent instead of the Node version, you can `require('superagent/superagent')`. Your requests will now show up in the Chrome developer tools Network tab. Note this environment is not covered by automated test suite and not officially supported. diff --git a/node_modules/superagent/docs/style.css b/node_modules/superagent/docs/style.css new file mode 100644 index 000000000..fb2a9e365 --- /dev/null +++ b/node_modules/superagent/docs/style.css @@ -0,0 +1,87 @@ +body { + padding: 40px 80px; + font: 14px/1.5 "Helvetica Neue", Helvetica, sans-serif; + background: #181818 url(images/bg.png); + text-align: center; +} + +#content { + margin: 0 auto; + padding: 10px 40px; + text-align: left; + background: white; + width: 50%; + -webkit-border-radius: 2px; + -moz-border-radius: 2px; + border-radius: 2px; + -webkit-box-shadow: 0 2px 5px 0 black; +} + +#menu { + font-size: 13px; + margin: 0; + padding: 0; + text-align: left; + position: fixed; + top: 15px; + left: 15px; +} + +#menu ul { + margin: 0; + padding: 0; +} + +#menu li { + list-style: none; +} + +#menu a { + color: rgba(255,255,255,.5); + text-decoration: none; +} + +#menu a:hover { + color: white; +} + +#menu .active a { + color: white; +} + +pre { + padding: 10px; +} + +code { + font-family: monaco, monospace, sans-serif; + font-size: 0.85em; +} + +p code { + border: 1px solid #ECEA75; + padding: 1px 3px; + -webkit-border-radius: 2px; + -moz-border-radius: 2px; + border-radius: 2px; + background: #FDFCD1; +} + +pre { + padding: 20px 25px; + border: 1px solid #ddd; + -webkit-box-shadow: inset 0 0 5px #eee; + -moz-box-shadow: inset 0 0 5px #eee; + box-shadow: inset 0 0 5px #eee; +} + +code .comment { color: #ddd } +code .init { color: #2F6FAD } +code .string { color: #5890AD } +code .keyword { color: #8A6343 } +code .number { color: #2F6FAD } + +/* override tocbot style to avoid vertical white line in table of content */ +.toc-link::before { + content: initial; +} diff --git a/node_modules/superagent/docs/tail.html b/node_modules/superagent/docs/tail.html new file mode 100644 index 000000000..9415a14ba --- /dev/null +++ b/node_modules/superagent/docs/tail.html @@ -0,0 +1,36 @@ +
+ Fork me on GitHub + + + + + + diff --git a/node_modules/superagent/docs/test.html b/node_modules/superagent/docs/test.html new file mode 100644 index 000000000..20d5f08bf --- /dev/null +++ b/node_modules/superagent/docs/test.html @@ -0,0 +1,5072 @@ + + + + + SuperAgent — elegant API for AJAX in Node and browsers + + + + + +
+
+

Agent

+
+
should remember defaults
+
if (typeof Promise === 'undefined') {
+  return;
+}
+let called = 0;
+let event_called = 0;
+const agent = request
+  .agent()
+  .accept('json')
+  .use(() => {
+    called++;
+  })
+  .once('request', () => {
+    event_called++;
+  })
+  .query({ hello: 'world' })
+  .set('X-test', 'testing');
+assert.equal(0, called);
+assert.equal(0, event_called);
+return agent
+  .get(`${base}/echo`)
+  .then(res => {
+    assert.equal(1, called);
+    assert.equal(1, event_called);
+    assert.equal('application/json', res.headers.accept);
+    assert.equal('testing', res.headers['x-test']);
+    return agent.get(`${base}/querystring`);
+  })
+  .then(res => {
+    assert.equal(2, called);
+    assert.equal(2, event_called);
+    assert.deepEqual({ hello: 'world' }, res.body);
+  });
+
+
+
+

request

+
+
+

res.statusCode

+
+
should set statusCode
+
done => {
+      request.get(`${uri}/login`, (err, res) => {
+        try {
+          assert.strictEqual(res.statusCode, 200);
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+    }
+
+
+
+

should allow the send shorthand

+
+
with callback in the method call
+
done => {
+      request.get(`${uri}/login`, (err, res) => {
+        assert.equal(res.status, 200);
+        done();
+      });
+    }
+
with data in the method call
+
done => {
+      request.post(`${uri}/echo`, { foo: 'bar' }).end((err, res) => {
+        assert.equal('{"foo":"bar"}', res.text);
+        done();
+      });
+    }
+
with callback and data in the method call
+
done => {
+      request.post(`${uri}/echo`, { foo: 'bar' }, (err, res) => {
+        assert.equal('{"foo":"bar"}', res.text);
+        done();
+      });
+    }
+
+
+
+

with a callback

+
+
should invoke .end()
+
done => {
+      request.get(`${uri}/login`, (err, res) => {
+        try {
+          assert.equal(res.status, 200);
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+    }
+
+
+
+

.end()

+
+
should issue a request
+
done => {
+      request.get(`${uri}/login`).end((err, res) => {
+        try {
+          assert.equal(res.status, 200);
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+    }
+
is optional with a promise
+
if (typeof Promise === 'undefined') {
+  return;
+}
+return request
+  .get(`${uri}/login`)
+  .then(res => res.status)
+  .then()
+  .then(status => {
+    assert.equal(200, status, 'Real promises pass results through');
+  });
+
called only once with a promise
+
if (typeof Promise === 'undefined') {
+  return;
+}
+const req = request.get(`${uri}/unique`);
+return Promise.all([req, req, req]).then(results => {
+  results.forEach(item => {
+    assert.equal(
+      item.body,
+      results[0].body,
+      'It should keep returning the same result after being called once'
+    );
+  });
+});
+
+
+
+

res.error

+
+
ok
+
done => {
+      let calledErrorEvent = false;
+      let calledOKHandler = false;
+      request
+        .get(`${uri}/error`)
+        .ok(res => {
+          assert.strictEqual(500, res.status);
+          calledOKHandler = true;
+          return true;
+        })
+        .on('error', err => {
+          calledErrorEvent = true;
+        })
+        .end((err, res) => {
+          try {
+            assert.ifError(err);
+            assert.strictEqual(res.status, 500);
+            assert(!calledErrorEvent);
+            assert(calledOKHandler);
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
should should be an Error object
+
done => {
+      let calledErrorEvent = false;
+      request
+        .get(`${uri}/error`)
+        .on('error', err => {
+          assert.strictEqual(err.status, 500);
+          calledErrorEvent = true;
+        })
+        .end((err, res) => {
+          try {
+            if (NODE) {
+              res.error.message.should.equal('cannot GET /error (500)');
+            } else {
+              res.error.message.should.equal(`cannot GET ${uri}/error (500)`);
+            }
+            assert.strictEqual(res.error.status, 500);
+            assert(err, 'should have an error for 500');
+            assert.equal(err.message, 'Internal Server Error');
+            assert(calledErrorEvent);
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
with .then() promise
+
if (typeof Promise === 'undefined') {
+  return;
+}
+return request.get(`${uri}/error`).then(
+  () => {
+    assert.fail();
+  },
+  err => {
+    assert.equal(err.message, 'Internal Server Error');
+  }
+);
+
with .ok() returning false
+
if (typeof Promise === 'undefined') {
+  return;
+}
+return request
+  .get(`${uri}/echo`)
+  .ok(() => false)
+  .then(
+    () => {
+      assert.fail();
+    },
+    err => {
+      assert.equal(200, err.response.status);
+      assert.equal(err.message, 'OK');
+    }
+  );
+
with .ok() throwing an Error
+
if (typeof Promise === 'undefined') {
+  return;
+}
+return request
+  .get(`${uri}/echo`)
+  .ok(() => {
+    throw new Error('boom');
+  })
+  .then(
+    () => {
+      assert.fail();
+    },
+    err => {
+      assert.equal(200, err.response.status);
+      assert.equal(err.message, 'boom');
+    }
+  );
+
+
+
+

res.header

+
+
should be an object
+
done => {
+      request.get(`${uri}/login`).end((err, res) => {
+        try {
+          assert.equal('Express', res.header['x-powered-by']);
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+    }
+
+
+
+

set headers

+
+
should only set headers for ownProperties of header
+
done => {
+      try {
+        request
+          .get(`${uri}/echo-headers`)
+          .set('valid', 'ok')
+          .end((err, res) => {
+            if (
+              !err &&
+              res.body &&
+              res.body.valid &&
+              !res.body.hasOwnProperty('invalid')
+            ) {
+              return done();
+            }
+            done(err || new Error('fail'));
+          });
+      } catch (err) {
+        done(err);
+      }
+    }
+
+
+
+

res.charset

+
+
should be set when present
+
done => {
+      request.get(`${uri}/login`).end((err, res) => {
+        try {
+          res.charset.should.equal('utf-8');
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+    }
+
+
+
+

res.statusType

+
+
should provide the first digit
+
done => {
+      request.get(`${uri}/login`).end((err, res) => {
+        try {
+          assert(!err, 'should not have an error for success responses');
+          assert.equal(200, res.status);
+          assert.equal(2, res.statusType);
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+    }
+
+
+
+

res.type

+
+
should provide the mime-type void of params
+
done => {
+      request.get(`${uri}/login`).end((err, res) => {
+        try {
+          res.type.should.equal('text/html');
+          res.charset.should.equal('utf-8');
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+    }
+
+
+
+

req.set(field, val)

+
+
should set the header field
+
done => {
+      request
+        .post(`${uri}/echo`)
+        .set('X-Foo', 'bar')
+        .set('X-Bar', 'baz')
+        .end((err, res) => {
+          try {
+            assert.equal('bar', res.header['x-foo']);
+            assert.equal('baz', res.header['x-bar']);
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
+
+
+

req.set(obj)

+
+
should set the header fields
+
done => {
+      request
+        .post(`${uri}/echo`)
+        .set({ 'X-Foo': 'bar', 'X-Bar': 'baz' })
+        .end((err, res) => {
+          try {
+            assert.equal('bar', res.header['x-foo']);
+            assert.equal('baz', res.header['x-bar']);
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
+
+
+

req.type(str)

+
+
should set the Content-Type
+
done => {
+      request
+        .post(`${uri}/echo`)
+        .type('text/x-foo')
+        .end((err, res) => {
+          try {
+            res.header['content-type'].should.equal('text/x-foo');
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
should map "json"
+
done => {
+      request
+        .post(`${uri}/echo`)
+        .type('json')
+        .send('{"a": 1}')
+        .end((err, res) => {
+          try {
+            res.should.be.json();
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
should map "html"
+
done => {
+      request
+        .post(`${uri}/echo`)
+        .type('html')
+        .end((err, res) => {
+          try {
+            res.header['content-type'].should.equal('text/html');
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
+
+
+

req.accept(str)

+
+
should set Accept
+
done => {
+      request
+        .get(`${uri}/echo`)
+        .accept('text/x-foo')
+        .end((err, res) => {
+          try {
+            res.header.accept.should.equal('text/x-foo');
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
should map "json"
+
done => {
+      request
+        .get(`${uri}/echo`)
+        .accept('json')
+        .end((err, res) => {
+          try {
+            res.header.accept.should.equal('application/json');
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
should map "xml"
+
done => {
+      request
+        .get(`${uri}/echo`)
+        .accept('xml')
+        .end((err, res) => {
+          try {
+            // Mime module keeps changing this :(
+            assert(
+              res.header.accept == 'application/xml' ||
+                res.header.accept == 'text/xml'
+            );
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
should map "html"
+
done => {
+      request
+        .get(`${uri}/echo`)
+        .accept('html')
+        .end((err, res) => {
+          try {
+            res.header.accept.should.equal('text/html');
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
+
+
+

req.send(str)

+
+
should write the string
+
done => {
+      request
+        .post(`${uri}/echo`)
+        .type('json')
+        .send('{"name":"tobi"}')
+        .end((err, res) => {
+          try {
+            res.text.should.equal('{"name":"tobi"}');
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
+
+
+

req.send(Object)

+
+
should default to json
+
done => {
+      request
+        .post(`${uri}/echo`)
+        .send({ name: 'tobi' })
+        .end((err, res) => {
+          try {
+            res.should.be.json();
+            res.text.should.equal('{"name":"tobi"}');
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
+

when called several times

+
+
should merge the objects
+
done => {
+        request
+          .post(`${uri}/echo`)
+          .send({ name: 'tobi' })
+          .send({ age: 1 })
+          .end((err, res) => {
+            try {
+              res.should.be.json();
+              if (NODE) {
+                res.buffered.should.be.true();
+              }
+              res.text.should.equal('{"name":"tobi","age":1}');
+              done();
+            } catch (err2) {
+              done(err2);
+            }
+          });
+      }
+
+
+
+
+
+

.end(fn)

+
+
should check arity
+
done => {
+      request
+        .post(`${uri}/echo`)
+        .send({ name: 'tobi' })
+        .end((err, res) => {
+          try {
+            assert.ifError(err);
+            res.text.should.equal('{"name":"tobi"}');
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
should emit request
+
done => {
+      const req = request.post(`${uri}/echo`);
+      req.on('request', request => {
+        assert.equal(req, request);
+        done();
+      });
+      req.end();
+    }
+
should emit response
+
done => {
+      request
+        .post(`${uri}/echo`)
+        .send({ name: 'tobi' })
+        .on('response', res => {
+          res.text.should.equal('{"name":"tobi"}');
+          done();
+        })
+        .end();
+    }
+
+
+
+

.then(fulfill, reject)

+
+
should support successful fulfills with .then(fulfill)
+
done => {
+      if (typeof Promise === 'undefined') {
+        return done();
+      }
+      request
+        .post(`${uri}/echo`)
+        .send({ name: 'tobi' })
+        .then(res => {
+          res.type.should.equal('application/json');
+          res.text.should.equal('{"name":"tobi"}');
+          done();
+        });
+    }
+
should reject an error with .then(null, reject)
+
done => {
+      if (typeof Promise === 'undefined') {
+        return done();
+      }
+      request.get(`${uri}/error`).then(null, err => {
+        assert.equal(err.status, 500);
+        assert.equal(err.response.text, 'boom');
+        done();
+      });
+    }
+
+
+
+

.catch(reject)

+
+
should reject an error with .catch(reject)
+
done => {
+      if (typeof Promise === 'undefined') {
+        return done();
+      }
+      request.get(`${uri}/error`).catch(err => {
+        assert.equal(err.status, 500);
+        assert.equal(err.response.text, 'boom');
+        done();
+      });
+    }
+
+
+
+

.abort()

+
+
should abort the request
+
done => {
+      const req = request.get(`${uri}/delay/3000`);
+      req.end((err, res) => {
+        try {
+          assert(false, 'should not complete the request');
+        } catch (err2) {
+          done(err2);
+        }
+      });
+      req.on('error', error => {
+        done(error);
+      });
+      req.on('abort', done);
+      setTimeout(() => {
+        req.abort();
+      }, 500);
+    }
+
should abort the promise
+
const req = request.get(`${uri}/delay/3000`);
+setTimeout(() => {
+  req.abort();
+}, 10);
+return req.then(
+  () => {
+    assert.fail('should not complete the request');
+  },
+  err => {
+    assert.equal('ABORTED', err.code);
+  }
+);
+
should allow chaining .abort() several times
+
done => {
+      const req = request.get(`${uri}/delay/3000`);
+      req.end((err, res) => {
+        try {
+          assert(false, 'should not complete the request');
+        } catch (err2) {
+          done(err2);
+        }
+      });
+      // This also verifies only a single 'done' event is emitted
+      req.on('abort', done);
+      setTimeout(() => {
+        req
+          .abort()
+          .abort()
+          .abort();
+      }, 1000);
+    }
+
should not allow abort then end
+
done => {
+      request
+        .get(`${uri}/delay/3000`)
+        .abort()
+        .end((err, res) => {
+          done(err ? undefined : new Error('Expected abort error'));
+        });
+    }
+
+
+
+

req.toJSON()

+
+
should describe the request
+
done => {
+      const req = request.post(`${uri}/echo`).send({ foo: 'baz' });
+      req.end((err, res) => {
+        try {
+          const json = req.toJSON();
+          assert.equal('POST', json.method);
+          assert(/\/echo$/.test(json.url));
+          assert.equal('baz', json.data.foo);
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+    }
+
+
+
+

req.options()

+
+
should allow request body
+
done => {
+      request
+        .options(`${uri}/options/echo/body`)
+        .send({ foo: 'baz' })
+        .end((err, res) => {
+          try {
+            assert.equal(err, null);
+            assert.strictEqual(res.body.foo, 'baz');
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
+
+
+

req.sortQuery()

+
+
nop with no querystring
+
done => {
+      request
+        .get(`${uri}/url`)
+        .sortQuery()
+        .end((err, res) => {
+          try {
+            assert.equal(res.text, '/url');
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
should sort the request querystring
+
done => {
+      request
+        .get(`${uri}/url`)
+        .query('search=Manny')
+        .query('order=desc')
+        .sortQuery()
+        .end((err, res) => {
+          try {
+            assert.equal(res.text, '/url?order=desc&search=Manny');
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
should allow disabling sorting
+
done => {
+      request
+        .get(`${uri}/url`)
+        .query('search=Manny')
+        .query('order=desc')
+        .sortQuery() // take default of true
+        .sortQuery(false) // override it in later call
+        .end((err, res) => {
+          try {
+            assert.equal(res.text, '/url?search=Manny&order=desc');
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
should sort the request querystring using customized function
+
done => {
+      request
+        .get(`${uri}/url`)
+        .query('name=Nick')
+        .query('search=Manny')
+        .query('order=desc')
+        .sortQuery((a, b) => a.length - b.length)
+        .end((err, res) => {
+          try {
+            assert.equal(res.text, '/url?name=Nick&order=desc&search=Manny');
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
+
+
+
+
+

req.set("Content-Type", contentType)

+
+
should work with just the contentType component
+
done => {
+    request
+      .post(`${uri}/echo`)
+      .set('Content-Type', 'application/json')
+      .send({ name: 'tobi' })
+      .end((err, res) => {
+        assert(!err);
+        done();
+      });
+  }
+
should work with the charset component
+
done => {
+    request
+      .post(`${uri}/echo`)
+      .set('Content-Type', 'application/json; charset=utf-8')
+      .send({ name: 'tobi' })
+      .end((err, res) => {
+        assert(!err);
+        done();
+      });
+  }
+
+
+
+

req.send(Object) as "form"

+
+
+

with req.type() set to form

+
+
should send x-www-form-urlencoded data
+
done => {
+      request
+        .post(`${base}/echo`)
+        .type('form')
+        .send({ name: 'tobi' })
+        .end((err, res) => {
+          res.header['content-type'].should.equal(
+            'application/x-www-form-urlencoded'
+          );
+          res.text.should.equal('name=tobi');
+          done();
+        });
+    }
+
+
+
+

when called several times

+
+
should merge the objects
+
done => {
+      request
+        .post(`${base}/echo`)
+        .type('form')
+        .send({ name: { first: 'tobi', last: 'holowaychuk' } })
+        .send({ age: '1' })
+        .end((err, res) => {
+          res.header['content-type'].should.equal(
+            'application/x-www-form-urlencoded'
+          );
+          res.text.should.equal(
+            'name%5Bfirst%5D=tobi&name%5Blast%5D=holowaychuk&age=1'
+          );
+          done();
+        });
+    }
+
+
+
+
+
+

req.attach

+
+
ignores null file
+
done => {
+    request
+      .post('/echo')
+      .attach('image', null)
+      .end((err, res) => {
+        done();
+      });
+  }
+
+
+
+

req.field

+
+
allow bools
+
done => {
+    if (!formDataSupported) {
+      return done();
+    }
+    request
+      .post(`${base}/formecho`)
+      .field('bools', true)
+      .field('strings', 'true')
+      .end((err, res) => {
+        assert.ifError(err);
+        assert.deepStrictEqual(res.body, { bools: 'true', strings: 'true' });
+        done();
+      });
+  }
+
allow objects
+
done => {
+    if (!formDataSupported) {
+      return done();
+    }
+    request
+      .post(`${base}/formecho`)
+      .field({ bools: true, strings: 'true' })
+      .end((err, res) => {
+        assert.ifError(err);
+        assert.deepStrictEqual(res.body, { bools: 'true', strings: 'true' });
+        done();
+      });
+  }
+
works with arrays in objects
+
done => {
+    if (!formDataSupported) {
+      return done();
+    }
+    request
+      .post(`${base}/formecho`)
+      .field({ numbers: [1, 2, 3] })
+      .end((err, res) => {
+        assert.ifError(err);
+        assert.deepStrictEqual(res.body, { numbers: ['1', '2', '3'] });
+        done();
+      });
+  }
+
works with arrays
+
done => {
+    if (!formDataSupported) {
+      return done();
+    }
+    request
+      .post(`${base}/formecho`)
+      .field('letters', ['a', 'b', 'c'])
+      .end((err, res) => {
+        assert.ifError(err);
+        assert.deepStrictEqual(res.body, { letters: ['a', 'b', 'c'] });
+        done();
+      });
+  }
+
throw when empty
+
should.throws(() => {
+  request.post(`${base}/echo`).field();
+}, /name/);
+should.throws(() => {
+  request.post(`${base}/echo`).field('name');
+}, /val/);
+
cannot be mixed with send()
+
assert.throws(() => {
+  request
+    .post('/echo')
+    .field('form', 'data')
+    .send('hi');
+});
+assert.throws(() => {
+  request
+    .post('/echo')
+    .send('hi')
+    .field('form', 'data');
+});
+
+
+
+

req.send(Object) as "json"

+
+
should default to json
+
done => {
+    request
+      .post(`${uri}/echo`)
+      .send({ name: 'tobi' })
+      .end((err, res) => {
+        res.should.be.json();
+        res.text.should.equal('{"name":"tobi"}');
+        done();
+      });
+  }
+
should work with arrays
+
done => {
+    request
+      .post(`${uri}/echo`)
+      .send([1, 2, 3])
+      .end((err, res) => {
+        res.should.be.json();
+        res.text.should.equal('[1,2,3]');
+        done();
+      });
+  }
+
should work with value null
+
done => {
+    request
+      .post(`${uri}/echo`)
+      .type('json')
+      .send('null')
+      .end((err, res) => {
+        res.should.be.json();
+        assert.strictEqual(res.body, null);
+        done();
+      });
+  }
+
should work with value false
+
done => {
+    request
+      .post(`${uri}/echo`)
+      .type('json')
+      .send('false')
+      .end((err, res) => {
+        res.should.be.json();
+        res.body.should.equal(false);
+        done();
+      });
+  }
+
should work with value 0
+
done => {
+      // fails in IE9
+      request
+        .post(`${uri}/echo`)
+        .type('json')
+        .send('0')
+        .end((err, res) => {
+          res.should.be.json();
+          res.body.should.equal(0);
+          done();
+        });
+    }
+
should work with empty string value
+
done => {
+    request
+      .post(`${uri}/echo`)
+      .type('json')
+      .send('""')
+      .end((err, res) => {
+        res.should.be.json();
+        res.body.should.equal('');
+        done();
+      });
+  }
+
should work with GET
+
done => {
+      request
+        .get(`${uri}/echo`)
+        .send({ tobi: 'ferret' })
+        .end((err, res) => {
+          try {
+            res.should.be.json();
+            res.text.should.equal('{"tobi":"ferret"}');
+            ({ tobi: 'ferret' }.should.eql(res.body));
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
should work with vendor MIME type
+
done => {
+    request
+      .post(`${uri}/echo`)
+      .set('Content-Type', 'application/vnd.example+json')
+      .send({ name: 'vendor' })
+      .end((err, res) => {
+        res.text.should.equal('{"name":"vendor"}');
+        ({ name: 'vendor' }.should.eql(res.body));
+        done();
+      });
+  }
+
+

when called several times

+
+
should merge the objects
+
done => {
+      request
+        .post(`${uri}/echo`)
+        .send({ name: 'tobi' })
+        .send({ age: 1 })
+        .end((err, res) => {
+          res.should.be.json();
+          res.text.should.equal('{"name":"tobi","age":1}');
+          ({ name: 'tobi', age: 1 }.should.eql(res.body));
+          done();
+        });
+    }
+
+
+
+
+
+

res.body

+
+
+

application/json

+
+
should parse the body
+
done => {
+      request.get(`${uri}/json`).end((err, res) => {
+        res.text.should.equal('{"name":"manny"}');
+        res.body.should.eql({ name: 'manny' });
+        done();
+      });
+    }
+
+
+
+

HEAD requests

+
+
should not throw a parse error
+
done => {
+        request.head(`${uri}/json`).end((err, res) => {
+          try {
+            assert.strictEqual(err, null);
+            assert.strictEqual(res.text, undefined);
+            assert.strictEqual(Object.keys(res.body).length, 0);
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+      }
+
+
+
+

Invalid JSON response

+
+
should return the raw response
+
done => {
+      request.get(`${uri}/invalid-json`).end((err, res) => {
+        assert.deepEqual(
+          err.rawResponse,
+          ")]}', {'header':{'code':200,'text':'OK','version':'1.0'},'data':'some data'}"
+        );
+        done();
+      });
+    }
+
should return the http status code
+
done => {
+      request.get(`${uri}/invalid-json-forbidden`).end((err, res) => {
+        assert.equal(err.statusCode, 403);
+        done();
+      });
+    }
+
+
+
+

No content

+
+
should not throw a parse error
+
done => {
+        request.get(`${uri}/no-content`).end((err, res) => {
+          try {
+            assert.strictEqual(err, null);
+            assert.strictEqual(res.text, '');
+            assert.strictEqual(Object.keys(res.body).length, 0);
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+      }
+
+
+
+

application/json+hal

+
+
should parse the body
+
done => {
+        request.get(`${uri}/json-hal`).end((err, res) => {
+          if (err) return done(err);
+          res.text.should.equal('{"name":"hal 5000"}');
+          res.body.should.eql({ name: 'hal 5000' });
+          done();
+        });
+      }
+
+
+
+

vnd.collection+json

+
+
should parse the body
+
done => {
+        request.get(`${uri}/collection-json`).end((err, res) => {
+          res.text.should.equal('{"name":"chewbacca"}');
+          res.body.should.eql({ name: 'chewbacca' });
+          done();
+        });
+      }
+
+
+
+
+
+

request

+
+
+

on redirect

+
+
should retain header fields
+
done => {
+      request
+        .get(`${base}/header`)
+        .set('X-Foo', 'bar')
+        .end((err, res) => {
+          try {
+            assert(res.body);
+            res.body.should.have.property('x-foo', 'bar');
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
should preserve timeout across redirects
+
done => {
+      request
+        .get(`${base}/movies/random`)
+        .timeout(250)
+        .end((err, res) => {
+          try {
+            assert(err instanceof Error, 'expected an error');
+            err.should.have.property('timeout', 250);
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
should successfully redirect after retry on error
+
done => {
+      const id = Math.random() * 1000000 * Date.now();
+      request
+        .get(`${base}/error/redirect/${id}`)
+        .retry(2)
+        .end((err, res) => {
+          assert(res.ok, 'response should be ok');
+          assert(res.text, 'first movie page');
+          done();
+        });
+    }
+
should preserve retries across redirects
+
done => {
+      const id = Math.random() * 1000000 * Date.now();
+      request
+        .get(`${base}/error/redirect-error${id}`)
+        .retry(2)
+        .end((err, res) => {
+          assert(err, 'expected an error');
+          assert.equal(2, err.retries, 'expected an error with .retries');
+          assert.equal(500, err.status, 'expected an error status of 500');
+          done();
+        });
+    }
+
+
+
+

on 303

+
+
should redirect with same method
+
done => {
+      request
+        .put(`${base}/redirect-303`)
+        .send({ msg: 'hello' })
+        .redirects(1)
+        .on('redirect', res => {
+          res.headers.location.should.equal('/reply-method');
+        })
+        .end((err, res) => {
+          if (err) {
+            done(err);
+            return;
+          }
+          res.text.should.equal('method=get');
+          done();
+        });
+    }
+
+
+
+

on 307

+
+
should redirect with same method
+
done => {
+      if (isMSIE) return done(); // IE9 broken
+      request
+        .put(`${base}/redirect-307`)
+        .send({ msg: 'hello' })
+        .redirects(1)
+        .on('redirect', res => {
+          res.headers.location.should.equal('/reply-method');
+        })
+        .end((err, res) => {
+          if (err) {
+            done(err);
+            return;
+          }
+          res.text.should.equal('method=put');
+          done();
+        });
+    }
+
+
+
+

on 308

+
+
should redirect with same method
+
done => {
+      if (isMSIE) return done(); // IE9 broken
+      request
+        .put(`${base}/redirect-308`)
+        .send({ msg: 'hello' })
+        .redirects(1)
+        .on('redirect', res => {
+          res.headers.location.should.equal('/reply-method');
+        })
+        .end((err, res) => {
+          if (err) {
+            done(err);
+            return;
+          }
+          res.text.should.equal('method=put');
+          done();
+        });
+    }
+
+
+
+
+
+

request

+
+
Request inheritance
+
assert(request.get(`${uri}/`) instanceof request.Request);
+
request() simple GET without callback
+
next => {
+    request('GET', 'test/test.request.js').end();
+    next();
+  }
+
request() simple GET
+
next => {
+    request('GET', `${uri}/ok`).end((err, res) => {
+      try {
+        assert(res instanceof request.Response, 'respond with Response');
+        assert(res.ok, 'response should be ok');
+        assert(res.text, 'res.text');
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
request() simple HEAD
+
next => {
+    request.head(`${uri}/ok`).end((err, res) => {
+      try {
+        assert(res instanceof request.Response, 'respond with Response');
+        assert(res.ok, 'response should be ok');
+        assert(!res.text, 'res.text');
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
request() GET 5xx
+
next => {
+    request('GET', `${uri}/error`).end((err, res) => {
+      try {
+        assert(err);
+        assert.equal(err.message, 'Internal Server Error');
+        assert(!res.ok, 'response should not be ok');
+        assert(res.error, 'response should be an error');
+        assert(!res.clientError, 'response should not be a client error');
+        assert(res.serverError, 'response should be a server error');
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
request() GET 4xx
+
next => {
+    request('GET', `${uri}/notfound`).end((err, res) => {
+      try {
+        assert(err);
+        assert.equal(err.message, 'Not Found');
+        assert(!res.ok, 'response should not be ok');
+        assert(res.error, 'response should be an error');
+        assert(res.clientError, 'response should be a client error');
+        assert(!res.serverError, 'response should not be a server error');
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
request() GET 404 Not Found
+
next => {
+    request('GET', `${uri}/notfound`).end((err, res) => {
+      try {
+        assert(err);
+        assert(res.notFound, 'response should be .notFound');
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
request() GET 400 Bad Request
+
next => {
+    request('GET', `${uri}/bad-request`).end((err, res) => {
+      try {
+        assert(err);
+        assert(res.badRequest, 'response should be .badRequest');
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
request() GET 401 Bad Request
+
next => {
+    request('GET', `${uri}/unauthorized`).end((err, res) => {
+      try {
+        assert(err);
+        assert(res.unauthorized, 'response should be .unauthorized');
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
request() GET 406 Not Acceptable
+
next => {
+    request('GET', `${uri}/not-acceptable`).end((err, res) => {
+      try {
+        assert(err);
+        assert(res.notAcceptable, 'response should be .notAcceptable');
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
request() GET 204 No Content
+
next => {
+    request('GET', `${uri}/no-content`).end((err, res) => {
+      try {
+        assert.ifError(err);
+        assert(res.noContent, 'response should be .noContent');
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
request() DELETE 204 No Content
+
next => {
+    request('DELETE', `${uri}/no-content`).end((err, res) => {
+      try {
+        assert.ifError(err);
+        assert(res.noContent, 'response should be .noContent');
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
request() header parsing
+
next => {
+    request('GET', `${uri}/notfound`).end((err, res) => {
+      try {
+        assert(err);
+        assert.equal('text/html; charset=utf-8', res.header['content-type']);
+        assert.equal('Express', res.header['x-powered-by']);
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
request() .status
+
next => {
+    request('GET', `${uri}/notfound`).end((err, res) => {
+      try {
+        assert(err);
+        assert.equal(404, res.status, 'response .status');
+        assert.equal(4, res.statusType, 'response .statusType');
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
get()
+
next => {
+    request.get(`${uri}/notfound`).end((err, res) => {
+      try {
+        assert(err);
+        assert.equal(404, res.status, 'response .status');
+        assert.equal(4, res.statusType, 'response .statusType');
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
put()
+
next => {
+    request.put(`${uri}/user/12`).end((err, res) => {
+      try {
+        assert.equal('updated', res.text, 'response text');
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
put().send()
+
next => {
+    request
+      .put(`${uri}/user/13/body`)
+      .send({ user: 'new' })
+      .end((err, res) => {
+        try {
+          assert.equal('received new', res.text, 'response text');
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
post()
+
next => {
+    request.post(`${uri}/user`).end((err, res) => {
+      try {
+        assert.equal('created', res.text, 'response text');
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
del()
+
next => {
+    request.del(`${uri}/user/12`).end((err, res) => {
+      try {
+        assert.equal('deleted', res.text, 'response text');
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
delete()
+
next => {
+    request.delete(`${uri}/user/12`).end((err, res) => {
+      try {
+        assert.equal('deleted', res.text, 'response text');
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
post() data
+
next => {
+    request
+      .post(`${uri}/todo/item`)
+      .type('application/octet-stream')
+      .send('tobi')
+      .end((err, res) => {
+        try {
+          assert.equal('added "tobi"', res.text, 'response text');
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
request .type()
+
next => {
+    request
+      .post(`${uri}/user/12/pet`)
+      .type('urlencoded')
+      .send('pet=tobi')
+      .end((err, res) => {
+        try {
+          assert.equal('added pet "tobi"', res.text, 'response text');
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
request .type() with alias
+
next => {
+    request
+      .post(`${uri}/user/12/pet`)
+      .type('application/x-www-form-urlencoded')
+      .send('pet=tobi')
+      .end((err, res) => {
+        try {
+          assert.equal('added pet "tobi"', res.text, 'response text');
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
request .get() with no data or callback
+
next => {
+    request.get(`${uri}/echo-header/content-type`);
+    next();
+  }
+
request .send() with no data only
+
next => {
+    request
+      .post(`${uri}/user/5/pet`)
+      .type('urlencoded')
+      .send('pet=tobi');
+    next();
+  }
+
request .send() with callback only
+
next => {
+    request
+      .get(`${uri}/echo-header/accept`)
+      .set('Accept', 'foo/bar')
+      .end((err, res) => {
+        try {
+          assert.equal('foo/bar', res.text);
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
request .accept() with json
+
next => {
+    request
+      .get(`${uri}/echo-header/accept`)
+      .accept('json')
+      .end((err, res) => {
+        try {
+          assert.equal('application/json', res.text);
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
request .accept() with application/json
+
next => {
+    request
+      .get(`${uri}/echo-header/accept`)
+      .accept('application/json')
+      .end((err, res) => {
+        try {
+          assert.equal('application/json', res.text);
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
request .accept() with xml
+
next => {
+    request
+      .get(`${uri}/echo-header/accept`)
+      .accept('xml')
+      .end((err, res) => {
+        try {
+          // We can't depend on mime module to be consistent with this
+          assert(res.text == 'application/xml' || res.text == 'text/xml');
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
request .accept() with application/xml
+
next => {
+    request
+      .get(`${uri}/echo-header/accept`)
+      .accept('application/xml')
+      .end((err, res) => {
+        try {
+          assert.equal('application/xml', res.text);
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
request .end()
+
next => {
+    request
+      .put(`${uri}/echo-header/content-type`)
+      .set('Content-Type', 'text/plain')
+      .send('wahoo')
+      .end((err, res) => {
+        try {
+          assert.equal('text/plain', res.text);
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
request .send()
+
next => {
+    request
+      .put(`${uri}/echo-header/content-type`)
+      .set('Content-Type', 'text/plain')
+      .send('wahoo')
+      .end((err, res) => {
+        try {
+          assert.equal('text/plain', res.text);
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
request .set()
+
next => {
+    request
+      .put(`${uri}/echo-header/content-type`)
+      .set('Content-Type', 'text/plain')
+      .send('wahoo')
+      .end((err, res) => {
+        try {
+          assert.equal('text/plain', res.text);
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
request .set(object)
+
next => {
+    request
+      .put(`${uri}/echo-header/content-type`)
+      .set({ 'Content-Type': 'text/plain' })
+      .send('wahoo')
+      .end((err, res) => {
+        try {
+          assert.equal('text/plain', res.text);
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
POST urlencoded
+
next => {
+    request
+      .post(`${uri}/pet`)
+      .type('urlencoded')
+      .send({ name: 'Manny', species: 'cat' })
+      .end((err, res) => {
+        try {
+          assert.equal('added Manny the cat', res.text);
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
POST json
+
next => {
+    request
+      .post(`${uri}/pet`)
+      .type('json')
+      .send({ name: 'Manny', species: 'cat' })
+      .end((err, res) => {
+        try {
+          assert.equal('added Manny the cat', res.text);
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
POST json array
+
next => {
+    request
+      .post(`${uri}/echo`)
+      .send([1, 2, 3])
+      .end((err, res) => {
+        try {
+          assert.equal(
+            'application/json',
+            res.header['content-type'].split(';')[0]
+          );
+          assert.equal('[1,2,3]', res.text);
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
POST json default
+
next => {
+    request
+      .post(`${uri}/pet`)
+      .send({ name: 'Manny', species: 'cat' })
+      .end((err, res) => {
+        try {
+          assert.equal('added Manny the cat', res.text);
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
POST json contentType charset
+
next => {
+    request
+      .post(`${uri}/echo`)
+      .set('Content-Type', 'application/json; charset=UTF-8')
+      .send({ data: ['data1', 'data2'] })
+      .end((err, res) => {
+        try {
+          assert.equal('{"data":["data1","data2"]}', res.text);
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
POST json contentType vendor
+
next => {
+    request
+      .post(`${uri}/echo`)
+      .set('Content-Type', 'application/vnd.example+json')
+      .send({ data: ['data1', 'data2'] })
+      .end((err, res) => {
+        try {
+          assert.equal('{"data":["data1","data2"]}', res.text);
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
POST multiple .send() calls
+
next => {
+    request
+      .post(`${uri}/pet`)
+      .send({ name: 'Manny' })
+      .send({ species: 'cat' })
+      .end((err, res) => {
+        try {
+          assert.equal('added Manny the cat', res.text);
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
POST multiple .send() strings
+
next => {
+    request
+      .post(`${uri}/echo`)
+      .send('user[name]=tj')
+      .send('user[email]=tj@vision-media.ca')
+      .end((err, res) => {
+        try {
+          assert.equal(
+            'application/x-www-form-urlencoded',
+            res.header['content-type'].split(';')[0]
+          );
+          assert.equal(
+            res.text,
+            'user[name]=tj&user[email]=tj@vision-media.ca'
+          );
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
POST with no data
+
next => {
+    request
+      .post(`${uri}/empty-body`)
+      .send()
+      .end((err, res) => {
+        try {
+          assert.ifError(err);
+          assert(res.noContent, 'response should be .noContent');
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
GET .type
+
next => {
+    request.get(`${uri}/pets`).end((err, res) => {
+      try {
+        assert.equal('application/json', res.type);
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
GET Content-Type params
+
next => {
+    request.get(`${uri}/text`).end((err, res) => {
+      try {
+        assert.equal('utf-8', res.charset);
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
GET json
+
next => {
+    request.get(`${uri}/pets`).end((err, res) => {
+      try {
+        assert.deepEqual(res.body, ['tobi', 'loki', 'jane']);
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
GET json-seq
+
next => {
+    request
+      .get(`${uri}/json-seq`)
+      .buffer()
+      .end((err, res) => {
+        try {
+          assert.ifError(err);
+          assert.deepEqual(res.text, '\u001E{"id":1}\n\u001E{"id":2}\n');
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
GET x-www-form-urlencoded
+
next => {
+    request.get(`${uri}/foo`).end((err, res) => {
+      try {
+        assert.deepEqual(res.body, { foo: 'bar' });
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
GET shorthand
+
next => {
+    request.get(`${uri}/foo`, (err, res) => {
+      try {
+        assert.equal('foo=bar', res.text);
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
POST shorthand
+
next => {
+    request.post(`${uri}/user/0/pet`, { pet: 'tobi' }, (err, res) => {
+      try {
+        assert.equal('added pet "tobi"', res.text);
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
POST shorthand without callback
+
next => {
+    request.post(`${uri}/user/0/pet`, { pet: 'tobi' }).end((err, res) => {
+      try {
+        assert.equal('added pet "tobi"', res.text);
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
GET querystring object with array
+
next => {
+    request
+      .get(`${uri}/querystring`)
+      .query({ val: ['a', 'b', 'c'] })
+      .end((err, res) => {
+        try {
+          assert.deepEqual(res.body, { val: ['a', 'b', 'c'] });
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
GET querystring object with array and primitives
+
next => {
+    request
+      .get(`${uri}/querystring`)
+      .query({ array: ['a', 'b', 'c'], string: 'foo', number: 10 })
+      .end((err, res) => {
+        try {
+          assert.deepEqual(res.body, {
+            array: ['a', 'b', 'c'],
+            string: 'foo',
+            number: 10
+          });
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
GET querystring object with two arrays
+
next => {
+    request
+      .get(`${uri}/querystring`)
+      .query({ array1: ['a', 'b', 'c'], array2: [1, 2, 3] })
+      .end((err, res) => {
+        try {
+          assert.deepEqual(res.body, {
+            array1: ['a', 'b', 'c'],
+            array2: [1, 2, 3]
+          });
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
GET querystring object
+
next => {
+    request
+      .get(`${uri}/querystring`)
+      .query({ search: 'Manny' })
+      .end((err, res) => {
+        try {
+          assert.deepEqual(res.body, { search: 'Manny' });
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
GET querystring append original
+
next => {
+    request
+      .get(`${uri}/querystring?search=Manny`)
+      .query({ range: '1..5' })
+      .end((err, res) => {
+        try {
+          assert.deepEqual(res.body, { search: 'Manny', range: '1..5' });
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
GET querystring multiple objects
+
next => {
+    request
+      .get(`${uri}/querystring`)
+      .query({ search: 'Manny' })
+      .query({ range: '1..5' })
+      .query({ order: 'desc' })
+      .end((err, res) => {
+        try {
+          assert.deepEqual(res.body, {
+            search: 'Manny',
+            range: '1..5',
+            order: 'desc'
+          });
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
GET querystring with strings
+
next => {
+    request
+      .get(`${uri}/querystring`)
+      .query('search=Manny')
+      .query('range=1..5')
+      .query('order=desc')
+      .end((err, res) => {
+        try {
+          assert.deepEqual(res.body, {
+            search: 'Manny',
+            range: '1..5',
+            order: 'desc'
+          });
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
GET querystring with strings and objects
+
next => {
+    request
+      .get(`${uri}/querystring`)
+      .query('search=Manny')
+      .query({ order: 'desc', range: '1..5' })
+      .end((err, res) => {
+        try {
+          assert.deepEqual(res.body, {
+            search: 'Manny',
+            range: '1..5',
+            order: 'desc'
+          });
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      });
+  }
+
GET shorthand payload goes to querystring
+
next => {
+    request.get(
+      `${uri}/querystring`,
+      { foo: 'FOO', bar: 'BAR' },
+      (err, res) => {
+        try {
+          assert.deepEqual(res.body, { foo: 'FOO', bar: 'BAR' });
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      }
+    );
+  }
+
HEAD shorthand payload goes to querystring
+
next => {
+    request.head(
+      `${uri}/querystring-in-header`,
+      { foo: 'FOO', bar: 'BAR' },
+      (err, res) => {
+        try {
+          assert.deepEqual(JSON.parse(res.headers.query), {
+            foo: 'FOO',
+            bar: 'BAR'
+          });
+          next();
+        } catch (err2) {
+          next(err2);
+        }
+      }
+    );
+  }
+
request(method, url)
+
next => {
+    request('GET', `${uri}/foo`).end((err, res) => {
+      try {
+        assert.equal('bar', res.body.foo);
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
request(url)
+
next => {
+    request(`${uri}/foo`).end((err, res) => {
+      try {
+        assert.equal('bar', res.body.foo);
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
request(url, fn)
+
next => {
+    request(`${uri}/foo`, (err, res) => {
+      try {
+        assert.equal('bar', res.body.foo);
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
req.timeout(ms)
+
next => {
+    const req = request.get(`${uri}/delay/3000`).timeout(1000);
+    req.end((err, res) => {
+      try {
+        assert(err, 'error missing');
+        assert.equal(1000, err.timeout, 'err.timeout missing');
+        assert.equal(
+          'Timeout of 1000ms exceeded',
+          err.message,
+          'err.message incorrect'
+        );
+        assert.equal(null, res);
+        assert(req.timedout, true);
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
req.timeout(ms) with redirect
+
next => {
+    const req = request.get(`${uri}/delay/const`).timeout(1000);
+    req.end((err, res) => {
+      try {
+        assert(err, 'error missing');
+        assert.equal(1000, err.timeout, 'err.timeout missing');
+        assert.equal(
+          'Timeout of 1000ms exceeded',
+          err.message,
+          'err.message incorrect'
+        );
+        assert.equal(null, res);
+        assert(req.timedout, true);
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
request event
+
next => {
+    request
+      .get(`${uri}/foo`)
+      .on('request', req => {
+        try {
+          assert.equal(`${uri}/foo`, req.url);
+          next();
+        } catch (err) {
+          next(err);
+        }
+      })
+      .end();
+  }
+
response event
+
next => {
+    request
+      .get(`${uri}/foo`)
+      .on('response', res => {
+        try {
+          assert.equal('bar', res.body.foo);
+          next();
+        } catch (err) {
+          next(err);
+        }
+      })
+      .end();
+  }
+
response should set statusCode
+
next => {
+    request.get(`${uri}/ok`, (err, res) => {
+      try {
+        assert.strictEqual(res.statusCode, 200);
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
req.toJSON()
+
next => {
+    request.get(`${uri}/ok`).end((err, res) => {
+      try {
+        const j = (res.request || res.req).toJSON();
+        ['url', 'method', 'data', 'headers'].forEach(prop => {
+          assert(j.hasOwnProperty(prop));
+        });
+        next();
+      } catch (err2) {
+        next(err2);
+      }
+    });
+  }
+
+
+
+

.retry(count)

+
+
should not retry if passed "0"
+
done => {
+    request
+      .get(`${base}/error`)
+      .retry(0)
+      .end((err, res) => {
+        try {
+          assert(err, 'expected an error');
+          assert.equal(
+            undefined,
+            err.retries,
+            'expected an error without .retries'
+          );
+          assert.equal(500, err.status, 'expected an error status of 500');
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+  }
+
should not retry if passed an invalid number
+
done => {
+    request
+      .get(`${base}/error`)
+      .retry(-2)
+      .end((err, res) => {
+        try {
+          assert(err, 'expected an error');
+          assert.equal(
+            undefined,
+            err.retries,
+            'expected an error without .retries'
+          );
+          assert.equal(500, err.status, 'expected an error status of 500');
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+  }
+
should not retry if passed undefined
+
done => {
+    request
+      .get(`${base}/error`)
+      .retry(undefined)
+      .end((err, res) => {
+        try {
+          assert(err, 'expected an error');
+          assert.equal(
+            undefined,
+            err.retries,
+            'expected an error without .retries'
+          );
+          assert.equal(500, err.status, 'expected an error status of 500');
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+  }
+
should handle server error after repeat attempt
+
done => {
+    request
+      .get(`${base}/error`)
+      .retry(2)
+      .end((err, res) => {
+        try {
+          assert(err, 'expected an error');
+          assert.equal(2, err.retries, 'expected an error with .retries');
+          assert.equal(500, err.status, 'expected an error status of 500');
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+  }
+
should retry if passed nothing
+
done => {
+    request
+      .get(`${base}/error`)
+      .retry()
+      .end((err, res) => {
+        try {
+          assert(err, 'expected an error');
+          assert.equal(1, err.retries, 'expected an error with .retries');
+          assert.equal(500, err.status, 'expected an error status of 500');
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+  }
+
should retry if passed "true"
+
done => {
+    request
+      .get(`${base}/error`)
+      .retry(true)
+      .end((err, res) => {
+        try {
+          assert(err, 'expected an error');
+          assert.equal(1, err.retries, 'expected an error with .retries');
+          assert.equal(500, err.status, 'expected an error status of 500');
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+  }
+
should handle successful request after repeat attempt from server error
+
done => {
+    request
+      .get(`${base}/error/ok/${uniqid()}`)
+      .query({ qs: 'present' })
+      .retry(2)
+      .end((err, res) => {
+        try {
+          assert.ifError(err);
+          assert(res.ok, 'response should be ok');
+          assert(res.text, 'res.text');
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+  }
+
should handle server timeout error after repeat attempt
+
done => {
+    request
+      .get(`${base}/delay/400`)
+      .timeout(200)
+      .retry(2)
+      .end((err, res) => {
+        try {
+          assert(err, 'expected an error');
+          assert.equal(2, err.retries, 'expected an error with .retries');
+          assert.equal(
+            'number',
+            typeof err.timeout,
+            'expected an error with .timeout'
+          );
+          assert.equal('ECONNABORTED', err.code, 'expected abort error code');
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+  }
+
should handle successful request after repeat attempt from server timeout
+
done => {
+    const url = `/delay/1200/ok/${uniqid()}?built=in`;
+    request
+      .get(base + url)
+      .query('string=ified')
+      .query({ json: 'ed' })
+      .timeout(600)
+      .retry(2)
+      .end((err, res) => {
+        try {
+          assert.ifError(err);
+          assert(res.ok, 'response should be ok');
+          assert.equal(res.text, `ok = ${url}&string=ified&json=ed`);
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+  }
+
should correctly abort a retry attempt
+
done => {
+    let aborted = false;
+    const req = request
+      .get(`${base}/delay/400`)
+      .timeout(200)
+      .retry(2);
+    req.end((err, res) => {
+      try {
+        assert(false, 'should not complete the request');
+      } catch (err2) {
+        done(err2);
+      }
+    });
+    req.on('abort', () => {
+      aborted = true;
+    });
+    setTimeout(() => {
+      req.abort();
+      setTimeout(() => {
+        try {
+          assert(aborted, 'should be aborted');
+          done();
+        } catch (err) {
+          done(err);
+        }
+      }, 150);
+    }, 150);
+  }
+
should correctly retain header fields
+
done => {
+    request
+      .get(`${base}/error/ok/${uniqid()}`)
+      .query({ qs: 'present' })
+      .retry(2)
+      .set('X-Foo', 'bar')
+      .end((err, res) => {
+        try {
+          assert.ifError(err);
+          assert(res.body);
+          res.body.should.have.property('x-foo', 'bar');
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+  }
+
should not retry on 4xx responses
+
done => {
+    request
+      .get(`${base}/bad-request`)
+      .retry(2)
+      .end((err, res) => {
+        try {
+          assert(err, 'expected an error');
+          assert.equal(0, err.retries, 'expected an error with 0 .retries');
+          assert.equal(400, err.status, 'expected an error status of 400');
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+  }
+
should execute callback on retry if passed
+
done => {
+    let callbackCallCount = 0;
+    function retryCallback(request) {
+      callbackCallCount++;
+    }
+    request
+      .get(`${base}/error`)
+      .retry(2, retryCallback)
+      .end((err, res) => {
+        try {
+          assert(err, 'expected an error');
+          assert.equal(2, err.retries, 'expected an error with .retries');
+          assert.equal(500, err.status, 'expected an error status of 500');
+          assert.equal(
+            2,
+            callbackCallCount,
+            'expected the callback to be called on each retry'
+          );
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+  }
+
+
+
+

.timeout(ms)

+
+
+

when timeout is exceeded

+
+
should error
+
done => {
+      request
+        .get(`${base}/delay/500`)
+        .timeout(150)
+        .end((err, res) => {
+          assert(err, 'expected an error');
+          assert.equal(
+            'number',
+            typeof err.timeout,
+            'expected an error with .timeout'
+          );
+          assert.equal('ECONNABORTED', err.code, 'expected abort error code');
+          done();
+        });
+    }
+
should handle gzip timeout
+
done => {
+      request
+        .get(`${base}/delay/zip`)
+        .timeout(150)
+        .end((err, res) => {
+          assert(err, 'expected an error');
+          assert.equal(
+            'number',
+            typeof err.timeout,
+            'expected an error with .timeout'
+          );
+          assert.equal('ECONNABORTED', err.code, 'expected abort error code');
+          done();
+        });
+    }
+
should handle buffer timeout
+
done => {
+      request
+        .get(`${base}/delay/json`)
+        .buffer(true)
+        .timeout(150)
+        .end((err, res) => {
+          assert(err, 'expected an error');
+          assert.equal(
+            'number',
+            typeof err.timeout,
+            'expected an error with .timeout'
+          );
+          assert.equal('ECONNABORTED', err.code, 'expected abort error code');
+          done();
+        });
+    }
+
should error on deadline
+
done => {
+      request
+        .get(`${base}/delay/500`)
+        .timeout({ deadline: 150 })
+        .end((err, res) => {
+          assert(err, 'expected an error');
+          assert.equal(
+            'number',
+            typeof err.timeout,
+            'expected an error with .timeout'
+          );
+          assert.equal('ECONNABORTED', err.code, 'expected abort error code');
+          done();
+        });
+    }
+
should support setting individual options
+
done => {
+      request
+        .get(`${base}/delay/500`)
+        .timeout({ deadline: 10 })
+        .timeout({ response: 99999 })
+        .end((err, res) => {
+          assert(err, 'expected an error');
+          assert.equal('ECONNABORTED', err.code, 'expected abort error code');
+          assert.equal('ETIME', err.errno);
+          done();
+        });
+    }
+
should error on response
+
done => {
+      request
+        .get(`${base}/delay/500`)
+        .timeout({ response: 150 })
+        .end((err, res) => {
+          assert(err, 'expected an error');
+          assert.equal(
+            'number',
+            typeof err.timeout,
+            'expected an error with .timeout'
+          );
+          assert.equal('ECONNABORTED', err.code, 'expected abort error code');
+          assert.equal('ETIMEDOUT', err.errno);
+          done();
+        });
+    }
+
should accept slow body with fast response
+
done => {
+      request
+        .get(`${base}/delay/slowbody`)
+        .timeout({ response: 1000 })
+        .on('progress', () => {
+          // This only makes the test faster without relying on arbitrary timeouts
+          request.get(`${base}/delay/slowbody/finish`).end();
+        })
+        .end(done);
+    }
+
+
+
+
+
+

request

+
+
+

use

+
+
should use plugin success
+
done => {
+      const now = `${Date.now()}`;
+      function uuid(req) {
+        req.set('X-UUID', now);
+        return req;
+      }
+      function prefix(req) {
+        req.url = uri + req.url;
+        return req;
+      }
+      request
+        .get('/echo')
+        .use(uuid)
+        .use(prefix)
+        .end((err, res) => {
+          assert.strictEqual(res.statusCode, 200);
+          assert.equal(res.get('X-UUID'), now);
+          done();
+        });
+    }
+
+
+
+
+
+

subclass

+
+
should be an instance of Request
+
const req = request.get('/');
+assert(req instanceof request.Request);
+
should use patched subclass
+
assert(OriginalRequest);
+let constructorCalled;
+let sendCalled;
+function NewRequest(...args) {
+  constructorCalled = true;
+  OriginalRequest.apply(this, args);
+}
+NewRequest.prototype = Object.create(OriginalRequest.prototype);
+NewRequest.prototype.send = function() {
+  sendCalled = true;
+  return this;
+};
+request.Request = NewRequest;
+const req = request.get('/').send();
+assert(constructorCalled);
+assert(sendCalled);
+assert(req instanceof NewRequest);
+assert(req instanceof OriginalRequest);
+
should use patched subclass in agent too
+
if (!request.agent) return; // Node-only
+function NewRequest(...args) {
+  OriginalRequest.apply(this, args);
+}
+NewRequest.prototype = Object.create(OriginalRequest.prototype);
+request.Request = NewRequest;
+const req = request.agent().del('/');
+assert(req instanceof NewRequest);
+assert(req instanceof OriginalRequest);
+
+
+
+

request

+
+
+

persistent agent

+
+
should gain a session on POST
+
agent3.post(`${base}/signin`).then(res => {
+        res.should.have.status(200);
+        should.not.exist(res.headers['set-cookie']);
+        res.text.should.containEql('dashboard');
+      })
+
should start with empty session (set cookies)
+
done => {
+      agent1.get(`${base}/dashboard`).end((err, res) => {
+        should.exist(err);
+        res.should.have.status(401);
+        should.exist(res.headers['set-cookie']);
+        done();
+      });
+    }
+
should gain a session (cookies already set)
+
agent1.post(`${base}/signin`).then(res => {
+        res.should.have.status(200);
+        should.not.exist(res.headers['set-cookie']);
+        res.text.should.containEql('dashboard');
+      })
+
should persist cookies across requests
+
agent1.get(`${base}/dashboard`).then(res => {
+        res.should.have.status(200);
+      })
+
should have the cookie set in the end callback
+
agent4
+        .post(`${base}/setcookie`)
+        .then(() => agent4.get(`${base}/getcookie`))
+        .then(res => {
+          res.should.have.status(200);
+          assert.strictEqual(res.text, 'jar');
+        })
+
should not share cookies
+
done => {
+      agent2.get(`${base}/dashboard`).end((err, res) => {
+        should.exist(err);
+        res.should.have.status(401);
+        done();
+      });
+    }
+
should not lose cookies between agents
+
agent1.get(`${base}/dashboard`).then(res => {
+        res.should.have.status(200);
+      })
+
should be able to follow redirects
+
agent1.get(base).then(res => {
+        res.should.have.status(200);
+        res.text.should.containEql('dashboard');
+      })
+
should be able to post redirects
+
agent1
+        .post(`${base}/redirect`)
+        .send({ foo: 'bar', baz: 'blaaah' })
+        .then(res => {
+          res.should.have.status(200);
+          res.text.should.containEql('simple');
+          res.redirects.should.eql([`${base}/simple`]);
+        })
+
should be able to limit redirects
+
done => {
+      agent1
+        .get(base)
+        .redirects(0)
+        .end((err, res) => {
+          should.exist(err);
+          res.should.have.status(302);
+          res.redirects.should.eql([]);
+          res.header.location.should.equal('/dashboard');
+          done();
+        });
+    }
+
should be able to create a new session (clear cookie)
+
agent1.post(`${base}/signout`).then(res => {
+        res.should.have.status(200);
+        should.exist(res.headers['set-cookie']);
+      })
+
should regenerate with an empty session
+
done => {
+      agent1.get(`${base}/dashboard`).end((err, res) => {
+        should.exist(err);
+        res.should.have.status(401);
+        should.not.exist(res.headers['set-cookie']);
+        done();
+      });
+    }
+
+
+
+
+
+

Basic auth

+
+
+

when credentials are present in url

+
+
should set Authorization
+
done => {
+      const new_url = URL.parse(base);
+      new_url.auth = 'tobi:learnboost';
+      new_url.pathname = '/basic-auth';
+      request.get(URL.format(new_url)).end((err, res) => {
+        res.status.should.equal(200);
+        done();
+      });
+    }
+
+
+
+

req.auth(user, pass)

+
+
should set Authorization
+
done => {
+      request
+        .get(`${base}/basic-auth`)
+        .auth('tobi', 'learnboost')
+        .end((err, res) => {
+          res.status.should.equal(200);
+          done();
+        });
+    }
+
+
+
+

req.auth(user + ":" + pass)

+
+
should set authorization
+
done => {
+      request
+        .get(`${base}/basic-auth/again`)
+        .auth('tobi')
+        .end((err, res) => {
+          res.status.should.eql(200);
+          done();
+        });
+    }
+
+
+
+
+
+

[node] request

+
+
should send body with .get().send()
+
next => {
+      request
+        .get(`${base}/echo`)
+        .set('Content-Type', 'text/plain')
+        .send('wahoo')
+        .end((err, res) => {
+          try {
+            assert.equal('wahoo', res.text);
+            next();
+          } catch (err2) {
+            next(err2);
+          }
+        });
+    }
+
+

with an url

+
+
should preserve the encoding of the url
+
done => {
+      request.get(`${base}/url?a=(b%29`).end((err, res) => {
+        assert.equal('/url?a=(b%29', res.text);
+        done();
+      });
+    }
+
+
+
+

with an object

+
+
should format the url
+
request.get(url.parse(`${base}/login`)).then(res => {
+        assert(res.ok);
+      })
+
+
+
+

without a schema

+
+
should default to http
+
request.get('localhost:5000/login').then(res => {
+        assert.equal(res.status, 200);
+      })
+
+
+
+

res.toJSON()

+
+
should describe the response
+
request
+        .post(`${base}/echo`)
+        .send({ foo: 'baz' })
+        .then(res => {
+          const obj = res.toJSON();
+          assert.equal('object', typeof obj.header);
+          assert.equal('object', typeof obj.req);
+          assert.equal(200, obj.status);
+          assert.equal('{"foo":"baz"}', obj.text);
+        })
+
+
+
+

res.links

+
+
should default to an empty object
+
request.get(`${base}/login`).then(res => {
+        res.links.should.eql({});
+      })
+
should parse the Link header field
+
done => {
+      request.get(`${base}/links`).end((err, res) => {
+        res.links.next.should.equal(
+          'https://api.github.com/repos/visionmedia/mocha/issues?page=2'
+        );
+        done();
+      });
+    }
+
+
+
+

req.unset(field)

+
+
should remove the header field
+
done => {
+      request
+        .post(`${base}/echo`)
+        .unset('User-Agent')
+        .end((err, res) => {
+          assert.equal(void 0, res.header['user-agent']);
+          done();
+        });
+    }
+
+
+
+

case-insensitive

+
+
should set/get header fields case-insensitively
+
const r = request.post(`${base}/echo`);
+r.set('MiXeD', 'helloes');
+assert.strictEqual(r.get('mixed'), 'helloes');
+
should unset header fields case-insensitively
+
const r = request.post(`${base}/echo`);
+r.set('MiXeD', 'helloes');
+r.unset('MIXED');
+assert.strictEqual(r.get('mixed'), undefined);
+
+
+
+

req.write(str)

+
+
should write the given data
+
done => {
+      const req = request.post(`${base}/echo`);
+      req.set('Content-Type', 'application/json');
+      assert.equal('boolean', typeof req.write('{"name"'));
+      assert.equal('boolean', typeof req.write(':"tobi"}'));
+      req.end((err, res) => {
+        res.text.should.equal('{"name":"tobi"}');
+        done();
+      });
+    }
+
+
+
+

req.pipe(stream)

+
+
should pipe the response to the given stream
+
done => {
+      const stream = new EventEmitter();
+      stream.buf = '';
+      stream.writable = true;
+      stream.write = function(chunk) {
+        this.buf += chunk;
+      };
+      stream.end = function() {
+        this.buf.should.equal('{"name":"tobi"}');
+        done();
+      };
+      request
+        .post(`${base}/echo`)
+        .send('{"name":"tobi"}')
+        .pipe(stream);
+    }
+
+
+
+

.buffer()

+
+
should enable buffering
+
done => {
+      request
+        .get(`${base}/custom`)
+        .buffer()
+        .end((err, res) => {
+          assert.ifError(err);
+          assert.equal('custom stuff', res.text);
+          assert(res.buffered);
+          done();
+        });
+    }
+
should take precedence over request.buffer['someMimeType'] = false
+
done => {
+      const type = 'application/barbaz';
+      const send = 'some text';
+      request.buffer[type] = false;
+      request
+        .post(`${base}/echo`)
+        .type(type)
+        .send(send)
+        .buffer()
+        .end((err, res) => {
+          delete request.buffer[type];
+          assert.ifError(err);
+          assert.equal(res.type, type);
+          assert.equal(send, res.text);
+          assert(res.buffered);
+          done();
+        });
+    }
+
+
+
+

.buffer(false)

+
+
should disable buffering
+
done => {
+      request
+        .post(`${base}/echo`)
+        .type('application/x-dog')
+        .send('hello this is dog')
+        .buffer(false)
+        .end((err, res) => {
+          assert.ifError(err);
+          assert.equal(null, res.text);
+          res.body.should.eql({});
+          let buf = '';
+          res.setEncoding('utf8');
+          res.on('data', chunk => {
+            buf += chunk;
+          });
+          res.on('end', () => {
+            buf.should.equal('hello this is dog');
+            done();
+          });
+        });
+    }
+
should take precedence over request.buffer['someMimeType'] = true
+
done => {
+      const type = 'application/foobar';
+      const send = 'hello this is a dog';
+      request.buffer[type] = true;
+      request
+        .post(`${base}/echo`)
+        .type(type)
+        .send(send)
+        .buffer(false)
+        .end((err, res) => {
+          delete request.buffer[type];
+          assert.ifError(err);
+          assert.equal(null, res.text);
+          assert.equal(res.type, type);
+          assert(!res.buffered);
+          res.body.should.eql({});
+          let buf = '';
+          res.setEncoding('utf8');
+          res.on('data', chunk => {
+            buf += chunk;
+          });
+          res.on('end', () => {
+            buf.should.equal(send);
+            done();
+          });
+        });
+    }
+
+
+
+

.withCredentials()

+
+
should not throw an error when using the client-side "withCredentials" method
+
done => {
+      request
+        .get(`${base}/custom`)
+        .withCredentials()
+        .end((err, res) => {
+          assert.ifError(err);
+          done();
+        });
+    }
+
+
+
+

.agent()

+
+
should return the defaut agent
+
done => {
+      const req = request.post(`${base}/echo`);
+      req.agent().should.equal(false);
+      done();
+    }
+
+
+
+

.agent(undefined)

+
+
should set an agent to undefined and ensure it is chainable
+
done => {
+      const req = request.get(`${base}/echo`);
+      const ret = req.agent(undefined);
+      ret.should.equal(req);
+      assert.strictEqual(req.agent(), undefined);
+      done();
+    }
+
+
+
+

.agent(new http.Agent())

+
+
should set passed agent
+
done => {
+      const http = require('http');
+      const req = request.get(`${base}/echo`);
+      const agent = new http.Agent();
+      const ret = req.agent(agent);
+      ret.should.equal(req);
+      req.agent().should.equal(agent);
+      done();
+    }
+
+
+
+

with a content type other than application/json or text/*

+
+
should still use buffering
+
return request
+  .post(`${base}/echo`)
+  .type('application/x-dog')
+  .send('hello this is dog')
+  .then(res => {
+    assert.equal(null, res.text);
+    assert.equal(res.body.toString(), 'hello this is dog');
+    res.buffered.should.be.true;
+  });
+
+
+
+

content-length

+
+
should be set to the byte length of a non-buffer object
+
done => {
+      const decoder = new StringDecoder('utf8');
+      let img = fs.readFileSync(`${__dirname}/fixtures/test.png`);
+      img = decoder.write(img);
+      request
+        .post(`${base}/echo`)
+        .type('application/x-image')
+        .send(img)
+        .buffer(false)
+        .end((err, res) => {
+          assert.ifError(err);
+          assert(!res.buffered);
+          assert.equal(res.header['content-length'], Buffer.byteLength(img));
+          done();
+        });
+    }
+
should be set to the length of a buffer object
+
done => {
+      const img = fs.readFileSync(`${__dirname}/fixtures/test.png`);
+      request
+        .post(`${base}/echo`)
+        .type('application/x-image')
+        .send(img)
+        .buffer(true)
+        .end((err, res) => {
+          assert.ifError(err);
+          assert(res.buffered);
+          assert.equal(res.header['content-length'], img.length);
+          done();
+        });
+    }
+
+
+
+
+
+

req.buffer['someMimeType']

+
+
should respect that agent.buffer(true) takes precedent
+
done => {
+    const agent = request.agent();
+    agent.buffer(true);
+    const type = 'application/somerandomtype';
+    const send = 'somerandomtext';
+    request.buffer[type] = false;
+    agent
+      .post(`${base}/echo`)
+      .type(type)
+      .send(send)
+      .end((err, res) => {
+        delete request.buffer[type];
+        assert.ifError(err);
+        assert.equal(res.type, type);
+        assert.equal(send, res.text);
+        assert(res.buffered);
+        done();
+      });
+  }
+
should respect that agent.buffer(false) takes precedent
+
done => {
+    const agent = request.agent();
+    agent.buffer(false);
+    const type = 'application/barrr';
+    const send = 'some random text2';
+    request.buffer[type] = true;
+    agent
+      .post(`${base}/echo`)
+      .type(type)
+      .send(send)
+      .end((err, res) => {
+        delete request.buffer[type];
+        assert.ifError(err);
+        assert.equal(null, res.text);
+        assert.equal(res.type, type);
+        assert(!res.buffered);
+        res.body.should.eql({});
+        let buf = '';
+        res.setEncoding('utf8');
+        res.on('data', chunk => {
+          buf += chunk;
+        });
+        res.on('end', () => {
+          buf.should.equal(send);
+          done();
+        });
+      });
+  }
+
should disable buffering for that mimetype when false
+
done => {
+    const type = 'application/bar';
+    const send = 'some random text';
+    request.buffer[type] = false;
+    request
+      .post(`${base}/echo`)
+      .type(type)
+      .send(send)
+      .end((err, res) => {
+        delete request.buffer[type];
+        assert.ifError(err);
+        assert.equal(null, res.text);
+        assert.equal(res.type, type);
+        assert(!res.buffered);
+        res.body.should.eql({});
+        let buf = '';
+        res.setEncoding('utf8');
+        res.on('data', chunk => {
+          buf += chunk;
+        });
+        res.on('end', () => {
+          buf.should.equal(send);
+          done();
+        });
+      });
+  }
+
should enable buffering for that mimetype when true
+
done => {
+    const type = 'application/baz';
+    const send = 'woooo';
+    request.buffer[type] = true;
+    request
+      .post(`${base}/echo`)
+      .type(type)
+      .send(send)
+      .end((err, res) => {
+        delete request.buffer[type];
+        assert.ifError(err);
+        assert.equal(res.type, type);
+        assert.equal(send, res.text);
+        assert(res.buffered);
+        done();
+      });
+  }
+
should fallback to default handling for that mimetype when undefined
+
const type = 'application/bazzz';
+const send = 'woooooo';
+return request
+  .post(`${base}/echo`)
+  .type(type)
+  .send(send)
+  .then(res => {
+    assert.equal(res.type, type);
+    assert.equal(send, res.body.toString());
+    assert(res.buffered);
+  });
+
+
+
+

exports

+
+
should expose .protocols
+
Object.keys(request.protocols).should.eql(['http:', 'https:', 'http2:']);
+
should expose .serialize
+
Object.keys(request.serialize).should.eql([
+  'application/x-www-form-urlencoded',
+  'application/json'
+]);
+
should expose .parse
+
Object.keys(request.parse).should.eql([
+  'application/x-www-form-urlencoded',
+  'application/json',
+  'text',
+  'application/octet-stream',
+  'application/pdf',
+  'image'
+]);
+
should export .buffer
+
Object.keys(request.buffer).should.eql([]);
+
+
+
+

flags

+
+
+

with 4xx response

+
+
should set res.error and res.clientError
+
done => {
+      request.get(`${base}/notfound`).end((err, res) => {
+        assert(err);
+        assert(!res.ok, 'response should not be ok');
+        assert(res.error, 'response should be an error');
+        assert(res.clientError, 'response should be a client error');
+        assert(!res.serverError, 'response should not be a server error');
+        done();
+      });
+    }
+
+
+
+

with 5xx response

+
+
should set res.error and res.serverError
+
done => {
+      request.get(`${base}/error`).end((err, res) => {
+        assert(err);
+        assert(!res.ok, 'response should not be ok');
+        assert(!res.notFound, 'response should not be notFound');
+        assert(res.error, 'response should be an error');
+        assert(!res.clientError, 'response should not be a client error');
+        assert(res.serverError, 'response should be a server error');
+        done();
+      });
+    }
+
+
+
+

with 404 Not Found

+
+
should res.notFound
+
done => {
+      request.get(`${base}/notfound`).end((err, res) => {
+        assert(err);
+        assert(res.notFound, 'response should be .notFound');
+        done();
+      });
+    }
+
+
+
+

with 400 Bad Request

+
+
should set req.badRequest
+
done => {
+      request.get(`${base}/bad-request`).end((err, res) => {
+        assert(err);
+        assert(res.badRequest, 'response should be .badRequest');
+        done();
+      });
+    }
+
+
+
+

with 401 Bad Request

+
+
should set res.unauthorized
+
done => {
+      request.get(`${base}/unauthorized`).end((err, res) => {
+        assert(err);
+        assert(res.unauthorized, 'response should be .unauthorized');
+        done();
+      });
+    }
+
+
+
+

with 406 Not Acceptable

+
+
should set res.notAcceptable
+
done => {
+      request.get(`${base}/not-acceptable`).end((err, res) => {
+        assert(err);
+        assert(res.notAcceptable, 'response should be .notAcceptable');
+        done();
+      });
+    }
+
+
+
+

with 204 No Content

+
+
should set res.noContent
+
done => {
+      request.get(`${base}/no-content`).end((err, res) => {
+        assert(!err);
+        assert(res.noContent, 'response should be .noContent');
+        done();
+      });
+    }
+
+
+
+

with 201 Created

+
+
should set res.created
+
done => {
+      request.post(`${base}/created`).end((err, res) => {
+        assert(!err);
+        assert(res.created, 'response should be .created');
+        done();
+      });
+    }
+
+
+
+

with 422 Unprocessable Entity

+
+
should set res.unprocessableEntity
+
done => {
+      request.post(`${base}/unprocessable-entity`).end((err, res) => {
+        assert(err);
+        assert(
+          res.unprocessableEntity,
+          'response should be .unprocessableEntity'
+        );
+        done();
+      });
+    }
+
+
+
+
+
+

Merging objects

+
+
Don't mix Buffer and JSON
+
assert.throws(() => {
+  request
+    .post('/echo')
+    .send(Buffer.from('some buffer'))
+    .send({ allowed: false });
+});
+
+
+
+

req.send(String)

+
+
should default to "form"
+
done => {
+    request
+      .post(`${base}/echo`)
+      .send('user[name]=tj')
+      .send('user[email]=tj@vision-media.ca')
+      .end((err, res) => {
+        res.header['content-type'].should.equal(
+          'application/x-www-form-urlencoded'
+        );
+        res.body.should.eql({
+          user: { name: 'tj', email: 'tj@vision-media.ca' }
+        });
+        done();
+      });
+  }
+
+
+
+

res.body

+
+
+

application/x-www-form-urlencoded

+
+
should parse the body
+
done => {
+      request.get(`${base}/form-data`).end((err, res) => {
+        res.text.should.equal('pet[name]=manny');
+        res.body.should.eql({ pet: { name: 'manny' } });
+        done();
+      });
+    }
+
+
+
+
+
+

https

+
+
+

certificate authority

+
+
+

request

+
+
should give a good response
+
done => {
+        request
+          .get(testEndpoint)
+          .ca(ca)
+          .end((err, res) => {
+            assert.ifError(err);
+            assert(res.ok);
+            assert.strictEqual('Safe and secure!', res.text);
+            done();
+          });
+      }
+
should reject unauthorized response
+
return request
+  .get(testEndpoint)
+  .trustLocalhost(false)
+  .then(
+    () => {
+      throw new Error('Allows MITM');
+    },
+    () => {}
+  );
+
should trust localhost unauthorized response
+
return request.get(testEndpoint).trustLocalhost(true);
+
should trust overriden localhost unauthorized response
+
return request
+  .get(`https://example.com:${server.address().port}`)
+  .connect('127.0.0.1')
+  .trustLocalhost();
+
+
+
+

.agent

+
+
should be able to make multiple requests without redefining the certificate
+
done => {
+        const agent = request.agent({ ca });
+        agent.get(testEndpoint).end((err, res) => {
+          assert.ifError(err);
+          assert(res.ok);
+          assert.strictEqual('Safe and secure!', res.text);
+          agent.get(url.parse(testEndpoint)).end((err, res) => {
+            assert.ifError(err);
+            assert(res.ok);
+            assert.strictEqual('Safe and secure!', res.text);
+            done();
+          });
+        });
+      }
+
+
+
+
+
+

client certificates

+
+
+

request

+
+
+
+
+

.agent

+
+
+
+
+
+
+
+
+

res.body

+
+
+

image/png

+
+
should parse the body
+
done => {
+      request.get(`${base}/image`).end((err, res) => {
+        res.type.should.equal('image/png');
+        Buffer.isBuffer(res.body).should.be.true();
+        (res.body.length - img.length).should.equal(0);
+        done();
+      });
+    }
+
+
+
+

application/octet-stream

+
+
should parse the body
+
done => {
+      request
+        .get(`${base}/image-as-octets`)
+        .buffer(true) // that's tech debt :(
+        .end((err, res) => {
+          res.type.should.equal('application/octet-stream');
+          Buffer.isBuffer(res.body).should.be.true();
+          (res.body.length - img.length).should.equal(0);
+          done();
+        });
+    }
+
+
+
+

application/octet-stream

+
+
should parse the body (using responseType)
+
done => {
+      request
+        .get(`${base}/image-as-octets`)
+        .responseType('blob')
+        .end((err, res) => {
+          res.type.should.equal('application/octet-stream');
+          Buffer.isBuffer(res.body).should.be.true();
+          (res.body.length - img.length).should.equal(0);
+          done();
+        });
+    }
+
+
+
+
+
+

zlib

+
+
should deflate the content
+
done => {
+    request.get(base).end((err, res) => {
+      res.should.have.status(200);
+      res.text.should.equal(subject);
+      res.headers['content-length'].should.be.below(subject.length);
+      done();
+    });
+  }
+
should protect from zip bombs
+
done => {
+    request
+      .get(base)
+      .buffer(true)
+      .maxResponseSize(1)
+      .end((err, res) => {
+        try {
+          assert.equal('Maximum response size reached', err && err.message);
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+  }
+
should ignore trailing junk
+
done => {
+    request.get(`${base}/junk`).end((err, res) => {
+      res.should.have.status(200);
+      res.text.should.equal(subject);
+      done();
+    });
+  }
+
should ignore missing data
+
done => {
+    request.get(`${base}/chopped`).end((err, res) => {
+      assert.equal(undefined, err);
+      res.should.have.status(200);
+      res.text.should.startWith(subject);
+      done();
+    });
+  }
+
should handle corrupted responses
+
done => {
+    request.get(`${base}/corrupt`).end((err, res) => {
+      assert(err, 'missing error');
+      assert(!res, 'response should not be defined');
+      done();
+    });
+  }
+
should handle no content with gzip header
+
done => {
+    request.get(`${base}/nocontent`).end((err, res) => {
+      assert.ifError(err);
+      assert(res);
+      res.should.have.status(204);
+      res.text.should.equal('');
+      res.headers.should.not.have.property('content-length');
+      done();
+    });
+  }
+
+

without encoding set

+
+
should buffer if asked
+
return request
+  .get(`${base}/binary`)
+  .buffer(true)
+  .then(res => {
+    res.should.have.status(200);
+    assert(res.headers['content-length']);
+    assert(res.body.byteLength);
+    assert.equal(subject, res.body.toString());
+  });
+
should emit buffers
+
done => {
+      request.get(`${base}/binary`).end((err, res) => {
+        res.should.have.status(200);
+        res.headers['content-length'].should.be.below(subject.length);
+        res.on('data', chunk => {
+          chunk.should.have.length(subject.length);
+        });
+        res.on('end', done);
+      });
+    }
+
+
+
+
+
+

Multipart

+
+
+

#field(name, value)

+
+
should set a multipart field value
+
const req = request.post(`${base}/echo`);
+req.field('user[name]', 'tobi');
+req.field('user[age]', '2');
+req.field('user[species]', 'ferret');
+return req.then(res => {
+  res.body['user[name]'].should.equal('tobi');
+  res.body['user[age]'].should.equal('2');
+  res.body['user[species]'].should.equal('ferret');
+});
+
should work with file attachments
+
const req = request.post(`${base}/echo`);
+req.field('name', 'Tobi');
+req.attach('document', 'test/node/fixtures/user.html');
+req.field('species', 'ferret');
+return req.then(res => {
+  res.body.name.should.equal('Tobi');
+  res.body.species.should.equal('ferret');
+  const html = res.files.document;
+  html.name.should.equal('user.html');
+  html.type.should.equal('text/html');
+  read(html.path).should.equal('<h1>name</h1>');
+});
+
+
+
+

#attach(name, path)

+
+
should attach a file
+
const req = request.post(`${base}/echo`);
+req.attach('one', 'test/node/fixtures/user.html');
+req.attach('two', 'test/node/fixtures/user.json');
+req.attach('three', 'test/node/fixtures/user.txt');
+return req.then(res => {
+  const html = res.files.one;
+  const json = res.files.two;
+  const text = res.files.three;
+  html.name.should.equal('user.html');
+  html.type.should.equal('text/html');
+  read(html.path).should.equal('<h1>name</h1>');
+  json.name.should.equal('user.json');
+  json.type.should.equal('application/json');
+  read(json.path).should.equal('{"name":"tobi"}');
+  text.name.should.equal('user.txt');
+  text.type.should.equal('text/plain');
+  read(text.path).should.equal('Tobi');
+});
+
+

when a file does not exist

+
+
should fail the request with an error
+
done => {
+        const req = request.post(`${base}/echo`);
+        req.attach('name', 'foo');
+        req.attach('name2', 'bar');
+        req.attach('name3', 'baz');
+        req.end((err, res) => {
+          assert.ok(Boolean(err), 'Request should have failed.');
+          err.code.should.equal('ENOENT');
+          err.message.should.containEql('ENOENT');
+          err.path.should.equal('foo');
+          done();
+        });
+      }
+
promise should fail
+
return request
+  .post(`${base}/echo`)
+  .field({ a: 1, b: 2 })
+  .attach('c', 'does-not-exist.txt')
+  .then(
+    res => assert.fail('It should not allow this'),
+    err => {
+      err.code.should.equal('ENOENT');
+      err.path.should.equal('does-not-exist.txt');
+    }
+  );
+
should report ECONNREFUSED via the callback
+
done => {
+        request
+          .post('http://127.0.0.1:1') // nobody is listening there
+          .attach('name', 'file-does-not-exist')
+          .end((err, res) => {
+            assert.ok(Boolean(err), 'Request should have failed');
+            err.code.should.equal('ECONNREFUSED');
+            done();
+          });
+      }
+
should report ECONNREFUSED via Promise
+
return request
+  .post('http://127.0.0.1:1') // nobody is listening there
+  .attach('name', 'file-does-not-exist')
+  .then(
+    res => assert.fail('Request should have failed'),
+    err => err.code.should.equal('ECONNREFUSED')
+  );
+
+
+
+
+
+

#attach(name, path, filename)

+
+
should use the custom filename
+
request
+        .post(`${base}/echo`)
+        .attach('document', 'test/node/fixtures/user.html', 'doc.html')
+        .then(res => {
+          const html = res.files.document;
+          html.name.should.equal('doc.html');
+          html.type.should.equal('text/html');
+          read(html.path).should.equal('<h1>name</h1>');
+        })
+
should fire progress event
+
done => {
+      let loaded = 0;
+      let total = 0;
+      let uploadEventWasFired = false;
+      request
+        .post(`${base}/echo`)
+        .attach('document', 'test/node/fixtures/user.html')
+        .on('progress', event => {
+          total = event.total;
+          loaded = event.loaded;
+          if (event.direction === 'upload') {
+            uploadEventWasFired = true;
+          }
+        })
+        .end((err, res) => {
+          if (err) return done(err);
+          const html = res.files.document;
+          html.name.should.equal('user.html');
+          html.type.should.equal('text/html');
+          read(html.path).should.equal('<h1>name</h1>');
+          total.should.equal(223);
+          loaded.should.equal(223);
+          uploadEventWasFired.should.equal(true);
+          done();
+        });
+    }
+
filesystem errors should be caught
+
done => {
+      request
+        .post(`${base}/echo`)
+        .attach('filedata', 'test/node/fixtures/non-existent-file.ext')
+        .end((err, res) => {
+          assert.ok(Boolean(err), 'Request should have failed.');
+          err.code.should.equal('ENOENT');
+          err.path.should.equal('test/node/fixtures/non-existent-file.ext');
+          done();
+        });
+    }
+
+
+
+

#field(name, val)

+
+
should set a multipart field value
+
done => {
+      request
+        .post(`${base}/echo`)
+        .field('first-name', 'foo')
+        .field('last-name', 'bar')
+        .end((err, res) => {
+          if (err) done(err);
+          res.should.be.ok();
+          res.body['first-name'].should.equal('foo');
+          res.body['last-name'].should.equal('bar');
+          done();
+        });
+    }
+
+
+
+

#field(object)

+
+
should set multiple multipart fields
+
done => {
+      request
+        .post(`${base}/echo`)
+        .field({ 'first-name': 'foo', 'last-name': 'bar' })
+        .end((err, res) => {
+          if (err) done(err);
+          res.should.be.ok();
+          res.body['first-name'].should.equal('foo');
+          res.body['last-name'].should.equal('bar');
+          done();
+        });
+    }
+
+
+
+
+
+

with network error

+
+
should error
+
request.get(`http://localhost:${this.port}/`).end((err, res) => {
+  assert(err, 'expected an error');
+  done();
+});
+
+
+
+

request

+
+
+

not modified

+
+
should start with 200
+
done => {
+      request.get(`${base}/if-mod`).end((err, res) => {
+        res.should.have.status(200);
+        res.text.should.match(/^\d+$/);
+        ts = Number(res.text);
+        done();
+      });
+    }
+
should then be 304
+
done => {
+      request
+        .get(`${base}/if-mod`)
+        .set('If-Modified-Since', new Date(ts).toUTCString())
+        .end((err, res) => {
+          res.should.have.status(304);
+          // res.text.should.be.empty
+          done();
+        });
+    }
+
+
+
+
+
+

req.parse(fn)

+
+
should take precedence over default parsers
+
done => {
+    request
+      .get(`${base}/manny`)
+      .parse(request.parse['application/json'])
+      .end((err, res) => {
+        assert(res.ok);
+        assert.equal('{"name":"manny"}', res.text);
+        assert.equal('manny', res.body.name);
+        done();
+      });
+  }
+
should be the only parser
+
request
+      .get(`${base}/image`)
+      .buffer(false)
+      .parse((res, fn) => {
+        res.on('data', () => {});
+      })
+      .then(res => {
+        assert(res.ok);
+        assert.strictEqual(res.text, undefined);
+        res.body.should.eql({});
+      })
+
should emit error if parser throws
+
done => {
+    request
+      .get(`${base}/manny`)
+      .parse(() => {
+        throw new Error('I am broken');
+      })
+      .on('error', err => {
+        err.message.should.equal('I am broken');
+        done();
+      })
+      .end();
+  }
+
should emit error if parser returns an error
+
done => {
+    request
+      .get(`${base}/manny`)
+      .parse((res, fn) => {
+        fn(new Error('I am broken'));
+      })
+      .on('error', err => {
+        err.message.should.equal('I am broken');
+        done();
+      })
+      .end();
+  }
+
should not emit error on chunked json
+
done => {
+      request.get(`${base}/chunked-json`).end(err => {
+        assert.ifError(err);
+        done();
+      });
+    }
+
should not emit error on aborted chunked json
+
done => {
+      const req = request.get(`${base}/chunked-json`);
+      req.end(err => {
+        assert.ifError(err);
+        done();
+      });
+      setTimeout(() => {
+        req.abort();
+      }, 50);
+    }
+
+
+
+

pipe on redirect

+
+
should follow Location
+
done => {
+    const stream = fs.createWriteStream(destPath);
+    const redirects = [];
+    const req = request
+      .get(base)
+      .on('redirect', res => {
+        redirects.push(res.headers.location);
+      })
+      .connect({
+        inapplicable: 'should be ignored'
+      });
+    stream.on('finish', () => {
+      redirects.should.eql(['/movies', '/movies/all', '/movies/all/0']);
+      fs.readFileSync(destPath, 'utf8').should.eql('first movie page');
+      done();
+    });
+    req.pipe(stream);
+  }
+
+
+
+

request pipe

+
+
should act as a writable stream
+
done => {
+    const req = request.post(base);
+    const stream = fs.createReadStream('test/node/fixtures/user.json');
+    req.type('json');
+    req.on('response', res => {
+      res.body.should.eql({ name: 'tobi' });
+      done();
+    });
+    stream.pipe(req);
+  }
+
end() stops piping
+
done => {
+    const stream = fs.createWriteStream(destPath);
+    request.get(base).end((err, res) => {
+      try {
+        res.pipe(stream);
+        return done(new Error('Did not prevent nonsense pipe'));
+      } catch (err2) {
+        /* expected error */
+      }
+      done();
+    });
+  }
+
should act as a readable stream
+
done => {
+    const stream = fs.createWriteStream(destPath);
+    let responseCalled = false;
+    const req = request.get(base);
+    req.type('json');
+    req.on('response', res => {
+      res.status.should.eql(200);
+      responseCalled = true;
+    });
+    stream.on('finish', () => {
+      JSON.parse(fs.readFileSync(destPath, 'utf8')).should.eql({
+        name: 'tobi'
+      });
+      responseCalled.should.be.true();
+      done();
+    });
+    req.pipe(stream);
+  }
+
+
+
+

req.query(String)

+
+
should support passing in a string
+
done => {
+    request
+      .del(base)
+      .query('name=t%F6bi')
+      .end((err, res) => {
+        res.body.should.eql({ name: 't%F6bi' });
+        done();
+      });
+  }
+
should work with url query-string and string for query
+
done => {
+    request
+      .del(`${base}/?name=tobi`)
+      .query('age=2%20')
+      .end((err, res) => {
+        res.body.should.eql({ name: 'tobi', age: '2 ' });
+        done();
+      });
+  }
+
should support compound elements in a string
+
done => {
+    request
+      .del(base)
+      .query('name=t%F6bi&age=2')
+      .end((err, res) => {
+        res.body.should.eql({ name: 't%F6bi', age: '2' });
+        done();
+      });
+  }
+
should work when called multiple times with a string
+
done => {
+    request
+      .del(base)
+      .query('name=t%F6bi')
+      .query('age=2%F6')
+      .end((err, res) => {
+        res.body.should.eql({ name: 't%F6bi', age: '2%F6' });
+        done();
+      });
+  }
+
should work with normal `query` object and query string
+
done => {
+    request
+      .del(base)
+      .query('name=t%F6bi')
+      .query({ age: '2' })
+      .end((err, res) => {
+        res.body.should.eql({ name: 't%F6bi', age: '2' });
+        done();
+      });
+  }
+
should not encode raw backticks, but leave encoded ones as is
+
return Promise.all([
+  request
+    .get(`${base}/raw-query`)
+    .query('name=`t%60bi`&age`=2')
+    .then(res => {
+      res.text.should.eql('name=`t%60bi`&age`=2');
+    }),
+  request.get(base + '/raw-query?`age%60`=2%60`').then(res => {
+    res.text.should.eql('`age%60`=2%60`');
+  }),
+  request
+    .get(`${base}/raw-query`)
+    .query('name=`t%60bi`')
+    .query('age`=2')
+    .then(res => {
+      res.text.should.eql('name=`t%60bi`&age`=2');
+    })
+]);
+
+
+
+

req.query(Object)

+
+
should construct the query-string
+
done => {
+    request
+      .del(base)
+      .query({ name: 'tobi' })
+      .query({ order: 'asc' })
+      .query({ limit: ['1', '2'] })
+      .end((err, res) => {
+        res.body.should.eql({ name: 'tobi', order: 'asc', limit: ['1', '2'] });
+        done();
+      });
+  }
+
should encode raw backticks
+
done => {
+    request
+      .get(`${base}/raw-query`)
+      .query({ name: '`tobi`' })
+      .query({ 'orde%60r': null })
+      .query({ '`limit`': ['%602`'] })
+      .end((err, res) => {
+        res.text.should.eql('name=%60tobi%60&orde%2560r&%60limit%60=%25602%60');
+        done();
+      });
+  }
+
should not error on dates
+
done => {
+    const date = new Date(0);
+    request
+      .del(base)
+      .query({ at: date })
+      .end((err, res) => {
+        assert.equal(date.toISOString(), res.body.at);
+        done();
+      });
+  }
+
should work after setting header fields
+
done => {
+    request
+      .del(base)
+      .set('Foo', 'bar')
+      .set('Bar', 'baz')
+      .query({ name: 'tobi' })
+      .query({ order: 'asc' })
+      .query({ limit: ['1', '2'] })
+      .end((err, res) => {
+        res.body.should.eql({ name: 'tobi', order: 'asc', limit: ['1', '2'] });
+        done();
+      });
+  }
+
should append to the original query-string
+
done => {
+    request
+      .del(`${base}/?name=tobi`)
+      .query({ order: 'asc' })
+      .end((err, res) => {
+        res.body.should.eql({ name: 'tobi', order: 'asc' });
+        done();
+      });
+  }
+
should retain the original query-string
+
done => {
+    request.del(`${base}/?name=tobi`).end((err, res) => {
+      res.body.should.eql({ name: 'tobi' });
+      done();
+    });
+  }
+
should keep only keys with null querystring values
+
done => {
+    request
+      .del(`${base}/url`)
+      .query({ nil: null })
+      .end((err, res) => {
+        res.text.should.equal('/url?nil');
+        done();
+      });
+  }
+
query-string should be sent on pipe
+
done => {
+    const req = request.put(`${base}/?name=tobi`);
+    const stream = fs.createReadStream('test/node/fixtures/user.json');
+    req.on('response', res => {
+      res.body.should.eql({ name: 'tobi' });
+      done();
+    });
+    stream.pipe(req);
+  }
+
+
+
+

request.get

+
+
+

on 301 redirect

+
+
should follow Location with a GET request
+
done => {
+      const req = request.get(`${base}/test-301`).redirects(1);
+      req.end((err, res) => {
+        req.req._headers.host.should.eql(`localhost:${server2.address().port}`);
+        res.status.should.eql(200);
+        res.text.should.eql('GET');
+        done();
+      });
+    }
+
+
+
+

on 302 redirect

+
+
should follow Location with a GET request
+
done => {
+      const req = request.get(`${base}/test-302`).redirects(1);
+      req.end((err, res) => {
+        req.req._headers.host.should.eql(`localhost:${server2.address().port}`);
+        res.status.should.eql(200);
+        res.text.should.eql('GET');
+        done();
+      });
+    }
+
+
+
+

on 303 redirect

+
+
should follow Location with a GET request
+
done => {
+      const req = request.get(`${base}/test-303`).redirects(1);
+      req.end((err, res) => {
+        req.req._headers.host.should.eql(`localhost:${server2.address().port}`);
+        res.status.should.eql(200);
+        res.text.should.eql('GET');
+        done();
+      });
+    }
+
+
+
+

on 307 redirect

+
+
should follow Location with a GET request
+
done => {
+      const req = request.get(`${base}/test-307`).redirects(1);
+      req.end((err, res) => {
+        req.req._headers.host.should.eql(`localhost:${server2.address().port}`);
+        res.status.should.eql(200);
+        res.text.should.eql('GET');
+        done();
+      });
+    }
+
+
+
+

on 308 redirect

+
+
should follow Location with a GET request
+
done => {
+      const req = request.get(`${base}/test-308`).redirects(1);
+      req.end((err, res) => {
+        req.req._headers.host.should.eql(`localhost:${server2.address().port}`);
+        res.status.should.eql(200);
+        res.text.should.eql('GET');
+        done();
+      });
+    }
+
+
+
+
+
+

request.post

+
+
+

on 301 redirect

+
+
should follow Location with a GET request
+
done => {
+      const req = request.post(`${base}/test-301`).redirects(1);
+      req.end((err, res) => {
+        req.req._headers.host.should.eql(`localhost:${server2.address().port}`);
+        res.status.should.eql(200);
+        res.text.should.eql('GET');
+        done();
+      });
+    }
+
+
+
+

on 302 redirect

+
+
should follow Location with a GET request
+
done => {
+      const req = request.post(`${base}/test-302`).redirects(1);
+      req.end((err, res) => {
+        req.req._headers.host.should.eql(`localhost:${server2.address().port}`);
+        res.status.should.eql(200);
+        res.text.should.eql('GET');
+        done();
+      });
+    }
+
+
+
+

on 303 redirect

+
+
should follow Location with a GET request
+
done => {
+      const req = request.post(`${base}/test-303`).redirects(1);
+      req.end((err, res) => {
+        req.req._headers.host.should.eql(`localhost:${server2.address().port}`);
+        res.status.should.eql(200);
+        res.text.should.eql('GET');
+        done();
+      });
+    }
+
+
+
+

on 307 redirect

+
+
should follow Location with a POST request
+
done => {
+      const req = request.post(`${base}/test-307`).redirects(1);
+      req.end((err, res) => {
+        req.req._headers.host.should.eql(`localhost:${server2.address().port}`);
+        res.status.should.eql(200);
+        res.text.should.eql('POST');
+        done();
+      });
+    }
+
+
+
+

on 308 redirect

+
+
should follow Location with a POST request
+
done => {
+      const req = request.post(`${base}/test-308`).redirects(1);
+      req.end((err, res) => {
+        req.req._headers.host.should.eql(`localhost:${server2.address().port}`);
+        res.status.should.eql(200);
+        res.text.should.eql('POST');
+        done();
+      });
+    }
+
+
+
+
+
+

request

+
+
+

on redirect

+
+
should merge cookies if agent is used
+
done => {
+      request
+        .agent()
+        .get(`${base}/cookie-redirect`)
+        .set('Cookie', 'orig=1; replaced=not')
+        .end((err, res) => {
+          try {
+            assert.ifError(err);
+            assert(/orig=1/.test(res.text), 'orig=1/.test');
+            assert(/replaced=yes/.test(res.text), 'replaced=yes/.test');
+            assert(/from-redir=1/.test(res.text), 'from-redir=1');
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
should not merge cookies if agent is not used
+
done => {
+      request
+        .get(`${base}/cookie-redirect`)
+        .set('Cookie', 'orig=1; replaced=not')
+        .end((err, res) => {
+          try {
+            assert.ifError(err);
+            assert(/orig=1/.test(res.text), '/orig=1');
+            assert(/replaced=not/.test(res.text), '/replaced=not');
+            assert(!/replaced=yes/.test(res.text), '!/replaced=yes');
+            assert(!/from-redir/.test(res.text), '!/from-redir');
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
should have previously set cookie for subsquent requests when agent is used
+
done => {
+      const agent = request.agent();
+      agent.get(`${base}/set-cookie`).end(err => {
+        assert.ifError(err);
+        agent
+          .get(`${base}/show-cookies`)
+          .set({ Cookie: 'orig=1' })
+          .end((err, res) => {
+            try {
+              assert.ifError(err);
+              assert(/orig=1/.test(res.text), 'orig=1/.test');
+              assert(/persist=123/.test(res.text), 'persist=123');
+              done();
+            } catch (err2) {
+              done(err2);
+            }
+          });
+      });
+    }
+
should follow Location
+
done => {
+      const redirects = [];
+      request
+        .get(base)
+        .on('redirect', res => {
+          redirects.push(res.headers.location);
+        })
+        .end((err, res) => {
+          try {
+            const arr = ['/movies', '/movies/all', '/movies/all/0'];
+            redirects.should.eql(arr);
+            res.text.should.equal('first movie page');
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
should follow Location with IP override
+
const redirects = [];
+const url = URL.parse(base);
+return request
+  .get(`http://redir.example.com:${url.port || '80'}${url.pathname}`)
+  .connect({
+    '*': url.hostname
+  })
+  .on('redirect', res => {
+    redirects.push(res.headers.location);
+  })
+  .then(res => {
+    const arr = ['/movies', '/movies/all', '/movies/all/0'];
+    redirects.should.eql(arr);
+    res.text.should.equal('first movie page');
+  });
+
should not follow on HEAD by default
+
const redirects = [];
+return request
+  .head(base)
+  .ok(() => true)
+  .on('redirect', res => {
+    redirects.push(res.headers.location);
+  })
+  .then(res => {
+    redirects.should.eql([]);
+    res.status.should.equal(302);
+  });
+
should follow on HEAD when redirects are set
+
done => {
+      const redirects = [];
+      request
+        .head(base)
+        .redirects(10)
+        .on('redirect', res => {
+          redirects.push(res.headers.location);
+        })
+        .end((err, res) => {
+          try {
+            const arr = [];
+            arr.push('/movies');
+            arr.push('/movies/all');
+            arr.push('/movies/all/0');
+            redirects.should.eql(arr);
+            assert(!res.text);
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
should remove Content-* fields
+
done => {
+      request
+        .post(`${base}/header`)
+        .type('txt')
+        .set('X-Foo', 'bar')
+        .set('X-Bar', 'baz')
+        .send('hey')
+        .end((err, res) => {
+          try {
+            assert(res.body);
+            res.body.should.have.property('x-foo', 'bar');
+            res.body.should.have.property('x-bar', 'baz');
+            res.body.should.not.have.property('content-type');
+            res.body.should.not.have.property('content-length');
+            res.body.should.not.have.property('transfer-encoding');
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
should retain cookies
+
done => {
+      request
+        .get(`${base}/header`)
+        .set('Cookie', 'foo=bar;')
+        .end((err, res) => {
+          try {
+            assert(res.body);
+            res.body.should.have.property('cookie', 'foo=bar;');
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
should not resend query parameters
+
done => {
+      const redirects = [];
+      const query = [];
+      request
+        .get(`${base}/?foo=bar`)
+        .on('redirect', res => {
+          query.push(res.headers.query);
+          redirects.push(res.headers.location);
+        })
+        .end((err, res) => {
+          try {
+            const arr = [];
+            arr.push('/movies');
+            arr.push('/movies/all');
+            arr.push('/movies/all/0');
+            redirects.should.eql(arr);
+            res.text.should.equal('first movie page');
+            query.should.eql(['{"foo":"bar"}', '{}', '{}']);
+            res.headers.query.should.eql('{}');
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
should handle no location header
+
done => {
+      request.get(`${base}/bad-redirect`).end((err, res) => {
+        try {
+          err.message.should.equal('No location header for redirect');
+          done();
+        } catch (err2) {
+          done(err2);
+        }
+      });
+    }
+
+

when relative

+
+
should redirect to a sibling path
+
done => {
+        const redirects = [];
+        request
+          .get(`${base}/relative`)
+          .on('redirect', res => {
+            redirects.push(res.headers.location);
+          })
+          .end((err, res) => {
+            try {
+              redirects.should.eql(['tobi']);
+              res.text.should.equal('tobi');
+              done();
+            } catch (err2) {
+              done(err2);
+            }
+          });
+      }
+
should redirect to a parent path
+
done => {
+        const redirects = [];
+        request
+          .get(`${base}/relative/sub`)
+          .on('redirect', res => {
+            redirects.push(res.headers.location);
+          })
+          .end((err, res) => {
+            try {
+              redirects.should.eql(['../tobi']);
+              res.text.should.equal('tobi');
+              done();
+            } catch (err2) {
+              done(err2);
+            }
+          });
+      }
+
+
+
+
+
+

req.redirects(n)

+
+
should alter the default number of redirects to follow
+
done => {
+      const redirects = [];
+      request
+        .get(base)
+        .redirects(2)
+        .on('redirect', res => {
+          redirects.push(res.headers.location);
+        })
+        .end((err, res) => {
+          try {
+            const arr = [];
+            assert(res.redirect, 'res.redirect');
+            arr.push('/movies');
+            arr.push('/movies/all');
+            redirects.should.eql(arr);
+            res.text.should.match(/Moved Temporarily|Found/);
+            done();
+          } catch (err2) {
+            done(err2);
+          }
+        });
+    }
+
+
+
+

on POST

+
+
should redirect as GET
+
const redirects = [];
+return request
+  .post(`${base}/movie`)
+  .send({ name: 'Tobi' })
+  .redirects(2)
+  .on('redirect', res => {
+    redirects.push(res.headers.location);
+  })
+  .then(res => {
+    redirects.should.eql(['/movies/all/0']);
+    res.text.should.equal('first movie page');
+  });
+
using multipart/form-data should redirect as GET
+
const redirects = [];
+request
+  .post(`${base}/movie`)
+  .type('form')
+  .field('name', 'Tobi')
+  .redirects(2)
+  .on('redirect', res => {
+    redirects.push(res.headers.location);
+  })
+  .then(res => {
+    redirects.should.eql(['/movies/all/0']);
+    res.text.should.equal('first movie page');
+  });
+
+
+
+
+
+

response

+
+
should act as a readable stream
+
done => {
+    const req = request.get(base).buffer(false);
+    req.end((err, res) => {
+      if (err) return done(err);
+      let trackEndEvent = 0;
+      let trackCloseEvent = 0;
+      res.on('end', () => {
+        trackEndEvent++;
+        trackEndEvent.should.equal(1);
+        if (!process.env.HTTP2_TEST) {
+          trackCloseEvent.should.equal(0); // close should not have been called
+        }
+        done();
+      });
+      res.on('close', () => {
+        trackCloseEvent++;
+      });
+      (() => {
+        res.pause();
+      }).should.not.throw();
+      (() => {
+        res.resume();
+      }).should.not.throw();
+      (() => {
+        res.destroy();
+      }).should.not.throw();
+    });
+  }
+
+
+
+

req.serialize(fn)

+
+
should take precedence over default parsers
+
done => {
+    request
+      .post(`${base}/echo`)
+      .send({ foo: 123 })
+      .serialize(data => '{"bar":456}')
+      .end((err, res) => {
+        assert.ifError(err);
+        assert.equal('{"bar":456}', res.text);
+        assert.equal(456, res.body.bar);
+        done();
+      });
+  }
+
+
+
+

request.get().set()

+
+
should set host header after get()
+
done => {
+    app.get('/', (req, res) => {
+      assert.equal(req.hostname, 'example.com');
+      res.end();
+    });
+    server = http.createServer(app);
+    server.listen(0, function listening() {
+      request
+        .get(`http://localhost:${server.address().port}`)
+        .set('host', 'example.com')
+        .then(() => {
+          return request
+            .get(`http://example.com:${server.address().port}`)
+            .connect({
+              'example.com': 'localhost',
+              '*': 'fail'
+            });
+        })
+        .then(() => done(), done);
+    });
+  }
+
+
+
+

res.toError()

+
+
should return an Error
+
done => {
+    request.get(base).end((err, res) => {
+      var err = res.toError();
+      assert.equal(err.status, 400);
+      assert.equal(err.method, 'GET');
+      assert.equal(err.path, '/');
+      assert.equal(err.message, 'cannot GET / (400)');
+      assert.equal(err.text, 'invalid json');
+      done();
+    });
+  }
+
+
+
+

[unix-sockets] http

+
+
+

request

+
+
path: / (root)
+
done => {
+      request.get(`${base}/`).end((err, res) => {
+        assert(res.ok);
+        assert.strictEqual('root ok!', res.text);
+        done();
+      });
+    }
+
path: /request/path
+
done => {
+      request.get(`${base}/request/path`).end((err, res) => {
+        assert(res.ok);
+        assert.strictEqual('request path ok!', res.text);
+        done();
+      });
+    }
+
+
+
+
+
+

[unix-sockets] https

+
+
+

request

+
+
path: / (root)
+
done => {
+      request
+        .get(`${base}/`)
+        .ca(cacert)
+        .end((err, res) => {
+          assert.ifError(err);
+          assert(res.ok);
+          assert.strictEqual('root ok!', res.text);
+          done();
+        });
+    }
+
path: /request/path
+
done => {
+      request
+        .get(`${base}/request/path`)
+        .ca(cacert)
+        .end((err, res) => {
+          assert.ifError(err);
+          assert(res.ok);
+          assert.strictEqual('request path ok!', res.text);
+          done();
+        });
+    }
+
+
+
+
+
+

req.get()

+
+
should set a default user-agent
+
request.get(`${base}/ua`).then(res => {
+      assert(res.headers);
+      assert(res.headers['user-agent']);
+      assert(
+        /^node-superagent\/\d+\.\d+\.\d+(?:-[a-z]+\.\d+|$)/.test(
+          res.headers['user-agent']
+        )
+      );
+    })
+
should be able to override user-agent
+
request
+      .get(`${base}/ua`)
+      .set('User-Agent', 'foo/bar')
+      .then(res => {
+        assert(res.headers);
+        assert.equal(res.headers['user-agent'], 'foo/bar');
+      })
+
should be able to wipe user-agent
+
request
+      .get(`${base}/ua`)
+      .unset('User-Agent')
+      .then(res => {
+        assert(res.headers);
+        assert.equal(res.headers['user-agent'], void 0);
+      })
+
+
+
+

utils.type(str)

+
+
should return the mime type
+
utils
+  .type('application/json; charset=utf-8')
+  .should.equal('application/json');
+utils.type('application/json').should.equal('application/json');
+
+
+
+

utils.params(str)

+
+
should return the field parameters
+
const obj = utils.params('application/json; charset=utf-8; foo  = bar');
+obj.charset.should.equal('utf-8');
+obj.foo.should.equal('bar');
+utils.params('application/json').should.eql({});
+
+
+
+

utils.parseLinks(str)

+
+
should parse links
+
const str =
+  '<https://api.github.com/repos/visionmedia/mocha/issues?page=2>; rel="next", <https://api.github.com/repos/visionmedia/mocha/issues?page=5>; rel="last"';
+const ret = utils.parseLinks(str);
+ret.next.should.equal(
+  'https://api.github.com/repos/visionmedia/mocha/issues?page=2'
+);
+ret.last.should.equal(
+  'https://api.github.com/repos/visionmedia/mocha/issues?page=5'
+);
+
+
+
+ Fork me on GitHub + + + + + + diff --git a/node_modules/superagent/index.html b/node_modules/superagent/index.html new file mode 100644 index 000000000..5765cee66 --- /dev/null +++ b/node_modules/superagent/index.html @@ -0,0 +1,47 @@ + + + + + SuperAgent — elegant API for AJAX in Node and browsers + + + + + +
+
+ Fork me on GitHub + + + + + + diff --git a/node_modules/superagent/lib/agent-base.js b/node_modules/superagent/lib/agent-base.js new file mode 100644 index 000000000..a6d400719 --- /dev/null +++ b/node_modules/superagent/lib/agent-base.js @@ -0,0 +1,42 @@ +"use strict"; + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + +function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } + +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + +function Agent() { + this._defaults = []; +} + +['use', 'on', 'once', 'set', 'query', 'type', 'accept', 'auth', 'withCredentials', 'sortQuery', 'retry', 'ok', 'redirects', 'timeout', 'buffer', 'serialize', 'parse', 'ca', 'key', 'pfx', 'cert', 'disableTLSCerts'].forEach(function (fn) { + // Default setting for all requests from this agent + Agent.prototype[fn] = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + this._defaults.push({ + fn: fn, + args: args + }); + + return this; + }; +}); + +Agent.prototype._setDefaults = function (req) { + this._defaults.forEach(function (def) { + req[def.fn].apply(req, _toConsumableArray(def.args)); + }); +}; + +module.exports = Agent; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uL3NyYy9hZ2VudC1iYXNlLmpzIl0sIm5hbWVzIjpbIkFnZW50IiwiX2RlZmF1bHRzIiwiZm9yRWFjaCIsImZuIiwicHJvdG90eXBlIiwiYXJncyIsInB1c2giLCJfc2V0RGVmYXVsdHMiLCJyZXEiLCJkZWYiLCJtb2R1bGUiLCJleHBvcnRzIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7OztBQUFBLFNBQVNBLEtBQVQsR0FBaUI7QUFDZixPQUFLQyxTQUFMLEdBQWlCLEVBQWpCO0FBQ0Q7O0FBRUQsQ0FDRSxLQURGLEVBRUUsSUFGRixFQUdFLE1BSEYsRUFJRSxLQUpGLEVBS0UsT0FMRixFQU1FLE1BTkYsRUFPRSxRQVBGLEVBUUUsTUFSRixFQVNFLGlCQVRGLEVBVUUsV0FWRixFQVdFLE9BWEYsRUFZRSxJQVpGLEVBYUUsV0FiRixFQWNFLFNBZEYsRUFlRSxRQWZGLEVBZ0JFLFdBaEJGLEVBaUJFLE9BakJGLEVBa0JFLElBbEJGLEVBbUJFLEtBbkJGLEVBb0JFLEtBcEJGLEVBcUJFLE1BckJGLEVBc0JFLGlCQXRCRixFQXVCRUMsT0F2QkYsQ0F1QlUsVUFBQUMsRUFBRSxFQUFJO0FBQ2Q7QUFDQUgsRUFBQUEsS0FBSyxDQUFDSSxTQUFOLENBQWdCRCxFQUFoQixJQUFzQixZQUFrQjtBQUFBLHNDQUFORSxJQUFNO0FBQU5BLE1BQUFBLElBQU07QUFBQTs7QUFDdEMsU0FBS0osU0FBTCxDQUFlSyxJQUFmLENBQW9CO0FBQUVILE1BQUFBLEVBQUUsRUFBRkEsRUFBRjtBQUFNRSxNQUFBQSxJQUFJLEVBQUpBO0FBQU4sS0FBcEI7O0FBQ0EsV0FBTyxJQUFQO0FBQ0QsR0FIRDtBQUlELENBN0JEOztBQStCQUwsS0FBSyxDQUFDSSxTQUFOLENBQWdCRyxZQUFoQixHQUErQixVQUFTQyxHQUFULEVBQWM7QUFDM0MsT0FBS1AsU0FBTCxDQUFlQyxPQUFmLENBQXVCLFVBQUFPLEdBQUcsRUFBSTtBQUM1QkQsSUFBQUEsR0FBRyxDQUFDQyxHQUFHLENBQUNOLEVBQUwsQ0FBSCxPQUFBSyxHQUFHLHFCQUFZQyxHQUFHLENBQUNKLElBQWhCLEVBQUg7QUFDRCxHQUZEO0FBR0QsQ0FKRDs7QUFNQUssTUFBTSxDQUFDQyxPQUFQLEdBQWlCWCxLQUFqQiIsInNvdXJjZXNDb250ZW50IjpbImZ1bmN0aW9uIEFnZW50KCkge1xuICB0aGlzLl9kZWZhdWx0cyA9IFtdO1xufVxuXG5bXG4gICd1c2UnLFxuICAnb24nLFxuICAnb25jZScsXG4gICdzZXQnLFxuICAncXVlcnknLFxuICAndHlwZScsXG4gICdhY2NlcHQnLFxuICAnYXV0aCcsXG4gICd3aXRoQ3JlZGVudGlhbHMnLFxuICAnc29ydFF1ZXJ5JyxcbiAgJ3JldHJ5JyxcbiAgJ29rJyxcbiAgJ3JlZGlyZWN0cycsXG4gICd0aW1lb3V0JyxcbiAgJ2J1ZmZlcicsXG4gICdzZXJpYWxpemUnLFxuICAncGFyc2UnLFxuICAnY2EnLFxuICAna2V5JyxcbiAgJ3BmeCcsXG4gICdjZXJ0JyxcbiAgJ2Rpc2FibGVUTFNDZXJ0cydcbl0uZm9yRWFjaChmbiA9PiB7XG4gIC8vIERlZmF1bHQgc2V0dGluZyBmb3IgYWxsIHJlcXVlc3RzIGZyb20gdGhpcyBhZ2VudFxuICBBZ2VudC5wcm90b3R5cGVbZm5dID0gZnVuY3Rpb24oLi4uYXJncykge1xuICAgIHRoaXMuX2RlZmF1bHRzLnB1c2goeyBmbiwgYXJncyB9KTtcbiAgICByZXR1cm4gdGhpcztcbiAgfTtcbn0pO1xuXG5BZ2VudC5wcm90b3R5cGUuX3NldERlZmF1bHRzID0gZnVuY3Rpb24ocmVxKSB7XG4gIHRoaXMuX2RlZmF1bHRzLmZvckVhY2goZGVmID0+IHtcbiAgICByZXFbZGVmLmZuXSguLi5kZWYuYXJncyk7XG4gIH0pO1xufTtcblxubW9kdWxlLmV4cG9ydHMgPSBBZ2VudDtcbiJdfQ== \ No newline at end of file diff --git a/node_modules/superagent/lib/client.js b/node_modules/superagent/lib/client.js new file mode 100644 index 000000000..385e4449b --- /dev/null +++ b/node_modules/superagent/lib/client.js @@ -0,0 +1,1020 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Root reference for iframes. + */ +var root; + +if (typeof window !== 'undefined') { + // Browser window + root = window; +} else if (typeof self === 'undefined') { + // Other environments + console.warn('Using browser-only version of superagent in non-browser environment'); + root = void 0; +} else { + // Web Worker + root = self; +} + +var Emitter = require('component-emitter'); + +var safeStringify = require('fast-safe-stringify'); + +var RequestBase = require('./request-base'); + +var isObject = require('./is-object'); + +var ResponseBase = require('./response-base'); + +var Agent = require('./agent-base'); +/** + * Noop. + */ + + +function noop() {} +/** + * Expose `request`. + */ + + +module.exports = function (method, url) { + // callback + if (typeof url === 'function') { + return new exports.Request('GET', method).end(url); + } // url first + + + if (arguments.length === 1) { + return new exports.Request('GET', method); + } + + return new exports.Request(method, url); +}; + +exports = module.exports; +var request = exports; +exports.Request = Request; +/** + * Determine XHR. + */ + +request.getXHR = function () { + if (root.XMLHttpRequest && (!root.location || root.location.protocol !== 'file:' || !root.ActiveXObject)) { + return new XMLHttpRequest(); + } + + try { + return new ActiveXObject('Microsoft.XMLHTTP'); + } catch (_unused) {} + + try { + return new ActiveXObject('Msxml2.XMLHTTP.6.0'); + } catch (_unused2) {} + + try { + return new ActiveXObject('Msxml2.XMLHTTP.3.0'); + } catch (_unused3) {} + + try { + return new ActiveXObject('Msxml2.XMLHTTP'); + } catch (_unused4) {} + + throw new Error('Browser-only version of superagent could not find XHR'); +}; +/** + * Removes leading and trailing whitespace, added to support IE. + * + * @param {String} s + * @return {String} + * @api private + */ + + +var trim = ''.trim ? function (s) { + return s.trim(); +} : function (s) { + return s.replace(/(^\s*|\s*$)/g, ''); +}; +/** + * Serialize the given `obj`. + * + * @param {Object} obj + * @return {String} + * @api private + */ + +function serialize(obj) { + if (!isObject(obj)) return obj; + var pairs = []; + + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) pushEncodedKeyValuePair(pairs, key, obj[key]); + } + + return pairs.join('&'); +} +/** + * Helps 'serialize' with serializing arrays. + * Mutates the pairs array. + * + * @param {Array} pairs + * @param {String} key + * @param {Mixed} val + */ + + +function pushEncodedKeyValuePair(pairs, key, val) { + if (val === undefined) return; + + if (val === null) { + pairs.push(encodeURI(key)); + return; + } + + if (Array.isArray(val)) { + val.forEach(function (v) { + pushEncodedKeyValuePair(pairs, key, v); + }); + } else if (isObject(val)) { + for (var subkey in val) { + if (Object.prototype.hasOwnProperty.call(val, subkey)) pushEncodedKeyValuePair(pairs, "".concat(key, "[").concat(subkey, "]"), val[subkey]); + } + } else { + pairs.push(encodeURI(key) + '=' + encodeURIComponent(val)); + } +} +/** + * Expose serialization method. + */ + + +request.serializeObject = serialize; +/** + * Parse the given x-www-form-urlencoded `str`. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function parseString(str) { + var obj = {}; + var pairs = str.split('&'); + var pair; + var pos; + + for (var i = 0, len = pairs.length; i < len; ++i) { + pair = pairs[i]; + pos = pair.indexOf('='); + + if (pos === -1) { + obj[decodeURIComponent(pair)] = ''; + } else { + obj[decodeURIComponent(pair.slice(0, pos))] = decodeURIComponent(pair.slice(pos + 1)); + } + } + + return obj; +} +/** + * Expose parser. + */ + + +request.parseString = parseString; +/** + * Default MIME type map. + * + * superagent.types.xml = 'application/xml'; + * + */ + +request.types = { + html: 'text/html', + json: 'application/json', + xml: 'text/xml', + urlencoded: 'application/x-www-form-urlencoded', + form: 'application/x-www-form-urlencoded', + 'form-data': 'application/x-www-form-urlencoded' +}; +/** + * Default serialization map. + * + * superagent.serialize['application/xml'] = function(obj){ + * return 'generated xml here'; + * }; + * + */ + +request.serialize = { + 'application/x-www-form-urlencoded': serialize, + 'application/json': safeStringify +}; +/** + * Default parsers. + * + * superagent.parse['application/xml'] = function(str){ + * return { object parsed from str }; + * }; + * + */ + +request.parse = { + 'application/x-www-form-urlencoded': parseString, + 'application/json': JSON.parse +}; +/** + * Parse the given header `str` into + * an object containing the mapped fields. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function parseHeader(str) { + var lines = str.split(/\r?\n/); + var fields = {}; + var index; + var line; + var field; + var val; + + for (var i = 0, len = lines.length; i < len; ++i) { + line = lines[i]; + index = line.indexOf(':'); + + if (index === -1) { + // could be empty line, just skip it + continue; + } + + field = line.slice(0, index).toLowerCase(); + val = trim(line.slice(index + 1)); + fields[field] = val; + } + + return fields; +} +/** + * Check if `mime` is json or has +json structured syntax suffix. + * + * @param {String} mime + * @return {Boolean} + * @api private + */ + + +function isJSON(mime) { + // should match /json or +json + // but not /json-seq + return /[/+]json($|[^-\w])/.test(mime); +} +/** + * Initialize a new `Response` with the given `xhr`. + * + * - set flags (.ok, .error, etc) + * - parse header + * + * Examples: + * + * Aliasing `superagent` as `request` is nice: + * + * request = superagent; + * + * We can use the promise-like API, or pass callbacks: + * + * request.get('/').end(function(res){}); + * request.get('/', function(res){}); + * + * Sending data can be chained: + * + * request + * .post('/user') + * .send({ name: 'tj' }) + * .end(function(res){}); + * + * Or passed to `.send()`: + * + * request + * .post('/user') + * .send({ name: 'tj' }, function(res){}); + * + * Or passed to `.post()`: + * + * request + * .post('/user', { name: 'tj' }) + * .end(function(res){}); + * + * Or further reduced to a single call for simple cases: + * + * request + * .post('/user', { name: 'tj' }, function(res){}); + * + * @param {XMLHTTPRequest} xhr + * @param {Object} options + * @api private + */ + + +function Response(req) { + this.req = req; + this.xhr = this.req.xhr; // responseText is accessible only if responseType is '' or 'text' and on older browsers + + this.text = this.req.method !== 'HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text') || typeof this.xhr.responseType === 'undefined' ? this.xhr.responseText : null; + this.statusText = this.req.xhr.statusText; + var status = this.xhr.status; // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + + if (status === 1223) { + status = 204; + } + + this._setStatusProperties(status); + + this.headers = parseHeader(this.xhr.getAllResponseHeaders()); + this.header = this.headers; // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but + // getResponseHeader still works. so we get content-type even if getting + // other headers fails. + + this.header['content-type'] = this.xhr.getResponseHeader('content-type'); + + this._setHeaderProperties(this.header); + + if (this.text === null && req._responseType) { + this.body = this.xhr.response; + } else { + this.body = this.req.method === 'HEAD' ? null : this._parseBody(this.text ? this.text : this.xhr.response); + } +} // eslint-disable-next-line new-cap + + +ResponseBase(Response.prototype); +/** + * Parse the given body `str`. + * + * Used for auto-parsing of bodies. Parsers + * are defined on the `superagent.parse` object. + * + * @param {String} str + * @return {Mixed} + * @api private + */ + +Response.prototype._parseBody = function (str) { + var parse = request.parse[this.type]; + + if (this.req._parser) { + return this.req._parser(this, str); + } + + if (!parse && isJSON(this.type)) { + parse = request.parse['application/json']; + } + + return parse && str && (str.length > 0 || str instanceof Object) ? parse(str) : null; +}; +/** + * Return an `Error` representative of this response. + * + * @return {Error} + * @api public + */ + + +Response.prototype.toError = function () { + var req = this.req; + var method = req.method; + var url = req.url; + var msg = "cannot ".concat(method, " ").concat(url, " (").concat(this.status, ")"); + var err = new Error(msg); + err.status = this.status; + err.method = method; + err.url = url; + return err; +}; +/** + * Expose `Response`. + */ + + +request.Response = Response; +/** + * Initialize a new `Request` with the given `method` and `url`. + * + * @param {String} method + * @param {String} url + * @api public + */ + +function Request(method, url) { + var self = this; + this._query = this._query || []; + this.method = method; + this.url = url; + this.header = {}; // preserves header name case + + this._header = {}; // coerces header names to lowercase + + this.on('end', function () { + var err = null; + var res = null; + + try { + res = new Response(self); + } catch (err_) { + err = new Error('Parser is unable to parse the response'); + err.parse = true; + err.original = err_; // issue #675: return the raw response if the response parsing fails + + if (self.xhr) { + // ie9 doesn't have 'response' property + err.rawResponse = typeof self.xhr.responseType === 'undefined' ? self.xhr.responseText : self.xhr.response; // issue #876: return the http status code if the response parsing fails + + err.status = self.xhr.status ? self.xhr.status : null; + err.statusCode = err.status; // backwards-compat only + } else { + err.rawResponse = null; + err.status = null; + } + + return self.callback(err); + } + + self.emit('response', res); + var new_err; + + try { + if (!self._isResponseOK(res)) { + new_err = new Error(res.statusText || res.text || 'Unsuccessful HTTP response'); + } + } catch (err_) { + new_err = err_; // ok() callback can throw + } // #1000 don't catch errors from the callback to avoid double calling it + + + if (new_err) { + new_err.original = err; + new_err.response = res; + new_err.status = res.status; + self.callback(new_err, res); + } else { + self.callback(null, res); + } + }); +} +/** + * Mixin `Emitter` and `RequestBase`. + */ +// eslint-disable-next-line new-cap + + +Emitter(Request.prototype); // eslint-disable-next-line new-cap + +RequestBase(Request.prototype); +/** + * Set Content-Type to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.xml = 'application/xml'; + * + * request.post('/') + * .type('xml') + * .send(xmlstring) + * .end(callback); + * + * request.post('/') + * .type('application/xml') + * .send(xmlstring) + * .end(callback); + * + * @param {String} type + * @return {Request} for chaining + * @api public + */ + +Request.prototype.type = function (type) { + this.set('Content-Type', request.types[type] || type); + return this; +}; +/** + * Set Accept to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.json = 'application/json'; + * + * request.get('/agent') + * .accept('json') + * .end(callback); + * + * request.get('/agent') + * .accept('application/json') + * .end(callback); + * + * @param {String} accept + * @return {Request} for chaining + * @api public + */ + + +Request.prototype.accept = function (type) { + this.set('Accept', request.types[type] || type); + return this; +}; +/** + * Set Authorization field value with `user` and `pass`. + * + * @param {String} user + * @param {String} [pass] optional in case of using 'bearer' as type + * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic') + * @return {Request} for chaining + * @api public + */ + + +Request.prototype.auth = function (user, pass, options) { + if (arguments.length === 1) pass = ''; + + if (_typeof(pass) === 'object' && pass !== null) { + // pass is optional and can be replaced with options + options = pass; + pass = ''; + } + + if (!options) { + options = { + type: typeof btoa === 'function' ? 'basic' : 'auto' + }; + } + + var encoder = function encoder(string) { + if (typeof btoa === 'function') { + return btoa(string); + } + + throw new Error('Cannot use basic auth, btoa is not a function'); + }; + + return this._auth(user, pass, options, encoder); +}; +/** + * Add query-string `val`. + * + * Examples: + * + * request.get('/shoes') + * .query('size=10') + * .query({ color: 'blue' }) + * + * @param {Object|String} val + * @return {Request} for chaining + * @api public + */ + + +Request.prototype.query = function (val) { + if (typeof val !== 'string') val = serialize(val); + if (val) this._query.push(val); + return this; +}; +/** + * Queue the given `file` as an attachment to the specified `field`, + * with optional `options` (or filename). + * + * ``` js + * request.post('/upload') + * .attach('content', new Blob(['hey!'], { type: "text/html"})) + * .end(callback); + * ``` + * + * @param {String} field + * @param {Blob|File} file + * @param {String|Object} options + * @return {Request} for chaining + * @api public + */ + + +Request.prototype.attach = function (field, file, options) { + if (file) { + if (this._data) { + throw new Error("superagent can't mix .send() and .attach()"); + } + + this._getFormData().append(field, file, options || file.name); + } + + return this; +}; + +Request.prototype._getFormData = function () { + if (!this._formData) { + this._formData = new root.FormData(); + } + + return this._formData; +}; +/** + * Invoke the callback with `err` and `res` + * and handle arity check. + * + * @param {Error} err + * @param {Response} res + * @api private + */ + + +Request.prototype.callback = function (err, res) { + if (this._shouldRetry(err, res)) { + return this._retry(); + } + + var fn = this._callback; + this.clearTimeout(); + + if (err) { + if (this._maxRetries) err.retries = this._retries - 1; + this.emit('error', err); + } + + fn(err, res); +}; +/** + * Invoke callback with x-domain error. + * + * @api private + */ + + +Request.prototype.crossDomainError = function () { + var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); + err.crossDomain = true; + err.status = this.status; + err.method = this.method; + err.url = this.url; + this.callback(err); +}; // This only warns, because the request is still likely to work + + +Request.prototype.agent = function () { + console.warn('This is not supported in browser version of superagent'); + return this; +}; + +Request.prototype.ca = Request.prototype.agent; +Request.prototype.buffer = Request.prototype.ca; // This throws, because it can't send/receive data as expected + +Request.prototype.write = function () { + throw new Error('Streaming is not supported in browser version of superagent'); +}; + +Request.prototype.pipe = Request.prototype.write; +/** + * Check if `obj` is a host object, + * we don't want to serialize these :) + * + * @param {Object} obj host object + * @return {Boolean} is a host object + * @api private + */ + +Request.prototype._isHost = function (obj) { + // Native objects stringify to [object File], [object Blob], [object FormData], etc. + return obj && _typeof(obj) === 'object' && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]'; +}; +/** + * Initiate request, invoking callback `fn(res)` + * with an instanceof `Response`. + * + * @param {Function} fn + * @return {Request} for chaining + * @api public + */ + + +Request.prototype.end = function (fn) { + if (this._endCalled) { + console.warn('Warning: .end() was called twice. This is not supported in superagent'); + } + + this._endCalled = true; // store callback + + this._callback = fn || noop; // querystring + + this._finalizeQueryString(); + + this._end(); +}; + +Request.prototype._setUploadTimeout = function () { + var self = this; // upload timeout it's wokrs only if deadline timeout is off + + if (this._uploadTimeout && !this._uploadTimeoutTimer) { + this._uploadTimeoutTimer = setTimeout(function () { + self._timeoutError('Upload timeout of ', self._uploadTimeout, 'ETIMEDOUT'); + }, this._uploadTimeout); + } +}; // eslint-disable-next-line complexity + + +Request.prototype._end = function () { + if (this._aborted) return this.callback(new Error('The request has been aborted even before .end() was called')); + var self = this; + this.xhr = request.getXHR(); + var xhr = this.xhr; + var data = this._formData || this._data; + + this._setTimeouts(); // state change + + + xhr.onreadystatechange = function () { + var readyState = xhr.readyState; + + if (readyState >= 2 && self._responseTimeoutTimer) { + clearTimeout(self._responseTimeoutTimer); + } + + if (readyState !== 4) { + return; + } // In IE9, reads to any property (e.g. status) off of an aborted XHR will + // result in the error "Could not complete the operation due to error c00c023f" + + + var status; + + try { + status = xhr.status; + } catch (_unused5) { + status = 0; + } + + if (!status) { + if (self.timedout || self._aborted) return; + return self.crossDomainError(); + } + + self.emit('end'); + }; // progress + + + var handleProgress = function handleProgress(direction, e) { + if (e.total > 0) { + e.percent = e.loaded / e.total * 100; + + if (e.percent === 100) { + clearTimeout(self._uploadTimeoutTimer); + } + } + + e.direction = direction; + self.emit('progress', e); + }; + + if (this.hasListeners('progress')) { + try { + xhr.addEventListener('progress', handleProgress.bind(null, 'download')); + + if (xhr.upload) { + xhr.upload.addEventListener('progress', handleProgress.bind(null, 'upload')); + } + } catch (_unused6) {// Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. + // Reported here: + // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context + } + } + + if (xhr.upload) { + this._setUploadTimeout(); + } // initiate request + + + try { + if (this.username && this.password) { + xhr.open(this.method, this.url, true, this.username, this.password); + } else { + xhr.open(this.method, this.url, true); + } + } catch (err) { + // see #1149 + return this.callback(err); + } // CORS + + + if (this._withCredentials) xhr.withCredentials = true; // body + + if (!this._formData && this.method !== 'GET' && this.method !== 'HEAD' && typeof data !== 'string' && !this._isHost(data)) { + // serialize stuff + var contentType = this._header['content-type']; + + var _serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : '']; + + if (!_serialize && isJSON(contentType)) { + _serialize = request.serialize['application/json']; + } + + if (_serialize) data = _serialize(data); + } // set header fields + + + for (var field in this.header) { + if (this.header[field] === null) continue; + if (Object.prototype.hasOwnProperty.call(this.header, field)) xhr.setRequestHeader(field, this.header[field]); + } + + if (this._responseType) { + xhr.responseType = this._responseType; + } // send stuff + + + this.emit('request', this); // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing) + // We need null here if data is undefined + + xhr.send(typeof data === 'undefined' ? null : data); +}; + +request.agent = function () { + return new Agent(); +}; + +['GET', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE'].forEach(function (method) { + Agent.prototype[method.toLowerCase()] = function (url, fn) { + var req = new request.Request(method, url); + + this._setDefaults(req); + + if (fn) { + req.end(fn); + } + + return req; + }; +}); +Agent.prototype.del = Agent.prototype.delete; +/** + * GET `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.get = function (url, data, fn) { + var req = request('GET', url); + + if (typeof data === 'function') { + fn = data; + data = null; + } + + if (data) req.query(data); + if (fn) req.end(fn); + return req; +}; +/** + * HEAD `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + + +request.head = function (url, data, fn) { + var req = request('HEAD', url); + + if (typeof data === 'function') { + fn = data; + data = null; + } + + if (data) req.query(data); + if (fn) req.end(fn); + return req; +}; +/** + * OPTIONS query to `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + + +request.options = function (url, data, fn) { + var req = request('OPTIONS', url); + + if (typeof data === 'function') { + fn = data; + data = null; + } + + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; +/** + * DELETE `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + + +function del(url, data, fn) { + var req = request('DELETE', url); + + if (typeof data === 'function') { + fn = data; + data = null; + } + + if (data) req.send(data); + if (fn) req.end(fn); + return req; +} + +request.del = del; +request.delete = del; +/** + * PATCH `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.patch = function (url, data, fn) { + var req = request('PATCH', url); + + if (typeof data === 'function') { + fn = data; + data = null; + } + + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; +/** + * POST `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + + +request.post = function (url, data, fn) { + var req = request('POST', url); + + if (typeof data === 'function') { + fn = data; + data = null; + } + + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; +/** + * PUT `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + + +request.put = function (url, data, fn) { + var req = request('PUT', url); + + if (typeof data === 'function') { + fn = data; + data = null; + } + + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uL3NyYy9jbGllbnQuanMiXSwibmFtZXMiOlsicm9vdCIsIndpbmRvdyIsInNlbGYiLCJjb25zb2xlIiwid2FybiIsIkVtaXR0ZXIiLCJyZXF1aXJlIiwic2FmZVN0cmluZ2lmeSIsIlJlcXVlc3RCYXNlIiwiaXNPYmplY3QiLCJSZXNwb25zZUJhc2UiLCJBZ2VudCIsIm5vb3AiLCJtb2R1bGUiLCJleHBvcnRzIiwibWV0aG9kIiwidXJsIiwiUmVxdWVzdCIsImVuZCIsImFyZ3VtZW50cyIsImxlbmd0aCIsInJlcXVlc3QiLCJnZXRYSFIiLCJYTUxIdHRwUmVxdWVzdCIsImxvY2F0aW9uIiwicHJvdG9jb2wiLCJBY3RpdmVYT2JqZWN0IiwiRXJyb3IiLCJ0cmltIiwicyIsInJlcGxhY2UiLCJzZXJpYWxpemUiLCJvYmoiLCJwYWlycyIsImtleSIsIk9iamVjdCIsInByb3RvdHlwZSIsImhhc093blByb3BlcnR5IiwiY2FsbCIsInB1c2hFbmNvZGVkS2V5VmFsdWVQYWlyIiwiam9pbiIsInZhbCIsInVuZGVmaW5lZCIsInB1c2giLCJlbmNvZGVVUkkiLCJBcnJheSIsImlzQXJyYXkiLCJmb3JFYWNoIiwidiIsInN1YmtleSIsImVuY29kZVVSSUNvbXBvbmVudCIsInNlcmlhbGl6ZU9iamVjdCIsInBhcnNlU3RyaW5nIiwic3RyIiwic3BsaXQiLCJwYWlyIiwicG9zIiwiaSIsImxlbiIsImluZGV4T2YiLCJkZWNvZGVVUklDb21wb25lbnQiLCJzbGljZSIsInR5cGVzIiwiaHRtbCIsImpzb24iLCJ4bWwiLCJ1cmxlbmNvZGVkIiwiZm9ybSIsInBhcnNlIiwiSlNPTiIsInBhcnNlSGVhZGVyIiwibGluZXMiLCJmaWVsZHMiLCJpbmRleCIsImxpbmUiLCJmaWVsZCIsInRvTG93ZXJDYXNlIiwiaXNKU09OIiwibWltZSIsInRlc3QiLCJSZXNwb25zZSIsInJlcSIsInhociIsInRleHQiLCJyZXNwb25zZVR5cGUiLCJyZXNwb25zZVRleHQiLCJzdGF0dXNUZXh0Iiwic3RhdHVzIiwiX3NldFN0YXR1c1Byb3BlcnRpZXMiLCJoZWFkZXJzIiwiZ2V0QWxsUmVzcG9uc2VIZWFkZXJzIiwiaGVhZGVyIiwiZ2V0UmVzcG9uc2VIZWFkZXIiLCJfc2V0SGVhZGVyUHJvcGVydGllcyIsIl9yZXNwb25zZVR5cGUiLCJib2R5IiwicmVzcG9uc2UiLCJfcGFyc2VCb2R5IiwidHlwZSIsIl9wYXJzZXIiLCJ0b0Vycm9yIiwibXNnIiwiZXJyIiwiX3F1ZXJ5IiwiX2hlYWRlciIsIm9uIiwicmVzIiwiZXJyXyIsIm9yaWdpbmFsIiwicmF3UmVzcG9uc2UiLCJzdGF0dXNDb2RlIiwiY2FsbGJhY2siLCJlbWl0IiwibmV3X2VyciIsIl9pc1Jlc3BvbnNlT0siLCJzZXQiLCJhY2NlcHQiLCJhdXRoIiwidXNlciIsInBhc3MiLCJvcHRpb25zIiwiYnRvYSIsImVuY29kZXIiLCJzdHJpbmciLCJfYXV0aCIsInF1ZXJ5IiwiYXR0YWNoIiwiZmlsZSIsIl9kYXRhIiwiX2dldEZvcm1EYXRhIiwiYXBwZW5kIiwibmFtZSIsIl9mb3JtRGF0YSIsIkZvcm1EYXRhIiwiX3Nob3VsZFJldHJ5IiwiX3JldHJ5IiwiZm4iLCJfY2FsbGJhY2siLCJjbGVhclRpbWVvdXQiLCJfbWF4UmV0cmllcyIsInJldHJpZXMiLCJfcmV0cmllcyIsImNyb3NzRG9tYWluRXJyb3IiLCJjcm9zc0RvbWFpbiIsImFnZW50IiwiY2EiLCJidWZmZXIiLCJ3cml0ZSIsInBpcGUiLCJfaXNIb3N0IiwidG9TdHJpbmciLCJfZW5kQ2FsbGVkIiwiX2ZpbmFsaXplUXVlcnlTdHJpbmciLCJfZW5kIiwiX3NldFVwbG9hZFRpbWVvdXQiLCJfdXBsb2FkVGltZW91dCIsIl91cGxvYWRUaW1lb3V0VGltZXIiLCJzZXRUaW1lb3V0IiwiX3RpbWVvdXRFcnJvciIsIl9hYm9ydGVkIiwiZGF0YSIsIl9zZXRUaW1lb3V0cyIsIm9ucmVhZHlzdGF0ZWNoYW5nZSIsInJlYWR5U3RhdGUiLCJfcmVzcG9uc2VUaW1lb3V0VGltZXIiLCJ0aW1lZG91dCIsImhhbmRsZVByb2dyZXNzIiwiZGlyZWN0aW9uIiwiZSIsInRvdGFsIiwicGVyY2VudCIsImxvYWRlZCIsImhhc0xpc3RlbmVycyIsImFkZEV2ZW50TGlzdGVuZXIiLCJiaW5kIiwidXBsb2FkIiwidXNlcm5hbWUiLCJwYXNzd29yZCIsIm9wZW4iLCJfd2l0aENyZWRlbnRpYWxzIiwid2l0aENyZWRlbnRpYWxzIiwiY29udGVudFR5cGUiLCJfc2VyaWFsaXplciIsInNldFJlcXVlc3RIZWFkZXIiLCJzZW5kIiwiX3NldERlZmF1bHRzIiwiZGVsIiwiZGVsZXRlIiwiZ2V0IiwiaGVhZCIsInBhdGNoIiwicG9zdCIsInB1dCJdLCJtYXBwaW5ncyI6Ijs7OztBQUFBOzs7QUFJQSxJQUFJQSxJQUFKOztBQUNBLElBQUksT0FBT0MsTUFBUCxLQUFrQixXQUF0QixFQUFtQztBQUNqQztBQUNBRCxFQUFBQSxJQUFJLEdBQUdDLE1BQVA7QUFDRCxDQUhELE1BR08sSUFBSSxPQUFPQyxJQUFQLEtBQWdCLFdBQXBCLEVBQWlDO0FBQ3RDO0FBQ0FDLEVBQUFBLE9BQU8sQ0FBQ0MsSUFBUixDQUNFLHFFQURGO0FBR0FKLEVBQUFBLElBQUksU0FBSjtBQUNELENBTk0sTUFNQTtBQUNMO0FBQ0FBLEVBQUFBLElBQUksR0FBR0UsSUFBUDtBQUNEOztBQUVELElBQU1HLE9BQU8sR0FBR0MsT0FBTyxDQUFDLG1CQUFELENBQXZCOztBQUNBLElBQU1DLGFBQWEsR0FBR0QsT0FBTyxDQUFDLHFCQUFELENBQTdCOztBQUNBLElBQU1FLFdBQVcsR0FBR0YsT0FBTyxDQUFDLGdCQUFELENBQTNCOztBQUNBLElBQU1HLFFBQVEsR0FBR0gsT0FBTyxDQUFDLGFBQUQsQ0FBeEI7O0FBQ0EsSUFBTUksWUFBWSxHQUFHSixPQUFPLENBQUMsaUJBQUQsQ0FBNUI7O0FBQ0EsSUFBTUssS0FBSyxHQUFHTCxPQUFPLENBQUMsY0FBRCxDQUFyQjtBQUVBOzs7OztBQUlBLFNBQVNNLElBQVQsR0FBZ0IsQ0FBRTtBQUVsQjs7Ozs7QUFJQUMsTUFBTSxDQUFDQyxPQUFQLEdBQWlCLFVBQVNDLE1BQVQsRUFBaUJDLEdBQWpCLEVBQXNCO0FBQ3JDO0FBQ0EsTUFBSSxPQUFPQSxHQUFQLEtBQWUsVUFBbkIsRUFBK0I7QUFDN0IsV0FBTyxJQUFJRixPQUFPLENBQUNHLE9BQVosQ0FBb0IsS0FBcEIsRUFBMkJGLE1BQTNCLEVBQW1DRyxHQUFuQyxDQUF1Q0YsR0FBdkMsQ0FBUDtBQUNELEdBSm9DLENBTXJDOzs7QUFDQSxNQUFJRyxTQUFTLENBQUNDLE1BQVYsS0FBcUIsQ0FBekIsRUFBNEI7QUFDMUIsV0FBTyxJQUFJTixPQUFPLENBQUNHLE9BQVosQ0FBb0IsS0FBcEIsRUFBMkJGLE1BQTNCLENBQVA7QUFDRDs7QUFFRCxTQUFPLElBQUlELE9BQU8sQ0FBQ0csT0FBWixDQUFvQkYsTUFBcEIsRUFBNEJDLEdBQTVCLENBQVA7QUFDRCxDQVpEOztBQWNBRixPQUFPLEdBQUdELE1BQU0sQ0FBQ0MsT0FBakI7QUFFQSxJQUFNTyxPQUFPLEdBQUdQLE9BQWhCO0FBRUFBLE9BQU8sQ0FBQ0csT0FBUixHQUFrQkEsT0FBbEI7QUFFQTs7OztBQUlBSSxPQUFPLENBQUNDLE1BQVIsR0FBaUIsWUFBTTtBQUNyQixNQUNFdEIsSUFBSSxDQUFDdUIsY0FBTCxLQUNDLENBQUN2QixJQUFJLENBQUN3QixRQUFOLElBQ0N4QixJQUFJLENBQUN3QixRQUFMLENBQWNDLFFBQWQsS0FBMkIsT0FENUIsSUFFQyxDQUFDekIsSUFBSSxDQUFDMEIsYUFIUixDQURGLEVBS0U7QUFDQSxXQUFPLElBQUlILGNBQUosRUFBUDtBQUNEOztBQUVELE1BQUk7QUFDRixXQUFPLElBQUlHLGFBQUosQ0FBa0IsbUJBQWxCLENBQVA7QUFDRCxHQUZELENBRUUsZ0JBQU0sQ0FBRTs7QUFFVixNQUFJO0FBQ0YsV0FBTyxJQUFJQSxhQUFKLENBQWtCLG9CQUFsQixDQUFQO0FBQ0QsR0FGRCxDQUVFLGlCQUFNLENBQUU7O0FBRVYsTUFBSTtBQUNGLFdBQU8sSUFBSUEsYUFBSixDQUFrQixvQkFBbEIsQ0FBUDtBQUNELEdBRkQsQ0FFRSxpQkFBTSxDQUFFOztBQUVWLE1BQUk7QUFDRixXQUFPLElBQUlBLGFBQUosQ0FBa0IsZ0JBQWxCLENBQVA7QUFDRCxHQUZELENBRUUsaUJBQU0sQ0FBRTs7QUFFVixRQUFNLElBQUlDLEtBQUosQ0FBVSx1REFBVixDQUFOO0FBQ0QsQ0EzQkQ7QUE2QkE7Ozs7Ozs7OztBQVFBLElBQU1DLElBQUksR0FBRyxHQUFHQSxJQUFILEdBQVUsVUFBQUMsQ0FBQztBQUFBLFNBQUlBLENBQUMsQ0FBQ0QsSUFBRixFQUFKO0FBQUEsQ0FBWCxHQUEwQixVQUFBQyxDQUFDO0FBQUEsU0FBSUEsQ0FBQyxDQUFDQyxPQUFGLENBQVUsY0FBVixFQUEwQixFQUExQixDQUFKO0FBQUEsQ0FBeEM7QUFFQTs7Ozs7Ozs7QUFRQSxTQUFTQyxTQUFULENBQW1CQyxHQUFuQixFQUF3QjtBQUN0QixNQUFJLENBQUN2QixRQUFRLENBQUN1QixHQUFELENBQWIsRUFBb0IsT0FBT0EsR0FBUDtBQUNwQixNQUFNQyxLQUFLLEdBQUcsRUFBZDs7QUFDQSxPQUFLLElBQU1DLEdBQVgsSUFBa0JGLEdBQWxCLEVBQXVCO0FBQ3JCLFFBQUlHLE1BQU0sQ0FBQ0MsU0FBUCxDQUFpQkMsY0FBakIsQ0FBZ0NDLElBQWhDLENBQXFDTixHQUFyQyxFQUEwQ0UsR0FBMUMsQ0FBSixFQUNFSyx1QkFBdUIsQ0FBQ04sS0FBRCxFQUFRQyxHQUFSLEVBQWFGLEdBQUcsQ0FBQ0UsR0FBRCxDQUFoQixDQUF2QjtBQUNIOztBQUVELFNBQU9ELEtBQUssQ0FBQ08sSUFBTixDQUFXLEdBQVgsQ0FBUDtBQUNEO0FBRUQ7Ozs7Ozs7Ozs7QUFTQSxTQUFTRCx1QkFBVCxDQUFpQ04sS0FBakMsRUFBd0NDLEdBQXhDLEVBQTZDTyxHQUE3QyxFQUFrRDtBQUNoRCxNQUFJQSxHQUFHLEtBQUtDLFNBQVosRUFBdUI7O0FBQ3ZCLE1BQUlELEdBQUcsS0FBSyxJQUFaLEVBQWtCO0FBQ2hCUixJQUFBQSxLQUFLLENBQUNVLElBQU4sQ0FBV0MsU0FBUyxDQUFDVixHQUFELENBQXBCO0FBQ0E7QUFDRDs7QUFFRCxNQUFJVyxLQUFLLENBQUNDLE9BQU4sQ0FBY0wsR0FBZCxDQUFKLEVBQXdCO0FBQ3RCQSxJQUFBQSxHQUFHLENBQUNNLE9BQUosQ0FBWSxVQUFBQyxDQUFDLEVBQUk7QUFDZlQsTUFBQUEsdUJBQXVCLENBQUNOLEtBQUQsRUFBUUMsR0FBUixFQUFhYyxDQUFiLENBQXZCO0FBQ0QsS0FGRDtBQUdELEdBSkQsTUFJTyxJQUFJdkMsUUFBUSxDQUFDZ0MsR0FBRCxDQUFaLEVBQW1CO0FBQ3hCLFNBQUssSUFBTVEsTUFBWCxJQUFxQlIsR0FBckIsRUFBMEI7QUFDeEIsVUFBSU4sTUFBTSxDQUFDQyxTQUFQLENBQWlCQyxjQUFqQixDQUFnQ0MsSUFBaEMsQ0FBcUNHLEdBQXJDLEVBQTBDUSxNQUExQyxDQUFKLEVBQ0VWLHVCQUF1QixDQUFDTixLQUFELFlBQVdDLEdBQVgsY0FBa0JlLE1BQWxCLFFBQTZCUixHQUFHLENBQUNRLE1BQUQsQ0FBaEMsQ0FBdkI7QUFDSDtBQUNGLEdBTE0sTUFLQTtBQUNMaEIsSUFBQUEsS0FBSyxDQUFDVSxJQUFOLENBQVdDLFNBQVMsQ0FBQ1YsR0FBRCxDQUFULEdBQWlCLEdBQWpCLEdBQXVCZ0Isa0JBQWtCLENBQUNULEdBQUQsQ0FBcEQ7QUFDRDtBQUNGO0FBRUQ7Ozs7O0FBSUFwQixPQUFPLENBQUM4QixlQUFSLEdBQTBCcEIsU0FBMUI7QUFFQTs7Ozs7Ozs7QUFRQSxTQUFTcUIsV0FBVCxDQUFxQkMsR0FBckIsRUFBMEI7QUFDeEIsTUFBTXJCLEdBQUcsR0FBRyxFQUFaO0FBQ0EsTUFBTUMsS0FBSyxHQUFHb0IsR0FBRyxDQUFDQyxLQUFKLENBQVUsR0FBVixDQUFkO0FBQ0EsTUFBSUMsSUFBSjtBQUNBLE1BQUlDLEdBQUo7O0FBRUEsT0FBSyxJQUFJQyxDQUFDLEdBQUcsQ0FBUixFQUFXQyxHQUFHLEdBQUd6QixLQUFLLENBQUNiLE1BQTVCLEVBQW9DcUMsQ0FBQyxHQUFHQyxHQUF4QyxFQUE2QyxFQUFFRCxDQUEvQyxFQUFrRDtBQUNoREYsSUFBQUEsSUFBSSxHQUFHdEIsS0FBSyxDQUFDd0IsQ0FBRCxDQUFaO0FBQ0FELElBQUFBLEdBQUcsR0FBR0QsSUFBSSxDQUFDSSxPQUFMLENBQWEsR0FBYixDQUFOOztBQUNBLFFBQUlILEdBQUcsS0FBSyxDQUFDLENBQWIsRUFBZ0I7QUFDZHhCLE1BQUFBLEdBQUcsQ0FBQzRCLGtCQUFrQixDQUFDTCxJQUFELENBQW5CLENBQUgsR0FBZ0MsRUFBaEM7QUFDRCxLQUZELE1BRU87QUFDTHZCLE1BQUFBLEdBQUcsQ0FBQzRCLGtCQUFrQixDQUFDTCxJQUFJLENBQUNNLEtBQUwsQ0FBVyxDQUFYLEVBQWNMLEdBQWQsQ0FBRCxDQUFuQixDQUFILEdBQThDSSxrQkFBa0IsQ0FDOURMLElBQUksQ0FBQ00sS0FBTCxDQUFXTCxHQUFHLEdBQUcsQ0FBakIsQ0FEOEQsQ0FBaEU7QUFHRDtBQUNGOztBQUVELFNBQU94QixHQUFQO0FBQ0Q7QUFFRDs7Ozs7QUFJQVgsT0FBTyxDQUFDK0IsV0FBUixHQUFzQkEsV0FBdEI7QUFFQTs7Ozs7OztBQU9BL0IsT0FBTyxDQUFDeUMsS0FBUixHQUFnQjtBQUNkQyxFQUFBQSxJQUFJLEVBQUUsV0FEUTtBQUVkQyxFQUFBQSxJQUFJLEVBQUUsa0JBRlE7QUFHZEMsRUFBQUEsR0FBRyxFQUFFLFVBSFM7QUFJZEMsRUFBQUEsVUFBVSxFQUFFLG1DQUpFO0FBS2RDLEVBQUFBLElBQUksRUFBRSxtQ0FMUTtBQU1kLGVBQWE7QUFOQyxDQUFoQjtBQVNBOzs7Ozs7Ozs7QUFTQTlDLE9BQU8sQ0FBQ1UsU0FBUixHQUFvQjtBQUNsQix1Q0FBcUNBLFNBRG5CO0FBRWxCLHNCQUFvQnhCO0FBRkYsQ0FBcEI7QUFLQTs7Ozs7Ozs7O0FBU0FjLE9BQU8sQ0FBQytDLEtBQVIsR0FBZ0I7QUFDZCx1Q0FBcUNoQixXQUR2QjtBQUVkLHNCQUFvQmlCLElBQUksQ0FBQ0Q7QUFGWCxDQUFoQjtBQUtBOzs7Ozs7Ozs7QUFTQSxTQUFTRSxXQUFULENBQXFCakIsR0FBckIsRUFBMEI7QUFDeEIsTUFBTWtCLEtBQUssR0FBR2xCLEdBQUcsQ0FBQ0MsS0FBSixDQUFVLE9BQVYsQ0FBZDtBQUNBLE1BQU1rQixNQUFNLEdBQUcsRUFBZjtBQUNBLE1BQUlDLEtBQUo7QUFDQSxNQUFJQyxJQUFKO0FBQ0EsTUFBSUMsS0FBSjtBQUNBLE1BQUlsQyxHQUFKOztBQUVBLE9BQUssSUFBSWdCLENBQUMsR0FBRyxDQUFSLEVBQVdDLEdBQUcsR0FBR2EsS0FBSyxDQUFDbkQsTUFBNUIsRUFBb0NxQyxDQUFDLEdBQUdDLEdBQXhDLEVBQTZDLEVBQUVELENBQS9DLEVBQWtEO0FBQ2hEaUIsSUFBQUEsSUFBSSxHQUFHSCxLQUFLLENBQUNkLENBQUQsQ0FBWjtBQUNBZ0IsSUFBQUEsS0FBSyxHQUFHQyxJQUFJLENBQUNmLE9BQUwsQ0FBYSxHQUFiLENBQVI7O0FBQ0EsUUFBSWMsS0FBSyxLQUFLLENBQUMsQ0FBZixFQUFrQjtBQUNoQjtBQUNBO0FBQ0Q7O0FBRURFLElBQUFBLEtBQUssR0FBR0QsSUFBSSxDQUFDYixLQUFMLENBQVcsQ0FBWCxFQUFjWSxLQUFkLEVBQXFCRyxXQUFyQixFQUFSO0FBQ0FuQyxJQUFBQSxHQUFHLEdBQUdiLElBQUksQ0FBQzhDLElBQUksQ0FBQ2IsS0FBTCxDQUFXWSxLQUFLLEdBQUcsQ0FBbkIsQ0FBRCxDQUFWO0FBQ0FELElBQUFBLE1BQU0sQ0FBQ0csS0FBRCxDQUFOLEdBQWdCbEMsR0FBaEI7QUFDRDs7QUFFRCxTQUFPK0IsTUFBUDtBQUNEO0FBRUQ7Ozs7Ozs7OztBQVFBLFNBQVNLLE1BQVQsQ0FBZ0JDLElBQWhCLEVBQXNCO0FBQ3BCO0FBQ0E7QUFDQSxTQUFPLHFCQUFxQkMsSUFBckIsQ0FBMEJELElBQTFCLENBQVA7QUFDRDtBQUVEOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztBQThDQSxTQUFTRSxRQUFULENBQWtCQyxHQUFsQixFQUF1QjtBQUNyQixPQUFLQSxHQUFMLEdBQVdBLEdBQVg7QUFDQSxPQUFLQyxHQUFMLEdBQVcsS0FBS0QsR0FBTCxDQUFTQyxHQUFwQixDQUZxQixDQUdyQjs7QUFDQSxPQUFLQyxJQUFMLEdBQ0csS0FBS0YsR0FBTCxDQUFTbEUsTUFBVCxLQUFvQixNQUFwQixLQUNFLEtBQUttRSxHQUFMLENBQVNFLFlBQVQsS0FBMEIsRUFBMUIsSUFBZ0MsS0FBS0YsR0FBTCxDQUFTRSxZQUFULEtBQTBCLE1BRDVELENBQUQsSUFFQSxPQUFPLEtBQUtGLEdBQUwsQ0FBU0UsWUFBaEIsS0FBaUMsV0FGakMsR0FHSSxLQUFLRixHQUFMLENBQVNHLFlBSGIsR0FJSSxJQUxOO0FBTUEsT0FBS0MsVUFBTCxHQUFrQixLQUFLTCxHQUFMLENBQVNDLEdBQVQsQ0FBYUksVUFBL0I7QUFWcUIsTUFXZkMsTUFYZSxHQVdKLEtBQUtMLEdBWEQsQ0FXZkssTUFYZSxFQVlyQjs7QUFDQSxNQUFJQSxNQUFNLEtBQUssSUFBZixFQUFxQjtBQUNuQkEsSUFBQUEsTUFBTSxHQUFHLEdBQVQ7QUFDRDs7QUFFRCxPQUFLQyxvQkFBTCxDQUEwQkQsTUFBMUI7O0FBQ0EsT0FBS0UsT0FBTCxHQUFlbkIsV0FBVyxDQUFDLEtBQUtZLEdBQUwsQ0FBU1EscUJBQVQsRUFBRCxDQUExQjtBQUNBLE9BQUtDLE1BQUwsR0FBYyxLQUFLRixPQUFuQixDQW5CcUIsQ0FvQnJCO0FBQ0E7QUFDQTs7QUFDQSxPQUFLRSxNQUFMLENBQVksY0FBWixJQUE4QixLQUFLVCxHQUFMLENBQVNVLGlCQUFULENBQTJCLGNBQTNCLENBQTlCOztBQUNBLE9BQUtDLG9CQUFMLENBQTBCLEtBQUtGLE1BQS9COztBQUVBLE1BQUksS0FBS1IsSUFBTCxLQUFjLElBQWQsSUFBc0JGLEdBQUcsQ0FBQ2EsYUFBOUIsRUFBNkM7QUFDM0MsU0FBS0MsSUFBTCxHQUFZLEtBQUtiLEdBQUwsQ0FBU2MsUUFBckI7QUFDRCxHQUZELE1BRU87QUFDTCxTQUFLRCxJQUFMLEdBQ0UsS0FBS2QsR0FBTCxDQUFTbEUsTUFBVCxLQUFvQixNQUFwQixHQUNJLElBREosR0FFSSxLQUFLa0YsVUFBTCxDQUFnQixLQUFLZCxJQUFMLEdBQVksS0FBS0EsSUFBakIsR0FBd0IsS0FBS0QsR0FBTCxDQUFTYyxRQUFqRCxDQUhOO0FBSUQ7QUFDRixDLENBRUQ7OztBQUNBdEYsWUFBWSxDQUFDc0UsUUFBUSxDQUFDNUMsU0FBVixDQUFaO0FBRUE7Ozs7Ozs7Ozs7O0FBV0E0QyxRQUFRLENBQUM1QyxTQUFULENBQW1CNkQsVUFBbkIsR0FBZ0MsVUFBUzVDLEdBQVQsRUFBYztBQUM1QyxNQUFJZSxLQUFLLEdBQUcvQyxPQUFPLENBQUMrQyxLQUFSLENBQWMsS0FBSzhCLElBQW5CLENBQVo7O0FBQ0EsTUFBSSxLQUFLakIsR0FBTCxDQUFTa0IsT0FBYixFQUFzQjtBQUNwQixXQUFPLEtBQUtsQixHQUFMLENBQVNrQixPQUFULENBQWlCLElBQWpCLEVBQXVCOUMsR0FBdkIsQ0FBUDtBQUNEOztBQUVELE1BQUksQ0FBQ2UsS0FBRCxJQUFVUyxNQUFNLENBQUMsS0FBS3FCLElBQU4sQ0FBcEIsRUFBaUM7QUFDL0I5QixJQUFBQSxLQUFLLEdBQUcvQyxPQUFPLENBQUMrQyxLQUFSLENBQWMsa0JBQWQsQ0FBUjtBQUNEOztBQUVELFNBQU9BLEtBQUssSUFBSWYsR0FBVCxLQUFpQkEsR0FBRyxDQUFDakMsTUFBSixHQUFhLENBQWIsSUFBa0JpQyxHQUFHLFlBQVlsQixNQUFsRCxJQUNIaUMsS0FBSyxDQUFDZixHQUFELENBREYsR0FFSCxJQUZKO0FBR0QsQ0FiRDtBQWVBOzs7Ozs7OztBQU9BMkIsUUFBUSxDQUFDNUMsU0FBVCxDQUFtQmdFLE9BQW5CLEdBQTZCLFlBQVc7QUFBQSxNQUM5Qm5CLEdBRDhCLEdBQ3RCLElBRHNCLENBQzlCQSxHQUQ4QjtBQUFBLE1BRTlCbEUsTUFGOEIsR0FFbkJrRSxHQUZtQixDQUU5QmxFLE1BRjhCO0FBQUEsTUFHOUJDLEdBSDhCLEdBR3RCaUUsR0FIc0IsQ0FHOUJqRSxHQUg4QjtBQUt0QyxNQUFNcUYsR0FBRyxvQkFBYXRGLE1BQWIsY0FBdUJDLEdBQXZCLGVBQStCLEtBQUt1RSxNQUFwQyxNQUFUO0FBQ0EsTUFBTWUsR0FBRyxHQUFHLElBQUkzRSxLQUFKLENBQVUwRSxHQUFWLENBQVo7QUFDQUMsRUFBQUEsR0FBRyxDQUFDZixNQUFKLEdBQWEsS0FBS0EsTUFBbEI7QUFDQWUsRUFBQUEsR0FBRyxDQUFDdkYsTUFBSixHQUFhQSxNQUFiO0FBQ0F1RixFQUFBQSxHQUFHLENBQUN0RixHQUFKLEdBQVVBLEdBQVY7QUFFQSxTQUFPc0YsR0FBUDtBQUNELENBWkQ7QUFjQTs7Ozs7QUFJQWpGLE9BQU8sQ0FBQzJELFFBQVIsR0FBbUJBLFFBQW5CO0FBRUE7Ozs7Ozs7O0FBUUEsU0FBUy9ELE9BQVQsQ0FBaUJGLE1BQWpCLEVBQXlCQyxHQUF6QixFQUE4QjtBQUM1QixNQUFNZCxJQUFJLEdBQUcsSUFBYjtBQUNBLE9BQUtxRyxNQUFMLEdBQWMsS0FBS0EsTUFBTCxJQUFlLEVBQTdCO0FBQ0EsT0FBS3hGLE1BQUwsR0FBY0EsTUFBZDtBQUNBLE9BQUtDLEdBQUwsR0FBV0EsR0FBWDtBQUNBLE9BQUsyRSxNQUFMLEdBQWMsRUFBZCxDQUw0QixDQUtWOztBQUNsQixPQUFLYSxPQUFMLEdBQWUsRUFBZixDQU40QixDQU1UOztBQUNuQixPQUFLQyxFQUFMLENBQVEsS0FBUixFQUFlLFlBQU07QUFDbkIsUUFBSUgsR0FBRyxHQUFHLElBQVY7QUFDQSxRQUFJSSxHQUFHLEdBQUcsSUFBVjs7QUFFQSxRQUFJO0FBQ0ZBLE1BQUFBLEdBQUcsR0FBRyxJQUFJMUIsUUFBSixDQUFhOUUsSUFBYixDQUFOO0FBQ0QsS0FGRCxDQUVFLE9BQU95RyxJQUFQLEVBQWE7QUFDYkwsTUFBQUEsR0FBRyxHQUFHLElBQUkzRSxLQUFKLENBQVUsd0NBQVYsQ0FBTjtBQUNBMkUsTUFBQUEsR0FBRyxDQUFDbEMsS0FBSixHQUFZLElBQVo7QUFDQWtDLE1BQUFBLEdBQUcsQ0FBQ00sUUFBSixHQUFlRCxJQUFmLENBSGEsQ0FJYjs7QUFDQSxVQUFJekcsSUFBSSxDQUFDZ0YsR0FBVCxFQUFjO0FBQ1o7QUFDQW9CLFFBQUFBLEdBQUcsQ0FBQ08sV0FBSixHQUNFLE9BQU8zRyxJQUFJLENBQUNnRixHQUFMLENBQVNFLFlBQWhCLEtBQWlDLFdBQWpDLEdBQ0lsRixJQUFJLENBQUNnRixHQUFMLENBQVNHLFlBRGIsR0FFSW5GLElBQUksQ0FBQ2dGLEdBQUwsQ0FBU2MsUUFIZixDQUZZLENBTVo7O0FBQ0FNLFFBQUFBLEdBQUcsQ0FBQ2YsTUFBSixHQUFhckYsSUFBSSxDQUFDZ0YsR0FBTCxDQUFTSyxNQUFULEdBQWtCckYsSUFBSSxDQUFDZ0YsR0FBTCxDQUFTSyxNQUEzQixHQUFvQyxJQUFqRDtBQUNBZSxRQUFBQSxHQUFHLENBQUNRLFVBQUosR0FBaUJSLEdBQUcsQ0FBQ2YsTUFBckIsQ0FSWSxDQVFpQjtBQUM5QixPQVRELE1BU087QUFDTGUsUUFBQUEsR0FBRyxDQUFDTyxXQUFKLEdBQWtCLElBQWxCO0FBQ0FQLFFBQUFBLEdBQUcsQ0FBQ2YsTUFBSixHQUFhLElBQWI7QUFDRDs7QUFFRCxhQUFPckYsSUFBSSxDQUFDNkcsUUFBTCxDQUFjVCxHQUFkLENBQVA7QUFDRDs7QUFFRHBHLElBQUFBLElBQUksQ0FBQzhHLElBQUwsQ0FBVSxVQUFWLEVBQXNCTixHQUF0QjtBQUVBLFFBQUlPLE9BQUo7O0FBQ0EsUUFBSTtBQUNGLFVBQUksQ0FBQy9HLElBQUksQ0FBQ2dILGFBQUwsQ0FBbUJSLEdBQW5CLENBQUwsRUFBOEI7QUFDNUJPLFFBQUFBLE9BQU8sR0FBRyxJQUFJdEYsS0FBSixDQUNSK0UsR0FBRyxDQUFDcEIsVUFBSixJQUFrQm9CLEdBQUcsQ0FBQ3ZCLElBQXRCLElBQThCLDRCQUR0QixDQUFWO0FBR0Q7QUFDRixLQU5ELENBTUUsT0FBT3dCLElBQVAsRUFBYTtBQUNiTSxNQUFBQSxPQUFPLEdBQUdOLElBQVYsQ0FEYSxDQUNHO0FBQ2pCLEtBdkNrQixDQXlDbkI7OztBQUNBLFFBQUlNLE9BQUosRUFBYTtBQUNYQSxNQUFBQSxPQUFPLENBQUNMLFFBQVIsR0FBbUJOLEdBQW5CO0FBQ0FXLE1BQUFBLE9BQU8sQ0FBQ2pCLFFBQVIsR0FBbUJVLEdBQW5CO0FBQ0FPLE1BQUFBLE9BQU8sQ0FBQzFCLE1BQVIsR0FBaUJtQixHQUFHLENBQUNuQixNQUFyQjtBQUNBckYsTUFBQUEsSUFBSSxDQUFDNkcsUUFBTCxDQUFjRSxPQUFkLEVBQXVCUCxHQUF2QjtBQUNELEtBTEQsTUFLTztBQUNMeEcsTUFBQUEsSUFBSSxDQUFDNkcsUUFBTCxDQUFjLElBQWQsRUFBb0JMLEdBQXBCO0FBQ0Q7QUFDRixHQWxERDtBQW1ERDtBQUVEOzs7QUFJQTs7O0FBQ0FyRyxPQUFPLENBQUNZLE9BQU8sQ0FBQ21CLFNBQVQsQ0FBUCxDLENBQ0E7O0FBQ0E1QixXQUFXLENBQUNTLE9BQU8sQ0FBQ21CLFNBQVQsQ0FBWDtBQUVBOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0FBc0JBbkIsT0FBTyxDQUFDbUIsU0FBUixDQUFrQjhELElBQWxCLEdBQXlCLFVBQVNBLElBQVQsRUFBZTtBQUN0QyxPQUFLaUIsR0FBTCxDQUFTLGNBQVQsRUFBeUI5RixPQUFPLENBQUN5QyxLQUFSLENBQWNvQyxJQUFkLEtBQXVCQSxJQUFoRDtBQUNBLFNBQU8sSUFBUDtBQUNELENBSEQ7QUFLQTs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0FBb0JBakYsT0FBTyxDQUFDbUIsU0FBUixDQUFrQmdGLE1BQWxCLEdBQTJCLFVBQVNsQixJQUFULEVBQWU7QUFDeEMsT0FBS2lCLEdBQUwsQ0FBUyxRQUFULEVBQW1COUYsT0FBTyxDQUFDeUMsS0FBUixDQUFjb0MsSUFBZCxLQUF1QkEsSUFBMUM7QUFDQSxTQUFPLElBQVA7QUFDRCxDQUhEO0FBS0E7Ozs7Ozs7Ozs7O0FBVUFqRixPQUFPLENBQUNtQixTQUFSLENBQWtCaUYsSUFBbEIsR0FBeUIsVUFBU0MsSUFBVCxFQUFlQyxJQUFmLEVBQXFCQyxPQUFyQixFQUE4QjtBQUNyRCxNQUFJckcsU0FBUyxDQUFDQyxNQUFWLEtBQXFCLENBQXpCLEVBQTRCbUcsSUFBSSxHQUFHLEVBQVA7O0FBQzVCLE1BQUksUUFBT0EsSUFBUCxNQUFnQixRQUFoQixJQUE0QkEsSUFBSSxLQUFLLElBQXpDLEVBQStDO0FBQzdDO0FBQ0FDLElBQUFBLE9BQU8sR0FBR0QsSUFBVjtBQUNBQSxJQUFBQSxJQUFJLEdBQUcsRUFBUDtBQUNEOztBQUVELE1BQUksQ0FBQ0MsT0FBTCxFQUFjO0FBQ1pBLElBQUFBLE9BQU8sR0FBRztBQUNSdEIsTUFBQUEsSUFBSSxFQUFFLE9BQU91QixJQUFQLEtBQWdCLFVBQWhCLEdBQTZCLE9BQTdCLEdBQXVDO0FBRHJDLEtBQVY7QUFHRDs7QUFFRCxNQUFNQyxPQUFPLEdBQUcsU0FBVkEsT0FBVSxDQUFBQyxNQUFNLEVBQUk7QUFDeEIsUUFBSSxPQUFPRixJQUFQLEtBQWdCLFVBQXBCLEVBQWdDO0FBQzlCLGFBQU9BLElBQUksQ0FBQ0UsTUFBRCxDQUFYO0FBQ0Q7O0FBRUQsVUFBTSxJQUFJaEcsS0FBSixDQUFVLCtDQUFWLENBQU47QUFDRCxHQU5EOztBQVFBLFNBQU8sS0FBS2lHLEtBQUwsQ0FBV04sSUFBWCxFQUFpQkMsSUFBakIsRUFBdUJDLE9BQXZCLEVBQWdDRSxPQUFoQyxDQUFQO0FBQ0QsQ0F2QkQ7QUF5QkE7Ozs7Ozs7Ozs7Ozs7OztBQWNBekcsT0FBTyxDQUFDbUIsU0FBUixDQUFrQnlGLEtBQWxCLEdBQTBCLFVBQVNwRixHQUFULEVBQWM7QUFDdEMsTUFBSSxPQUFPQSxHQUFQLEtBQWUsUUFBbkIsRUFBNkJBLEdBQUcsR0FBR1YsU0FBUyxDQUFDVSxHQUFELENBQWY7QUFDN0IsTUFBSUEsR0FBSixFQUFTLEtBQUs4RCxNQUFMLENBQVk1RCxJQUFaLENBQWlCRixHQUFqQjtBQUNULFNBQU8sSUFBUDtBQUNELENBSkQ7QUFNQTs7Ozs7Ozs7Ozs7Ozs7Ozs7O0FBaUJBeEIsT0FBTyxDQUFDbUIsU0FBUixDQUFrQjBGLE1BQWxCLEdBQTJCLFVBQVNuRCxLQUFULEVBQWdCb0QsSUFBaEIsRUFBc0JQLE9BQXRCLEVBQStCO0FBQ3hELE1BQUlPLElBQUosRUFBVTtBQUNSLFFBQUksS0FBS0MsS0FBVCxFQUFnQjtBQUNkLFlBQU0sSUFBSXJHLEtBQUosQ0FBVSw0Q0FBVixDQUFOO0FBQ0Q7O0FBRUQsU0FBS3NHLFlBQUwsR0FBb0JDLE1BQXBCLENBQTJCdkQsS0FBM0IsRUFBa0NvRCxJQUFsQyxFQUF3Q1AsT0FBTyxJQUFJTyxJQUFJLENBQUNJLElBQXhEO0FBQ0Q7O0FBRUQsU0FBTyxJQUFQO0FBQ0QsQ0FWRDs7QUFZQWxILE9BQU8sQ0FBQ21CLFNBQVIsQ0FBa0I2RixZQUFsQixHQUFpQyxZQUFXO0FBQzFDLE1BQUksQ0FBQyxLQUFLRyxTQUFWLEVBQXFCO0FBQ25CLFNBQUtBLFNBQUwsR0FBaUIsSUFBSXBJLElBQUksQ0FBQ3FJLFFBQVQsRUFBakI7QUFDRDs7QUFFRCxTQUFPLEtBQUtELFNBQVo7QUFDRCxDQU5EO0FBUUE7Ozs7Ozs7Ozs7QUFTQW5ILE9BQU8sQ0FBQ21CLFNBQVIsQ0FBa0IyRSxRQUFsQixHQUE2QixVQUFTVCxHQUFULEVBQWNJLEdBQWQsRUFBbUI7QUFDOUMsTUFBSSxLQUFLNEIsWUFBTCxDQUFrQmhDLEdBQWxCLEVBQXVCSSxHQUF2QixDQUFKLEVBQWlDO0FBQy9CLFdBQU8sS0FBSzZCLE1BQUwsRUFBUDtBQUNEOztBQUVELE1BQU1DLEVBQUUsR0FBRyxLQUFLQyxTQUFoQjtBQUNBLE9BQUtDLFlBQUw7O0FBRUEsTUFBSXBDLEdBQUosRUFBUztBQUNQLFFBQUksS0FBS3FDLFdBQVQsRUFBc0JyQyxHQUFHLENBQUNzQyxPQUFKLEdBQWMsS0FBS0MsUUFBTCxHQUFnQixDQUE5QjtBQUN0QixTQUFLN0IsSUFBTCxDQUFVLE9BQVYsRUFBbUJWLEdBQW5CO0FBQ0Q7O0FBRURrQyxFQUFBQSxFQUFFLENBQUNsQyxHQUFELEVBQU1JLEdBQU4sQ0FBRjtBQUNELENBZEQ7QUFnQkE7Ozs7Ozs7QUFNQXpGLE9BQU8sQ0FBQ21CLFNBQVIsQ0FBa0IwRyxnQkFBbEIsR0FBcUMsWUFBVztBQUM5QyxNQUFNeEMsR0FBRyxHQUFHLElBQUkzRSxLQUFKLENBQ1YsOEpBRFUsQ0FBWjtBQUdBMkUsRUFBQUEsR0FBRyxDQUFDeUMsV0FBSixHQUFrQixJQUFsQjtBQUVBekMsRUFBQUEsR0FBRyxDQUFDZixNQUFKLEdBQWEsS0FBS0EsTUFBbEI7QUFDQWUsRUFBQUEsR0FBRyxDQUFDdkYsTUFBSixHQUFhLEtBQUtBLE1BQWxCO0FBQ0F1RixFQUFBQSxHQUFHLENBQUN0RixHQUFKLEdBQVUsS0FBS0EsR0FBZjtBQUVBLE9BQUsrRixRQUFMLENBQWNULEdBQWQ7QUFDRCxDQVhELEMsQ0FhQTs7O0FBQ0FyRixPQUFPLENBQUNtQixTQUFSLENBQWtCNEcsS0FBbEIsR0FBMEIsWUFBVztBQUNuQzdJLEVBQUFBLE9BQU8sQ0FBQ0MsSUFBUixDQUFhLHdEQUFiO0FBQ0EsU0FBTyxJQUFQO0FBQ0QsQ0FIRDs7QUFLQWEsT0FBTyxDQUFDbUIsU0FBUixDQUFrQjZHLEVBQWxCLEdBQXVCaEksT0FBTyxDQUFDbUIsU0FBUixDQUFrQjRHLEtBQXpDO0FBQ0EvSCxPQUFPLENBQUNtQixTQUFSLENBQWtCOEcsTUFBbEIsR0FBMkJqSSxPQUFPLENBQUNtQixTQUFSLENBQWtCNkcsRUFBN0MsQyxDQUVBOztBQUNBaEksT0FBTyxDQUFDbUIsU0FBUixDQUFrQitHLEtBQWxCLEdBQTBCLFlBQU07QUFDOUIsUUFBTSxJQUFJeEgsS0FBSixDQUNKLDZEQURJLENBQU47QUFHRCxDQUpEOztBQU1BVixPQUFPLENBQUNtQixTQUFSLENBQWtCZ0gsSUFBbEIsR0FBeUJuSSxPQUFPLENBQUNtQixTQUFSLENBQWtCK0csS0FBM0M7QUFFQTs7Ozs7Ozs7O0FBUUFsSSxPQUFPLENBQUNtQixTQUFSLENBQWtCaUgsT0FBbEIsR0FBNEIsVUFBU3JILEdBQVQsRUFBYztBQUN4QztBQUNBLFNBQ0VBLEdBQUcsSUFDSCxRQUFPQSxHQUFQLE1BQWUsUUFEZixJQUVBLENBQUNhLEtBQUssQ0FBQ0MsT0FBTixDQUFjZCxHQUFkLENBRkQsSUFHQUcsTUFBTSxDQUFDQyxTQUFQLENBQWlCa0gsUUFBakIsQ0FBMEJoSCxJQUExQixDQUErQk4sR0FBL0IsTUFBd0MsaUJBSjFDO0FBTUQsQ0FSRDtBQVVBOzs7Ozs7Ozs7O0FBU0FmLE9BQU8sQ0FBQ21CLFNBQVIsQ0FBa0JsQixHQUFsQixHQUF3QixVQUFTc0gsRUFBVCxFQUFhO0FBQ25DLE1BQUksS0FBS2UsVUFBVCxFQUFxQjtBQUNuQnBKLElBQUFBLE9BQU8sQ0FBQ0MsSUFBUixDQUNFLHVFQURGO0FBR0Q7O0FBRUQsT0FBS21KLFVBQUwsR0FBa0IsSUFBbEIsQ0FQbUMsQ0FTbkM7O0FBQ0EsT0FBS2QsU0FBTCxHQUFpQkQsRUFBRSxJQUFJNUgsSUFBdkIsQ0FWbUMsQ0FZbkM7O0FBQ0EsT0FBSzRJLG9CQUFMOztBQUVBLE9BQUtDLElBQUw7QUFDRCxDQWhCRDs7QUFrQkF4SSxPQUFPLENBQUNtQixTQUFSLENBQWtCc0gsaUJBQWxCLEdBQXNDLFlBQVc7QUFDL0MsTUFBTXhKLElBQUksR0FBRyxJQUFiLENBRCtDLENBRy9DOztBQUNBLE1BQUksS0FBS3lKLGNBQUwsSUFBdUIsQ0FBQyxLQUFLQyxtQkFBakMsRUFBc0Q7QUFDcEQsU0FBS0EsbUJBQUwsR0FBMkJDLFVBQVUsQ0FBQyxZQUFNO0FBQzFDM0osTUFBQUEsSUFBSSxDQUFDNEosYUFBTCxDQUNFLG9CQURGLEVBRUU1SixJQUFJLENBQUN5SixjQUZQLEVBR0UsV0FIRjtBQUtELEtBTm9DLEVBTWxDLEtBQUtBLGNBTjZCLENBQXJDO0FBT0Q7QUFDRixDQWJELEMsQ0FlQTs7O0FBQ0ExSSxPQUFPLENBQUNtQixTQUFSLENBQWtCcUgsSUFBbEIsR0FBeUIsWUFBVztBQUNsQyxNQUFJLEtBQUtNLFFBQVQsRUFDRSxPQUFPLEtBQUtoRCxRQUFMLENBQ0wsSUFBSXBGLEtBQUosQ0FBVSw0REFBVixDQURLLENBQVA7QUFJRixNQUFNekIsSUFBSSxHQUFHLElBQWI7QUFDQSxPQUFLZ0YsR0FBTCxHQUFXN0QsT0FBTyxDQUFDQyxNQUFSLEVBQVg7QUFQa0MsTUFRMUI0RCxHQVIwQixHQVFsQixJQVJrQixDQVExQkEsR0FSMEI7QUFTbEMsTUFBSThFLElBQUksR0FBRyxLQUFLNUIsU0FBTCxJQUFrQixLQUFLSixLQUFsQzs7QUFFQSxPQUFLaUMsWUFBTCxHQVhrQyxDQWFsQzs7O0FBQ0EvRSxFQUFBQSxHQUFHLENBQUNnRixrQkFBSixHQUF5QixZQUFNO0FBQUEsUUFDckJDLFVBRHFCLEdBQ05qRixHQURNLENBQ3JCaUYsVUFEcUI7O0FBRTdCLFFBQUlBLFVBQVUsSUFBSSxDQUFkLElBQW1CakssSUFBSSxDQUFDa0sscUJBQTVCLEVBQW1EO0FBQ2pEMUIsTUFBQUEsWUFBWSxDQUFDeEksSUFBSSxDQUFDa0sscUJBQU4sQ0FBWjtBQUNEOztBQUVELFFBQUlELFVBQVUsS0FBSyxDQUFuQixFQUFzQjtBQUNwQjtBQUNELEtBUjRCLENBVTdCO0FBQ0E7OztBQUNBLFFBQUk1RSxNQUFKOztBQUNBLFFBQUk7QUFDRkEsTUFBQUEsTUFBTSxHQUFHTCxHQUFHLENBQUNLLE1BQWI7QUFDRCxLQUZELENBRUUsaUJBQU07QUFDTkEsTUFBQUEsTUFBTSxHQUFHLENBQVQ7QUFDRDs7QUFFRCxRQUFJLENBQUNBLE1BQUwsRUFBYTtBQUNYLFVBQUlyRixJQUFJLENBQUNtSyxRQUFMLElBQWlCbkssSUFBSSxDQUFDNkosUUFBMUIsRUFBb0M7QUFDcEMsYUFBTzdKLElBQUksQ0FBQzRJLGdCQUFMLEVBQVA7QUFDRDs7QUFFRDVJLElBQUFBLElBQUksQ0FBQzhHLElBQUwsQ0FBVSxLQUFWO0FBQ0QsR0F6QkQsQ0Fka0MsQ0F5Q2xDOzs7QUFDQSxNQUFNc0QsY0FBYyxHQUFHLFNBQWpCQSxjQUFpQixDQUFDQyxTQUFELEVBQVlDLENBQVosRUFBa0I7QUFDdkMsUUFBSUEsQ0FBQyxDQUFDQyxLQUFGLEdBQVUsQ0FBZCxFQUFpQjtBQUNmRCxNQUFBQSxDQUFDLENBQUNFLE9BQUYsR0FBYUYsQ0FBQyxDQUFDRyxNQUFGLEdBQVdILENBQUMsQ0FBQ0MsS0FBZCxHQUF1QixHQUFuQzs7QUFFQSxVQUFJRCxDQUFDLENBQUNFLE9BQUYsS0FBYyxHQUFsQixFQUF1QjtBQUNyQmhDLFFBQUFBLFlBQVksQ0FBQ3hJLElBQUksQ0FBQzBKLG1CQUFOLENBQVo7QUFDRDtBQUNGOztBQUVEWSxJQUFBQSxDQUFDLENBQUNELFNBQUYsR0FBY0EsU0FBZDtBQUNBckssSUFBQUEsSUFBSSxDQUFDOEcsSUFBTCxDQUFVLFVBQVYsRUFBc0J3RCxDQUF0QjtBQUNELEdBWEQ7O0FBYUEsTUFBSSxLQUFLSSxZQUFMLENBQWtCLFVBQWxCLENBQUosRUFBbUM7QUFDakMsUUFBSTtBQUNGMUYsTUFBQUEsR0FBRyxDQUFDMkYsZ0JBQUosQ0FBcUIsVUFBckIsRUFBaUNQLGNBQWMsQ0FBQ1EsSUFBZixDQUFvQixJQUFwQixFQUEwQixVQUExQixDQUFqQzs7QUFDQSxVQUFJNUYsR0FBRyxDQUFDNkYsTUFBUixFQUFnQjtBQUNkN0YsUUFBQUEsR0FBRyxDQUFDNkYsTUFBSixDQUFXRixnQkFBWCxDQUNFLFVBREYsRUFFRVAsY0FBYyxDQUFDUSxJQUFmLENBQW9CLElBQXBCLEVBQTBCLFFBQTFCLENBRkY7QUFJRDtBQUNGLEtBUkQsQ0FRRSxpQkFBTSxDQUNOO0FBQ0E7QUFDQTtBQUNEO0FBQ0Y7O0FBRUQsTUFBSTVGLEdBQUcsQ0FBQzZGLE1BQVIsRUFBZ0I7QUFDZCxTQUFLckIsaUJBQUw7QUFDRCxHQXpFaUMsQ0EyRWxDOzs7QUFDQSxNQUFJO0FBQ0YsUUFBSSxLQUFLc0IsUUFBTCxJQUFpQixLQUFLQyxRQUExQixFQUFvQztBQUNsQy9GLE1BQUFBLEdBQUcsQ0FBQ2dHLElBQUosQ0FBUyxLQUFLbkssTUFBZCxFQUFzQixLQUFLQyxHQUEzQixFQUFnQyxJQUFoQyxFQUFzQyxLQUFLZ0ssUUFBM0MsRUFBcUQsS0FBS0MsUUFBMUQ7QUFDRCxLQUZELE1BRU87QUFDTC9GLE1BQUFBLEdBQUcsQ0FBQ2dHLElBQUosQ0FBUyxLQUFLbkssTUFBZCxFQUFzQixLQUFLQyxHQUEzQixFQUFnQyxJQUFoQztBQUNEO0FBQ0YsR0FORCxDQU1FLE9BQU9zRixHQUFQLEVBQVk7QUFDWjtBQUNBLFdBQU8sS0FBS1MsUUFBTCxDQUFjVCxHQUFkLENBQVA7QUFDRCxHQXJGaUMsQ0F1RmxDOzs7QUFDQSxNQUFJLEtBQUs2RSxnQkFBVCxFQUEyQmpHLEdBQUcsQ0FBQ2tHLGVBQUosR0FBc0IsSUFBdEIsQ0F4Rk8sQ0EwRmxDOztBQUNBLE1BQ0UsQ0FBQyxLQUFLaEQsU0FBTixJQUNBLEtBQUtySCxNQUFMLEtBQWdCLEtBRGhCLElBRUEsS0FBS0EsTUFBTCxLQUFnQixNQUZoQixJQUdBLE9BQU9pSixJQUFQLEtBQWdCLFFBSGhCLElBSUEsQ0FBQyxLQUFLWCxPQUFMLENBQWFXLElBQWIsQ0FMSCxFQU1FO0FBQ0E7QUFDQSxRQUFNcUIsV0FBVyxHQUFHLEtBQUs3RSxPQUFMLENBQWEsY0FBYixDQUFwQjs7QUFDQSxRQUFJekUsVUFBUyxHQUNYLEtBQUt1SixXQUFMLElBQ0FqSyxPQUFPLENBQUNVLFNBQVIsQ0FBa0JzSixXQUFXLEdBQUdBLFdBQVcsQ0FBQy9ILEtBQVosQ0FBa0IsR0FBbEIsRUFBdUIsQ0FBdkIsQ0FBSCxHQUErQixFQUE1RCxDQUZGOztBQUdBLFFBQUksQ0FBQ3ZCLFVBQUQsSUFBYzhDLE1BQU0sQ0FBQ3dHLFdBQUQsQ0FBeEIsRUFBdUM7QUFDckN0SixNQUFBQSxVQUFTLEdBQUdWLE9BQU8sQ0FBQ1UsU0FBUixDQUFrQixrQkFBbEIsQ0FBWjtBQUNEOztBQUVELFFBQUlBLFVBQUosRUFBZWlJLElBQUksR0FBR2pJLFVBQVMsQ0FBQ2lJLElBQUQsQ0FBaEI7QUFDaEIsR0E1R2lDLENBOEdsQzs7O0FBQ0EsT0FBSyxJQUFNckYsS0FBWCxJQUFvQixLQUFLZ0IsTUFBekIsRUFBaUM7QUFDL0IsUUFBSSxLQUFLQSxNQUFMLENBQVloQixLQUFaLE1BQXVCLElBQTNCLEVBQWlDO0FBRWpDLFFBQUl4QyxNQUFNLENBQUNDLFNBQVAsQ0FBaUJDLGNBQWpCLENBQWdDQyxJQUFoQyxDQUFxQyxLQUFLcUQsTUFBMUMsRUFBa0RoQixLQUFsRCxDQUFKLEVBQ0VPLEdBQUcsQ0FBQ3FHLGdCQUFKLENBQXFCNUcsS0FBckIsRUFBNEIsS0FBS2dCLE1BQUwsQ0FBWWhCLEtBQVosQ0FBNUI7QUFDSDs7QUFFRCxNQUFJLEtBQUttQixhQUFULEVBQXdCO0FBQ3RCWixJQUFBQSxHQUFHLENBQUNFLFlBQUosR0FBbUIsS0FBS1UsYUFBeEI7QUFDRCxHQXhIaUMsQ0EwSGxDOzs7QUFDQSxPQUFLa0IsSUFBTCxDQUFVLFNBQVYsRUFBcUIsSUFBckIsRUEzSGtDLENBNkhsQztBQUNBOztBQUNBOUIsRUFBQUEsR0FBRyxDQUFDc0csSUFBSixDQUFTLE9BQU94QixJQUFQLEtBQWdCLFdBQWhCLEdBQThCLElBQTlCLEdBQXFDQSxJQUE5QztBQUNELENBaElEOztBQWtJQTNJLE9BQU8sQ0FBQzJILEtBQVIsR0FBZ0I7QUFBQSxTQUFNLElBQUlySSxLQUFKLEVBQU47QUFBQSxDQUFoQjs7QUFFQSxDQUFDLEtBQUQsRUFBUSxNQUFSLEVBQWdCLFNBQWhCLEVBQTJCLE9BQTNCLEVBQW9DLEtBQXBDLEVBQTJDLFFBQTNDLEVBQXFEb0MsT0FBckQsQ0FBNkQsVUFBQWhDLE1BQU0sRUFBSTtBQUNyRUosRUFBQUEsS0FBSyxDQUFDeUIsU0FBTixDQUFnQnJCLE1BQU0sQ0FBQzZELFdBQVAsRUFBaEIsSUFBd0MsVUFBUzVELEdBQVQsRUFBY3dILEVBQWQsRUFBa0I7QUFDeEQsUUFBTXZELEdBQUcsR0FBRyxJQUFJNUQsT0FBTyxDQUFDSixPQUFaLENBQW9CRixNQUFwQixFQUE0QkMsR0FBNUIsQ0FBWjs7QUFDQSxTQUFLeUssWUFBTCxDQUFrQnhHLEdBQWxCOztBQUNBLFFBQUl1RCxFQUFKLEVBQVE7QUFDTnZELE1BQUFBLEdBQUcsQ0FBQy9ELEdBQUosQ0FBUXNILEVBQVI7QUFDRDs7QUFFRCxXQUFPdkQsR0FBUDtBQUNELEdBUkQ7QUFTRCxDQVZEO0FBWUF0RSxLQUFLLENBQUN5QixTQUFOLENBQWdCc0osR0FBaEIsR0FBc0IvSyxLQUFLLENBQUN5QixTQUFOLENBQWdCdUosTUFBdEM7QUFFQTs7Ozs7Ozs7OztBQVVBdEssT0FBTyxDQUFDdUssR0FBUixHQUFjLFVBQUM1SyxHQUFELEVBQU1nSixJQUFOLEVBQVl4QixFQUFaLEVBQW1CO0FBQy9CLE1BQU12RCxHQUFHLEdBQUc1RCxPQUFPLENBQUMsS0FBRCxFQUFRTCxHQUFSLENBQW5COztBQUNBLE1BQUksT0FBT2dKLElBQVAsS0FBZ0IsVUFBcEIsRUFBZ0M7QUFDOUJ4QixJQUFBQSxFQUFFLEdBQUd3QixJQUFMO0FBQ0FBLElBQUFBLElBQUksR0FBRyxJQUFQO0FBQ0Q7O0FBRUQsTUFBSUEsSUFBSixFQUFVL0UsR0FBRyxDQUFDNEMsS0FBSixDQUFVbUMsSUFBVjtBQUNWLE1BQUl4QixFQUFKLEVBQVF2RCxHQUFHLENBQUMvRCxHQUFKLENBQVFzSCxFQUFSO0FBQ1IsU0FBT3ZELEdBQVA7QUFDRCxDQVZEO0FBWUE7Ozs7Ozs7Ozs7O0FBVUE1RCxPQUFPLENBQUN3SyxJQUFSLEdBQWUsVUFBQzdLLEdBQUQsRUFBTWdKLElBQU4sRUFBWXhCLEVBQVosRUFBbUI7QUFDaEMsTUFBTXZELEdBQUcsR0FBRzVELE9BQU8sQ0FBQyxNQUFELEVBQVNMLEdBQVQsQ0FBbkI7O0FBQ0EsTUFBSSxPQUFPZ0osSUFBUCxLQUFnQixVQUFwQixFQUFnQztBQUM5QnhCLElBQUFBLEVBQUUsR0FBR3dCLElBQUw7QUFDQUEsSUFBQUEsSUFBSSxHQUFHLElBQVA7QUFDRDs7QUFFRCxNQUFJQSxJQUFKLEVBQVUvRSxHQUFHLENBQUM0QyxLQUFKLENBQVVtQyxJQUFWO0FBQ1YsTUFBSXhCLEVBQUosRUFBUXZELEdBQUcsQ0FBQy9ELEdBQUosQ0FBUXNILEVBQVI7QUFDUixTQUFPdkQsR0FBUDtBQUNELENBVkQ7QUFZQTs7Ozs7Ozs7Ozs7QUFVQTVELE9BQU8sQ0FBQ21HLE9BQVIsR0FBa0IsVUFBQ3hHLEdBQUQsRUFBTWdKLElBQU4sRUFBWXhCLEVBQVosRUFBbUI7QUFDbkMsTUFBTXZELEdBQUcsR0FBRzVELE9BQU8sQ0FBQyxTQUFELEVBQVlMLEdBQVosQ0FBbkI7O0FBQ0EsTUFBSSxPQUFPZ0osSUFBUCxLQUFnQixVQUFwQixFQUFnQztBQUM5QnhCLElBQUFBLEVBQUUsR0FBR3dCLElBQUw7QUFDQUEsSUFBQUEsSUFBSSxHQUFHLElBQVA7QUFDRDs7QUFFRCxNQUFJQSxJQUFKLEVBQVUvRSxHQUFHLENBQUN1RyxJQUFKLENBQVN4QixJQUFUO0FBQ1YsTUFBSXhCLEVBQUosRUFBUXZELEdBQUcsQ0FBQy9ELEdBQUosQ0FBUXNILEVBQVI7QUFDUixTQUFPdkQsR0FBUDtBQUNELENBVkQ7QUFZQTs7Ozs7Ozs7Ozs7QUFVQSxTQUFTeUcsR0FBVCxDQUFhMUssR0FBYixFQUFrQmdKLElBQWxCLEVBQXdCeEIsRUFBeEIsRUFBNEI7QUFDMUIsTUFBTXZELEdBQUcsR0FBRzVELE9BQU8sQ0FBQyxRQUFELEVBQVdMLEdBQVgsQ0FBbkI7O0FBQ0EsTUFBSSxPQUFPZ0osSUFBUCxLQUFnQixVQUFwQixFQUFnQztBQUM5QnhCLElBQUFBLEVBQUUsR0FBR3dCLElBQUw7QUFDQUEsSUFBQUEsSUFBSSxHQUFHLElBQVA7QUFDRDs7QUFFRCxNQUFJQSxJQUFKLEVBQVUvRSxHQUFHLENBQUN1RyxJQUFKLENBQVN4QixJQUFUO0FBQ1YsTUFBSXhCLEVBQUosRUFBUXZELEdBQUcsQ0FBQy9ELEdBQUosQ0FBUXNILEVBQVI7QUFDUixTQUFPdkQsR0FBUDtBQUNEOztBQUVENUQsT0FBTyxDQUFDcUssR0FBUixHQUFjQSxHQUFkO0FBQ0FySyxPQUFPLENBQUNzSyxNQUFSLEdBQWlCRCxHQUFqQjtBQUVBOzs7Ozs7Ozs7O0FBVUFySyxPQUFPLENBQUN5SyxLQUFSLEdBQWdCLFVBQUM5SyxHQUFELEVBQU1nSixJQUFOLEVBQVl4QixFQUFaLEVBQW1CO0FBQ2pDLE1BQU12RCxHQUFHLEdBQUc1RCxPQUFPLENBQUMsT0FBRCxFQUFVTCxHQUFWLENBQW5COztBQUNBLE1BQUksT0FBT2dKLElBQVAsS0FBZ0IsVUFBcEIsRUFBZ0M7QUFDOUJ4QixJQUFBQSxFQUFFLEdBQUd3QixJQUFMO0FBQ0FBLElBQUFBLElBQUksR0FBRyxJQUFQO0FBQ0Q7O0FBRUQsTUFBSUEsSUFBSixFQUFVL0UsR0FBRyxDQUFDdUcsSUFBSixDQUFTeEIsSUFBVDtBQUNWLE1BQUl4QixFQUFKLEVBQVF2RCxHQUFHLENBQUMvRCxHQUFKLENBQVFzSCxFQUFSO0FBQ1IsU0FBT3ZELEdBQVA7QUFDRCxDQVZEO0FBWUE7Ozs7Ozs7Ozs7O0FBVUE1RCxPQUFPLENBQUMwSyxJQUFSLEdBQWUsVUFBQy9LLEdBQUQsRUFBTWdKLElBQU4sRUFBWXhCLEVBQVosRUFBbUI7QUFDaEMsTUFBTXZELEdBQUcsR0FBRzVELE9BQU8sQ0FBQyxNQUFELEVBQVNMLEdBQVQsQ0FBbkI7O0FBQ0EsTUFBSSxPQUFPZ0osSUFBUCxLQUFnQixVQUFwQixFQUFnQztBQUM5QnhCLElBQUFBLEVBQUUsR0FBR3dCLElBQUw7QUFDQUEsSUFBQUEsSUFBSSxHQUFHLElBQVA7QUFDRDs7QUFFRCxNQUFJQSxJQUFKLEVBQVUvRSxHQUFHLENBQUN1RyxJQUFKLENBQVN4QixJQUFUO0FBQ1YsTUFBSXhCLEVBQUosRUFBUXZELEdBQUcsQ0FBQy9ELEdBQUosQ0FBUXNILEVBQVI7QUFDUixTQUFPdkQsR0FBUDtBQUNELENBVkQ7QUFZQTs7Ozs7Ozs7Ozs7QUFVQTVELE9BQU8sQ0FBQzJLLEdBQVIsR0FBYyxVQUFDaEwsR0FBRCxFQUFNZ0osSUFBTixFQUFZeEIsRUFBWixFQUFtQjtBQUMvQixNQUFNdkQsR0FBRyxHQUFHNUQsT0FBTyxDQUFDLEtBQUQsRUFBUUwsR0FBUixDQUFuQjs7QUFDQSxNQUFJLE9BQU9nSixJQUFQLEtBQWdCLFVBQXBCLEVBQWdDO0FBQzlCeEIsSUFBQUEsRUFBRSxHQUFHd0IsSUFBTDtBQUNBQSxJQUFBQSxJQUFJLEdBQUcsSUFBUDtBQUNEOztBQUVELE1BQUlBLElBQUosRUFBVS9FLEdBQUcsQ0FBQ3VHLElBQUosQ0FBU3hCLElBQVQ7QUFDVixNQUFJeEIsRUFBSixFQUFRdkQsR0FBRyxDQUFDL0QsR0FBSixDQUFRc0gsRUFBUjtBQUNSLFNBQU92RCxHQUFQO0FBQ0QsQ0FWRCIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogUm9vdCByZWZlcmVuY2UgZm9yIGlmcmFtZXMuXG4gKi9cblxubGV0IHJvb3Q7XG5pZiAodHlwZW9mIHdpbmRvdyAhPT0gJ3VuZGVmaW5lZCcpIHtcbiAgLy8gQnJvd3NlciB3aW5kb3dcbiAgcm9vdCA9IHdpbmRvdztcbn0gZWxzZSBpZiAodHlwZW9mIHNlbGYgPT09ICd1bmRlZmluZWQnKSB7XG4gIC8vIE90aGVyIGVudmlyb25tZW50c1xuICBjb25zb2xlLndhcm4oXG4gICAgJ1VzaW5nIGJyb3dzZXItb25seSB2ZXJzaW9uIG9mIHN1cGVyYWdlbnQgaW4gbm9uLWJyb3dzZXIgZW52aXJvbm1lbnQnXG4gICk7XG4gIHJvb3QgPSB0aGlzO1xufSBlbHNlIHtcbiAgLy8gV2ViIFdvcmtlclxuICByb290ID0gc2VsZjtcbn1cblxuY29uc3QgRW1pdHRlciA9IHJlcXVpcmUoJ2NvbXBvbmVudC1lbWl0dGVyJyk7XG5jb25zdCBzYWZlU3RyaW5naWZ5ID0gcmVxdWlyZSgnZmFzdC1zYWZlLXN0cmluZ2lmeScpO1xuY29uc3QgUmVxdWVzdEJhc2UgPSByZXF1aXJlKCcuL3JlcXVlc3QtYmFzZScpO1xuY29uc3QgaXNPYmplY3QgPSByZXF1aXJlKCcuL2lzLW9iamVjdCcpO1xuY29uc3QgUmVzcG9uc2VCYXNlID0gcmVxdWlyZSgnLi9yZXNwb25zZS1iYXNlJyk7XG5jb25zdCBBZ2VudCA9IHJlcXVpcmUoJy4vYWdlbnQtYmFzZScpO1xuXG4vKipcbiAqIE5vb3AuXG4gKi9cblxuZnVuY3Rpb24gbm9vcCgpIHt9XG5cbi8qKlxuICogRXhwb3NlIGByZXF1ZXN0YC5cbiAqL1xuXG5tb2R1bGUuZXhwb3J0cyA9IGZ1bmN0aW9uKG1ldGhvZCwgdXJsKSB7XG4gIC8vIGNhbGxiYWNrXG4gIGlmICh0eXBlb2YgdXJsID09PSAnZnVuY3Rpb24nKSB7XG4gICAgcmV0dXJuIG5ldyBleHBvcnRzLlJlcXVlc3QoJ0dFVCcsIG1ldGhvZCkuZW5kKHVybCk7XG4gIH1cblxuICAvLyB1cmwgZmlyc3RcbiAgaWYgKGFyZ3VtZW50cy5sZW5ndGggPT09IDEpIHtcbiAgICByZXR1cm4gbmV3IGV4cG9ydHMuUmVxdWVzdCgnR0VUJywgbWV0aG9kKTtcbiAgfVxuXG4gIHJldHVybiBuZXcgZXhwb3J0cy5SZXF1ZXN0KG1ldGhvZCwgdXJsKTtcbn07XG5cbmV4cG9ydHMgPSBtb2R1bGUuZXhwb3J0cztcblxuY29uc3QgcmVxdWVzdCA9IGV4cG9ydHM7XG5cbmV4cG9ydHMuUmVxdWVzdCA9IFJlcXVlc3Q7XG5cbi8qKlxuICogRGV0ZXJtaW5lIFhIUi5cbiAqL1xuXG5yZXF1ZXN0LmdldFhIUiA9ICgpID0+IHtcbiAgaWYgKFxuICAgIHJvb3QuWE1MSHR0cFJlcXVlc3QgJiZcbiAgICAoIXJvb3QubG9jYXRpb24gfHxcbiAgICAgIHJvb3QubG9jYXRpb24ucHJvdG9jb2wgIT09ICdmaWxlOicgfHxcbiAgICAgICFyb290LkFjdGl2ZVhPYmplY3QpXG4gICkge1xuICAgIHJldHVybiBuZXcgWE1MSHR0cFJlcXVlc3QoKTtcbiAgfVxuXG4gIHRyeSB7XG4gICAgcmV0dXJuIG5ldyBBY3RpdmVYT2JqZWN0KCdNaWNyb3NvZnQuWE1MSFRUUCcpO1xuICB9IGNhdGNoIHt9XG5cbiAgdHJ5IHtcbiAgICByZXR1cm4gbmV3IEFjdGl2ZVhPYmplY3QoJ01zeG1sMi5YTUxIVFRQLjYuMCcpO1xuICB9IGNhdGNoIHt9XG5cbiAgdHJ5IHtcbiAgICByZXR1cm4gbmV3IEFjdGl2ZVhPYmplY3QoJ01zeG1sMi5YTUxIVFRQLjMuMCcpO1xuICB9IGNhdGNoIHt9XG5cbiAgdHJ5IHtcbiAgICByZXR1cm4gbmV3IEFjdGl2ZVhPYmplY3QoJ01zeG1sMi5YTUxIVFRQJyk7XG4gIH0gY2F0Y2gge31cblxuICB0aHJvdyBuZXcgRXJyb3IoJ0Jyb3dzZXItb25seSB2ZXJzaW9uIG9mIHN1cGVyYWdlbnQgY291bGQgbm90IGZpbmQgWEhSJyk7XG59O1xuXG4vKipcbiAqIFJlbW92ZXMgbGVhZGluZyBhbmQgdHJhaWxpbmcgd2hpdGVzcGFjZSwgYWRkZWQgdG8gc3VwcG9ydCBJRS5cbiAqXG4gKiBAcGFyYW0ge1N0cmluZ30gc1xuICogQHJldHVybiB7U3RyaW5nfVxuICogQGFwaSBwcml2YXRlXG4gKi9cblxuY29uc3QgdHJpbSA9ICcnLnRyaW0gPyBzID0+IHMudHJpbSgpIDogcyA9PiBzLnJlcGxhY2UoLyheXFxzKnxcXHMqJCkvZywgJycpO1xuXG4vKipcbiAqIFNlcmlhbGl6ZSB0aGUgZ2l2ZW4gYG9iamAuXG4gKlxuICogQHBhcmFtIHtPYmplY3R9IG9ialxuICogQHJldHVybiB7U3RyaW5nfVxuICogQGFwaSBwcml2YXRlXG4gKi9cblxuZnVuY3Rpb24gc2VyaWFsaXplKG9iaikge1xuICBpZiAoIWlzT2JqZWN0KG9iaikpIHJldHVybiBvYmo7XG4gIGNvbnN0IHBhaXJzID0gW107XG4gIGZvciAoY29uc3Qga2V5IGluIG9iaikge1xuICAgIGlmIChPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwob2JqLCBrZXkpKVxuICAgICAgcHVzaEVuY29kZWRLZXlWYWx1ZVBhaXIocGFpcnMsIGtleSwgb2JqW2tleV0pO1xuICB9XG5cbiAgcmV0dXJuIHBhaXJzLmpvaW4oJyYnKTtcbn1cblxuLyoqXG4gKiBIZWxwcyAnc2VyaWFsaXplJyB3aXRoIHNlcmlhbGl6aW5nIGFycmF5cy5cbiAqIE11dGF0ZXMgdGhlIHBhaXJzIGFycmF5LlxuICpcbiAqIEBwYXJhbSB7QXJyYXl9IHBhaXJzXG4gKiBAcGFyYW0ge1N0cmluZ30ga2V5XG4gKiBAcGFyYW0ge01peGVkfSB2YWxcbiAqL1xuXG5mdW5jdGlvbiBwdXNoRW5jb2RlZEtleVZhbHVlUGFpcihwYWlycywga2V5LCB2YWwpIHtcbiAgaWYgKHZhbCA9PT0gdW5kZWZpbmVkKSByZXR1cm47XG4gIGlmICh2YWwgPT09IG51bGwpIHtcbiAgICBwYWlycy5wdXNoKGVuY29kZVVSSShrZXkpKTtcbiAgICByZXR1cm47XG4gIH1cblxuICBpZiAoQXJyYXkuaXNBcnJheSh2YWwpKSB7XG4gICAgdmFsLmZvckVhY2godiA9PiB7XG4gICAgICBwdXNoRW5jb2RlZEtleVZhbHVlUGFpcihwYWlycywga2V5LCB2KTtcbiAgICB9KTtcbiAgfSBlbHNlIGlmIChpc09iamVjdCh2YWwpKSB7XG4gICAgZm9yIChjb25zdCBzdWJrZXkgaW4gdmFsKSB7XG4gICAgICBpZiAoT2JqZWN0LnByb3RvdHlwZS5oYXNPd25Qcm9wZXJ0eS5jYWxsKHZhbCwgc3Via2V5KSlcbiAgICAgICAgcHVzaEVuY29kZWRLZXlWYWx1ZVBhaXIocGFpcnMsIGAke2tleX1bJHtzdWJrZXl9XWAsIHZhbFtzdWJrZXldKTtcbiAgICB9XG4gIH0gZWxzZSB7XG4gICAgcGFpcnMucHVzaChlbmNvZGVVUkkoa2V5KSArICc9JyArIGVuY29kZVVSSUNvbXBvbmVudCh2YWwpKTtcbiAgfVxufVxuXG4vKipcbiAqIEV4cG9zZSBzZXJpYWxpemF0aW9uIG1ldGhvZC5cbiAqL1xuXG5yZXF1ZXN0LnNlcmlhbGl6ZU9iamVjdCA9IHNlcmlhbGl6ZTtcblxuLyoqXG4gKiBQYXJzZSB0aGUgZ2l2ZW4geC13d3ctZm9ybS11cmxlbmNvZGVkIGBzdHJgLlxuICpcbiAqIEBwYXJhbSB7U3RyaW5nfSBzdHJcbiAqIEByZXR1cm4ge09iamVjdH1cbiAqIEBhcGkgcHJpdmF0ZVxuICovXG5cbmZ1bmN0aW9uIHBhcnNlU3RyaW5nKHN0cikge1xuICBjb25zdCBvYmogPSB7fTtcbiAgY29uc3QgcGFpcnMgPSBzdHIuc3BsaXQoJyYnKTtcbiAgbGV0IHBhaXI7XG4gIGxldCBwb3M7XG5cbiAgZm9yIChsZXQgaSA9IDAsIGxlbiA9IHBhaXJzLmxlbmd0aDsgaSA8IGxlbjsgKytpKSB7XG4gICAgcGFpciA9IHBhaXJzW2ldO1xuICAgIHBvcyA9IHBhaXIuaW5kZXhPZignPScpO1xuICAgIGlmIChwb3MgPT09IC0xKSB7XG4gICAgICBvYmpbZGVjb2RlVVJJQ29tcG9uZW50KHBhaXIpXSA9ICcnO1xuICAgIH0gZWxzZSB7XG4gICAgICBvYmpbZGVjb2RlVVJJQ29tcG9uZW50KHBhaXIuc2xpY2UoMCwgcG9zKSldID0gZGVjb2RlVVJJQ29tcG9uZW50KFxuICAgICAgICBwYWlyLnNsaWNlKHBvcyArIDEpXG4gICAgICApO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiBvYmo7XG59XG5cbi8qKlxuICogRXhwb3NlIHBhcnNlci5cbiAqL1xuXG5yZXF1ZXN0LnBhcnNlU3RyaW5nID0gcGFyc2VTdHJpbmc7XG5cbi8qKlxuICogRGVmYXVsdCBNSU1FIHR5cGUgbWFwLlxuICpcbiAqICAgICBzdXBlcmFnZW50LnR5cGVzLnhtbCA9ICdhcHBsaWNhdGlvbi94bWwnO1xuICpcbiAqL1xuXG5yZXF1ZXN0LnR5cGVzID0ge1xuICBodG1sOiAndGV4dC9odG1sJyxcbiAganNvbjogJ2FwcGxpY2F0aW9uL2pzb24nLFxuICB4bWw6ICd0ZXh0L3htbCcsXG4gIHVybGVuY29kZWQ6ICdhcHBsaWNhdGlvbi94LXd3dy1mb3JtLXVybGVuY29kZWQnLFxuICBmb3JtOiAnYXBwbGljYXRpb24veC13d3ctZm9ybS11cmxlbmNvZGVkJyxcbiAgJ2Zvcm0tZGF0YSc6ICdhcHBsaWNhdGlvbi94LXd3dy1mb3JtLXVybGVuY29kZWQnXG59O1xuXG4vKipcbiAqIERlZmF1bHQgc2VyaWFsaXphdGlvbiBtYXAuXG4gKlxuICogICAgIHN1cGVyYWdlbnQuc2VyaWFsaXplWydhcHBsaWNhdGlvbi94bWwnXSA9IGZ1bmN0aW9uKG9iail7XG4gKiAgICAgICByZXR1cm4gJ2dlbmVyYXRlZCB4bWwgaGVyZSc7XG4gKiAgICAgfTtcbiAqXG4gKi9cblxucmVxdWVzdC5zZXJpYWxpemUgPSB7XG4gICdhcHBsaWNhdGlvbi94LXd3dy1mb3JtLXVybGVuY29kZWQnOiBzZXJpYWxpemUsXG4gICdhcHBsaWNhdGlvbi9qc29uJzogc2FmZVN0cmluZ2lmeVxufTtcblxuLyoqXG4gKiBEZWZhdWx0IHBhcnNlcnMuXG4gKlxuICogICAgIHN1cGVyYWdlbnQucGFyc2VbJ2FwcGxpY2F0aW9uL3htbCddID0gZnVuY3Rpb24oc3RyKXtcbiAqICAgICAgIHJldHVybiB7IG9iamVjdCBwYXJzZWQgZnJvbSBzdHIgfTtcbiAqICAgICB9O1xuICpcbiAqL1xuXG5yZXF1ZXN0LnBhcnNlID0ge1xuICAnYXBwbGljYXRpb24veC13d3ctZm9ybS11cmxlbmNvZGVkJzogcGFyc2VTdHJpbmcsXG4gICdhcHBsaWNhdGlvbi9qc29uJzogSlNPTi5wYXJzZVxufTtcblxuLyoqXG4gKiBQYXJzZSB0aGUgZ2l2ZW4gaGVhZGVyIGBzdHJgIGludG9cbiAqIGFuIG9iamVjdCBjb250YWluaW5nIHRoZSBtYXBwZWQgZmllbGRzLlxuICpcbiAqIEBwYXJhbSB7U3RyaW5nfSBzdHJcbiAqIEByZXR1cm4ge09iamVjdH1cbiAqIEBhcGkgcHJpdmF0ZVxuICovXG5cbmZ1bmN0aW9uIHBhcnNlSGVhZGVyKHN0cikge1xuICBjb25zdCBsaW5lcyA9IHN0ci5zcGxpdCgvXFxyP1xcbi8pO1xuICBjb25zdCBmaWVsZHMgPSB7fTtcbiAgbGV0IGluZGV4O1xuICBsZXQgbGluZTtcbiAgbGV0IGZpZWxkO1xuICBsZXQgdmFsO1xuXG4gIGZvciAobGV0IGkgPSAwLCBsZW4gPSBsaW5lcy5sZW5ndGg7IGkgPCBsZW47ICsraSkge1xuICAgIGxpbmUgPSBsaW5lc1tpXTtcbiAgICBpbmRleCA9IGxpbmUuaW5kZXhPZignOicpO1xuICAgIGlmIChpbmRleCA9PT0gLTEpIHtcbiAgICAgIC8vIGNvdWxkIGJlIGVtcHR5IGxpbmUsIGp1c3Qgc2tpcCBpdFxuICAgICAgY29udGludWU7XG4gICAgfVxuXG4gICAgZmllbGQgPSBsaW5lLnNsaWNlKDAsIGluZGV4KS50b0xvd2VyQ2FzZSgpO1xuICAgIHZhbCA9IHRyaW0obGluZS5zbGljZShpbmRleCArIDEpKTtcbiAgICBmaWVsZHNbZmllbGRdID0gdmFsO1xuICB9XG5cbiAgcmV0dXJuIGZpZWxkcztcbn1cblxuLyoqXG4gKiBDaGVjayBpZiBgbWltZWAgaXMganNvbiBvciBoYXMgK2pzb24gc3RydWN0dXJlZCBzeW50YXggc3VmZml4LlxuICpcbiAqIEBwYXJhbSB7U3RyaW5nfSBtaW1lXG4gKiBAcmV0dXJuIHtCb29sZWFufVxuICogQGFwaSBwcml2YXRlXG4gKi9cblxuZnVuY3Rpb24gaXNKU09OKG1pbWUpIHtcbiAgLy8gc2hvdWxkIG1hdGNoIC9qc29uIG9yICtqc29uXG4gIC8vIGJ1dCBub3QgL2pzb24tc2VxXG4gIHJldHVybiAvWy8rXWpzb24oJHxbXi1cXHddKS8udGVzdChtaW1lKTtcbn1cblxuLyoqXG4gKiBJbml0aWFsaXplIGEgbmV3IGBSZXNwb25zZWAgd2l0aCB0aGUgZ2l2ZW4gYHhocmAuXG4gKlxuICogIC0gc2V0IGZsYWdzICgub2ssIC5lcnJvciwgZXRjKVxuICogIC0gcGFyc2UgaGVhZGVyXG4gKlxuICogRXhhbXBsZXM6XG4gKlxuICogIEFsaWFzaW5nIGBzdXBlcmFnZW50YCBhcyBgcmVxdWVzdGAgaXMgbmljZTpcbiAqXG4gKiAgICAgIHJlcXVlc3QgPSBzdXBlcmFnZW50O1xuICpcbiAqICBXZSBjYW4gdXNlIHRoZSBwcm9taXNlLWxpa2UgQVBJLCBvciBwYXNzIGNhbGxiYWNrczpcbiAqXG4gKiAgICAgIHJlcXVlc3QuZ2V0KCcvJykuZW5kKGZ1bmN0aW9uKHJlcyl7fSk7XG4gKiAgICAgIHJlcXVlc3QuZ2V0KCcvJywgZnVuY3Rpb24ocmVzKXt9KTtcbiAqXG4gKiAgU2VuZGluZyBkYXRhIGNhbiBiZSBjaGFpbmVkOlxuICpcbiAqICAgICAgcmVxdWVzdFxuICogICAgICAgIC5wb3N0KCcvdXNlcicpXG4gKiAgICAgICAgLnNlbmQoeyBuYW1lOiAndGonIH0pXG4gKiAgICAgICAgLmVuZChmdW5jdGlvbihyZXMpe30pO1xuICpcbiAqICBPciBwYXNzZWQgdG8gYC5zZW5kKClgOlxuICpcbiAqICAgICAgcmVxdWVzdFxuICogICAgICAgIC5wb3N0KCcvdXNlcicpXG4gKiAgICAgICAgLnNlbmQoeyBuYW1lOiAndGonIH0sIGZ1bmN0aW9uKHJlcyl7fSk7XG4gKlxuICogIE9yIHBhc3NlZCB0byBgLnBvc3QoKWA6XG4gKlxuICogICAgICByZXF1ZXN0XG4gKiAgICAgICAgLnBvc3QoJy91c2VyJywgeyBuYW1lOiAndGonIH0pXG4gKiAgICAgICAgLmVuZChmdW5jdGlvbihyZXMpe30pO1xuICpcbiAqIE9yIGZ1cnRoZXIgcmVkdWNlZCB0byBhIHNpbmdsZSBjYWxsIGZvciBzaW1wbGUgY2FzZXM6XG4gKlxuICogICAgICByZXF1ZXN0XG4gKiAgICAgICAgLnBvc3QoJy91c2VyJywgeyBuYW1lOiAndGonIH0sIGZ1bmN0aW9uKHJlcyl7fSk7XG4gKlxuICogQHBhcmFtIHtYTUxIVFRQUmVxdWVzdH0geGhyXG4gKiBAcGFyYW0ge09iamVjdH0gb3B0aW9uc1xuICogQGFwaSBwcml2YXRlXG4gKi9cblxuZnVuY3Rpb24gUmVzcG9uc2UocmVxKSB7XG4gIHRoaXMucmVxID0gcmVxO1xuICB0aGlzLnhociA9IHRoaXMucmVxLnhocjtcbiAgLy8gcmVzcG9uc2VUZXh0IGlzIGFjY2Vzc2libGUgb25seSBpZiByZXNwb25zZVR5cGUgaXMgJycgb3IgJ3RleHQnIGFuZCBvbiBvbGRlciBicm93c2Vyc1xuICB0aGlzLnRleHQgPVxuICAgICh0aGlzLnJlcS5tZXRob2QgIT09ICdIRUFEJyAmJlxuICAgICAgKHRoaXMueGhyLnJlc3BvbnNlVHlwZSA9PT0gJycgfHwgdGhpcy54aHIucmVzcG9uc2VUeXBlID09PSAndGV4dCcpKSB8fFxuICAgIHR5cGVvZiB0aGlzLnhoci5yZXNwb25zZVR5cGUgPT09ICd1bmRlZmluZWQnXG4gICAgICA/IHRoaXMueGhyLnJlc3BvbnNlVGV4dFxuICAgICAgOiBudWxsO1xuICB0aGlzLnN0YXR1c1RleHQgPSB0aGlzLnJlcS54aHIuc3RhdHVzVGV4dDtcbiAgbGV0IHsgc3RhdHVzIH0gPSB0aGlzLnhocjtcbiAgLy8gaGFuZGxlIElFOSBidWc6IGh0dHA6Ly9zdGFja292ZXJmbG93LmNvbS9xdWVzdGlvbnMvMTAwNDY5NzIvbXNpZS1yZXR1cm5zLXN0YXR1cy1jb2RlLW9mLTEyMjMtZm9yLWFqYXgtcmVxdWVzdFxuICBpZiAoc3RhdHVzID09PSAxMjIzKSB7XG4gICAgc3RhdHVzID0gMjA0O1xuICB9XG5cbiAgdGhpcy5fc2V0U3RhdHVzUHJvcGVydGllcyhzdGF0dXMpO1xuICB0aGlzLmhlYWRlcnMgPSBwYXJzZUhlYWRlcih0aGlzLnhoci5nZXRBbGxSZXNwb25zZUhlYWRlcnMoKSk7XG4gIHRoaXMuaGVhZGVyID0gdGhpcy5oZWFkZXJzO1xuICAvLyBnZXRBbGxSZXNwb25zZUhlYWRlcnMgc29tZXRpbWVzIGZhbHNlbHkgcmV0dXJucyBcIlwiIGZvciBDT1JTIHJlcXVlc3RzLCBidXRcbiAgLy8gZ2V0UmVzcG9uc2VIZWFkZXIgc3RpbGwgd29ya3MuIHNvIHdlIGdldCBjb250ZW50LXR5cGUgZXZlbiBpZiBnZXR0aW5nXG4gIC8vIG90aGVyIGhlYWRlcnMgZmFpbHMuXG4gIHRoaXMuaGVhZGVyWydjb250ZW50LXR5cGUnXSA9IHRoaXMueGhyLmdldFJlc3BvbnNlSGVhZGVyKCdjb250ZW50LXR5cGUnKTtcbiAgdGhpcy5fc2V0SGVhZGVyUHJvcGVydGllcyh0aGlzLmhlYWRlcik7XG5cbiAgaWYgKHRoaXMudGV4dCA9PT0gbnVsbCAmJiByZXEuX3Jlc3BvbnNlVHlwZSkge1xuICAgIHRoaXMuYm9keSA9IHRoaXMueGhyLnJlc3BvbnNlO1xuICB9IGVsc2Uge1xuICAgIHRoaXMuYm9keSA9XG4gICAgICB0aGlzLnJlcS5tZXRob2QgPT09ICdIRUFEJ1xuICAgICAgICA/IG51bGxcbiAgICAgICAgOiB0aGlzLl9wYXJzZUJvZHkodGhpcy50ZXh0ID8gdGhpcy50ZXh0IDogdGhpcy54aHIucmVzcG9uc2UpO1xuICB9XG59XG5cbi8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBuZXctY2FwXG5SZXNwb25zZUJhc2UoUmVzcG9uc2UucHJvdG90eXBlKTtcblxuLyoqXG4gKiBQYXJzZSB0aGUgZ2l2ZW4gYm9keSBgc3RyYC5cbiAqXG4gKiBVc2VkIGZvciBhdXRvLXBhcnNpbmcgb2YgYm9kaWVzLiBQYXJzZXJzXG4gKiBhcmUgZGVmaW5lZCBvbiB0aGUgYHN1cGVyYWdlbnQucGFyc2VgIG9iamVjdC5cbiAqXG4gKiBAcGFyYW0ge1N0cmluZ30gc3RyXG4gKiBAcmV0dXJuIHtNaXhlZH1cbiAqIEBhcGkgcHJpdmF0ZVxuICovXG5cblJlc3BvbnNlLnByb3RvdHlwZS5fcGFyc2VCb2R5ID0gZnVuY3Rpb24oc3RyKSB7XG4gIGxldCBwYXJzZSA9IHJlcXVlc3QucGFyc2VbdGhpcy50eXBlXTtcbiAgaWYgKHRoaXMucmVxLl9wYXJzZXIpIHtcbiAgICByZXR1cm4gdGhpcy5yZXEuX3BhcnNlcih0aGlzLCBzdHIpO1xuICB9XG5cbiAgaWYgKCFwYXJzZSAmJiBpc0pTT04odGhpcy50eXBlKSkge1xuICAgIHBhcnNlID0gcmVxdWVzdC5wYXJzZVsnYXBwbGljYXRpb24vanNvbiddO1xuICB9XG5cbiAgcmV0dXJuIHBhcnNlICYmIHN0ciAmJiAoc3RyLmxlbmd0aCA+IDAgfHwgc3RyIGluc3RhbmNlb2YgT2JqZWN0KVxuICAgID8gcGFyc2Uoc3RyKVxuICAgIDogbnVsbDtcbn07XG5cbi8qKlxuICogUmV0dXJuIGFuIGBFcnJvcmAgcmVwcmVzZW50YXRpdmUgb2YgdGhpcyByZXNwb25zZS5cbiAqXG4gKiBAcmV0dXJuIHtFcnJvcn1cbiAqIEBhcGkgcHVibGljXG4gKi9cblxuUmVzcG9uc2UucHJvdG90eXBlLnRvRXJyb3IgPSBmdW5jdGlvbigpIHtcbiAgY29uc3QgeyByZXEgfSA9IHRoaXM7XG4gIGNvbnN0IHsgbWV0aG9kIH0gPSByZXE7XG4gIGNvbnN0IHsgdXJsIH0gPSByZXE7XG5cbiAgY29uc3QgbXNnID0gYGNhbm5vdCAke21ldGhvZH0gJHt1cmx9ICgke3RoaXMuc3RhdHVzfSlgO1xuICBjb25zdCBlcnIgPSBuZXcgRXJyb3IobXNnKTtcbiAgZXJyLnN0YXR1cyA9IHRoaXMuc3RhdHVzO1xuICBlcnIubWV0aG9kID0gbWV0aG9kO1xuICBlcnIudXJsID0gdXJsO1xuXG4gIHJldHVybiBlcnI7XG59O1xuXG4vKipcbiAqIEV4cG9zZSBgUmVzcG9uc2VgLlxuICovXG5cbnJlcXVlc3QuUmVzcG9uc2UgPSBSZXNwb25zZTtcblxuLyoqXG4gKiBJbml0aWFsaXplIGEgbmV3IGBSZXF1ZXN0YCB3aXRoIHRoZSBnaXZlbiBgbWV0aG9kYCBhbmQgYHVybGAuXG4gKlxuICogQHBhcmFtIHtTdHJpbmd9IG1ldGhvZFxuICogQHBhcmFtIHtTdHJpbmd9IHVybFxuICogQGFwaSBwdWJsaWNcbiAqL1xuXG5mdW5jdGlvbiBSZXF1ZXN0KG1ldGhvZCwgdXJsKSB7XG4gIGNvbnN0IHNlbGYgPSB0aGlzO1xuICB0aGlzLl9xdWVyeSA9IHRoaXMuX3F1ZXJ5IHx8IFtdO1xuICB0aGlzLm1ldGhvZCA9IG1ldGhvZDtcbiAgdGhpcy51cmwgPSB1cmw7XG4gIHRoaXMuaGVhZGVyID0ge307IC8vIHByZXNlcnZlcyBoZWFkZXIgbmFtZSBjYXNlXG4gIHRoaXMuX2hlYWRlciA9IHt9OyAvLyBjb2VyY2VzIGhlYWRlciBuYW1lcyB0byBsb3dlcmNhc2VcbiAgdGhpcy5vbignZW5kJywgKCkgPT4ge1xuICAgIGxldCBlcnIgPSBudWxsO1xuICAgIGxldCByZXMgPSBudWxsO1xuXG4gICAgdHJ5IHtcbiAgICAgIHJlcyA9IG5ldyBSZXNwb25zZShzZWxmKTtcbiAgICB9IGNhdGNoIChlcnJfKSB7XG4gICAgICBlcnIgPSBuZXcgRXJyb3IoJ1BhcnNlciBpcyB1bmFibGUgdG8gcGFyc2UgdGhlIHJlc3BvbnNlJyk7XG4gICAgICBlcnIucGFyc2UgPSB0cnVlO1xuICAgICAgZXJyLm9yaWdpbmFsID0gZXJyXztcbiAgICAgIC8vIGlzc3VlICM2NzU6IHJldHVybiB0aGUgcmF3IHJlc3BvbnNlIGlmIHRoZSByZXNwb25zZSBwYXJzaW5nIGZhaWxzXG4gICAgICBpZiAoc2VsZi54aHIpIHtcbiAgICAgICAgLy8gaWU5IGRvZXNuJ3QgaGF2ZSAncmVzcG9uc2UnIHByb3BlcnR5XG4gICAgICAgIGVyci5yYXdSZXNwb25zZSA9XG4gICAgICAgICAgdHlwZW9mIHNlbGYueGhyLnJlc3BvbnNlVHlwZSA9PT0gJ3VuZGVmaW5lZCdcbiAgICAgICAgICAgID8gc2VsZi54aHIucmVzcG9uc2VUZXh0XG4gICAgICAgICAgICA6IHNlbGYueGhyLnJlc3BvbnNlO1xuICAgICAgICAvLyBpc3N1ZSAjODc2OiByZXR1cm4gdGhlIGh0dHAgc3RhdHVzIGNvZGUgaWYgdGhlIHJlc3BvbnNlIHBhcnNpbmcgZmFpbHNcbiAgICAgICAgZXJyLnN0YXR1cyA9IHNlbGYueGhyLnN0YXR1cyA/IHNlbGYueGhyLnN0YXR1cyA6IG51bGw7XG4gICAgICAgIGVyci5zdGF0dXNDb2RlID0gZXJyLnN0YXR1czsgLy8gYmFja3dhcmRzLWNvbXBhdCBvbmx5XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBlcnIucmF3UmVzcG9uc2UgPSBudWxsO1xuICAgICAgICBlcnIuc3RhdHVzID0gbnVsbDtcbiAgICAgIH1cblxuICAgICAgcmV0dXJuIHNlbGYuY2FsbGJhY2soZXJyKTtcbiAgICB9XG5cbiAgICBzZWxmLmVtaXQoJ3Jlc3BvbnNlJywgcmVzKTtcblxuICAgIGxldCBuZXdfZXJyO1xuICAgIHRyeSB7XG4gICAgICBpZiAoIXNlbGYuX2lzUmVzcG9uc2VPSyhyZXMpKSB7XG4gICAgICAgIG5ld19lcnIgPSBuZXcgRXJyb3IoXG4gICAgICAgICAgcmVzLnN0YXR1c1RleHQgfHwgcmVzLnRleHQgfHwgJ1Vuc3VjY2Vzc2Z1bCBIVFRQIHJlc3BvbnNlJ1xuICAgICAgICApO1xuICAgICAgfVxuICAgIH0gY2F0Y2ggKGVycl8pIHtcbiAgICAgIG5ld19lcnIgPSBlcnJfOyAvLyBvaygpIGNhbGxiYWNrIGNhbiB0aHJvd1xuICAgIH1cblxuICAgIC8vICMxMDAwIGRvbid0IGNhdGNoIGVycm9ycyBmcm9tIHRoZSBjYWxsYmFjayB0byBhdm9pZCBkb3VibGUgY2FsbGluZyBpdFxuICAgIGlmIChuZXdfZXJyKSB7XG4gICAgICBuZXdfZXJyLm9yaWdpbmFsID0gZXJyO1xuICAgICAgbmV3X2Vyci5yZXNwb25zZSA9IHJlcztcbiAgICAgIG5ld19lcnIuc3RhdHVzID0gcmVzLnN0YXR1cztcbiAgICAgIHNlbGYuY2FsbGJhY2sobmV3X2VyciwgcmVzKTtcbiAgICB9IGVsc2Uge1xuICAgICAgc2VsZi5jYWxsYmFjayhudWxsLCByZXMpO1xuICAgIH1cbiAgfSk7XG59XG5cbi8qKlxuICogTWl4aW4gYEVtaXR0ZXJgIGFuZCBgUmVxdWVzdEJhc2VgLlxuICovXG5cbi8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBuZXctY2FwXG5FbWl0dGVyKFJlcXVlc3QucHJvdG90eXBlKTtcbi8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBuZXctY2FwXG5SZXF1ZXN0QmFzZShSZXF1ZXN0LnByb3RvdHlwZSk7XG5cbi8qKlxuICogU2V0IENvbnRlbnQtVHlwZSB0byBgdHlwZWAsIG1hcHBpbmcgdmFsdWVzIGZyb20gYHJlcXVlc3QudHlwZXNgLlxuICpcbiAqIEV4YW1wbGVzOlxuICpcbiAqICAgICAgc3VwZXJhZ2VudC50eXBlcy54bWwgPSAnYXBwbGljYXRpb24veG1sJztcbiAqXG4gKiAgICAgIHJlcXVlc3QucG9zdCgnLycpXG4gKiAgICAgICAgLnR5cGUoJ3htbCcpXG4gKiAgICAgICAgLnNlbmQoeG1sc3RyaW5nKVxuICogICAgICAgIC5lbmQoY2FsbGJhY2spO1xuICpcbiAqICAgICAgcmVxdWVzdC5wb3N0KCcvJylcbiAqICAgICAgICAudHlwZSgnYXBwbGljYXRpb24veG1sJylcbiAqICAgICAgICAuc2VuZCh4bWxzdHJpbmcpXG4gKiAgICAgICAgLmVuZChjYWxsYmFjayk7XG4gKlxuICogQHBhcmFtIHtTdHJpbmd9IHR5cGVcbiAqIEByZXR1cm4ge1JlcXVlc3R9IGZvciBjaGFpbmluZ1xuICogQGFwaSBwdWJsaWNcbiAqL1xuXG5SZXF1ZXN0LnByb3RvdHlwZS50eXBlID0gZnVuY3Rpb24odHlwZSkge1xuICB0aGlzLnNldCgnQ29udGVudC1UeXBlJywgcmVxdWVzdC50eXBlc1t0eXBlXSB8fCB0eXBlKTtcbiAgcmV0dXJuIHRoaXM7XG59O1xuXG4vKipcbiAqIFNldCBBY2NlcHQgdG8gYHR5cGVgLCBtYXBwaW5nIHZhbHVlcyBmcm9tIGByZXF1ZXN0LnR5cGVzYC5cbiAqXG4gKiBFeGFtcGxlczpcbiAqXG4gKiAgICAgIHN1cGVyYWdlbnQudHlwZXMuanNvbiA9ICdhcHBsaWNhdGlvbi9qc29uJztcbiAqXG4gKiAgICAgIHJlcXVlc3QuZ2V0KCcvYWdlbnQnKVxuICogICAgICAgIC5hY2NlcHQoJ2pzb24nKVxuICogICAgICAgIC5lbmQoY2FsbGJhY2spO1xuICpcbiAqICAgICAgcmVxdWVzdC5nZXQoJy9hZ2VudCcpXG4gKiAgICAgICAgLmFjY2VwdCgnYXBwbGljYXRpb24vanNvbicpXG4gKiAgICAgICAgLmVuZChjYWxsYmFjayk7XG4gKlxuICogQHBhcmFtIHtTdHJpbmd9IGFjY2VwdFxuICogQHJldHVybiB7UmVxdWVzdH0gZm9yIGNoYWluaW5nXG4gKiBAYXBpIHB1YmxpY1xuICovXG5cblJlcXVlc3QucHJvdG90eXBlLmFjY2VwdCA9IGZ1bmN0aW9uKHR5cGUpIHtcbiAgdGhpcy5zZXQoJ0FjY2VwdCcsIHJlcXVlc3QudHlwZXNbdHlwZV0gfHwgdHlwZSk7XG4gIHJldHVybiB0aGlzO1xufTtcblxuLyoqXG4gKiBTZXQgQXV0aG9yaXphdGlvbiBmaWVsZCB2YWx1ZSB3aXRoIGB1c2VyYCBhbmQgYHBhc3NgLlxuICpcbiAqIEBwYXJhbSB7U3RyaW5nfSB1c2VyXG4gKiBAcGFyYW0ge1N0cmluZ30gW3Bhc3NdIG9wdGlvbmFsIGluIGNhc2Ugb2YgdXNpbmcgJ2JlYXJlcicgYXMgdHlwZVxuICogQHBhcmFtIHtPYmplY3R9IG9wdGlvbnMgd2l0aCAndHlwZScgcHJvcGVydHkgJ2F1dG8nLCAnYmFzaWMnIG9yICdiZWFyZXInIChkZWZhdWx0ICdiYXNpYycpXG4gKiBAcmV0dXJuIHtSZXF1ZXN0fSBmb3IgY2hhaW5pbmdcbiAqIEBhcGkgcHVibGljXG4gKi9cblxuUmVxdWVzdC5wcm90b3R5cGUuYXV0aCA9IGZ1bmN0aW9uKHVzZXIsIHBhc3MsIG9wdGlvbnMpIHtcbiAgaWYgKGFyZ3VtZW50cy5sZW5ndGggPT09IDEpIHBhc3MgPSAnJztcbiAgaWYgKHR5cGVvZiBwYXNzID09PSAnb2JqZWN0JyAmJiBwYXNzICE9PSBudWxsKSB7XG4gICAgLy8gcGFzcyBpcyBvcHRpb25hbCBhbmQgY2FuIGJlIHJlcGxhY2VkIHdpdGggb3B0aW9uc1xuICAgIG9wdGlvbnMgPSBwYXNzO1xuICAgIHBhc3MgPSAnJztcbiAgfVxuXG4gIGlmICghb3B0aW9ucykge1xuICAgIG9wdGlvbnMgPSB7XG4gICAgICB0eXBlOiB0eXBlb2YgYnRvYSA9PT0gJ2Z1bmN0aW9uJyA/ICdiYXNpYycgOiAnYXV0bydcbiAgICB9O1xuICB9XG5cbiAgY29uc3QgZW5jb2RlciA9IHN0cmluZyA9PiB7XG4gICAgaWYgKHR5cGVvZiBidG9hID09PSAnZnVuY3Rpb24nKSB7XG4gICAgICByZXR1cm4gYnRvYShzdHJpbmcpO1xuICAgIH1cblxuICAgIHRocm93IG5ldyBFcnJvcignQ2Fubm90IHVzZSBiYXNpYyBhdXRoLCBidG9hIGlzIG5vdCBhIGZ1bmN0aW9uJyk7XG4gIH07XG5cbiAgcmV0dXJuIHRoaXMuX2F1dGgodXNlciwgcGFzcywgb3B0aW9ucywgZW5jb2Rlcik7XG59O1xuXG4vKipcbiAqIEFkZCBxdWVyeS1zdHJpbmcgYHZhbGAuXG4gKlxuICogRXhhbXBsZXM6XG4gKlxuICogICByZXF1ZXN0LmdldCgnL3Nob2VzJylcbiAqICAgICAucXVlcnkoJ3NpemU9MTAnKVxuICogICAgIC5xdWVyeSh7IGNvbG9yOiAnYmx1ZScgfSlcbiAqXG4gKiBAcGFyYW0ge09iamVjdHxTdHJpbmd9IHZhbFxuICogQHJldHVybiB7UmVxdWVzdH0gZm9yIGNoYWluaW5nXG4gKiBAYXBpIHB1YmxpY1xuICovXG5cblJlcXVlc3QucHJvdG90eXBlLnF1ZXJ5ID0gZnVuY3Rpb24odmFsKSB7XG4gIGlmICh0eXBlb2YgdmFsICE9PSAnc3RyaW5nJykgdmFsID0gc2VyaWFsaXplKHZhbCk7XG4gIGlmICh2YWwpIHRoaXMuX3F1ZXJ5LnB1c2godmFsKTtcbiAgcmV0dXJuIHRoaXM7XG59O1xuXG4vKipcbiAqIFF1ZXVlIHRoZSBnaXZlbiBgZmlsZWAgYXMgYW4gYXR0YWNobWVudCB0byB0aGUgc3BlY2lmaWVkIGBmaWVsZGAsXG4gKiB3aXRoIG9wdGlvbmFsIGBvcHRpb25zYCAob3IgZmlsZW5hbWUpLlxuICpcbiAqIGBgYCBqc1xuICogcmVxdWVzdC5wb3N0KCcvdXBsb2FkJylcbiAqICAgLmF0dGFjaCgnY29udGVudCcsIG5ldyBCbG9iKFsnPGEgaWQ9XCJhXCI+PGIgaWQ9XCJiXCI+aGV5ITwvYj48L2E+J10sIHsgdHlwZTogXCJ0ZXh0L2h0bWxcIn0pKVxuICogICAuZW5kKGNhbGxiYWNrKTtcbiAqIGBgYFxuICpcbiAqIEBwYXJhbSB7U3RyaW5nfSBmaWVsZFxuICogQHBhcmFtIHtCbG9ifEZpbGV9IGZpbGVcbiAqIEBwYXJhbSB7U3RyaW5nfE9iamVjdH0gb3B0aW9uc1xuICogQHJldHVybiB7UmVxdWVzdH0gZm9yIGNoYWluaW5nXG4gKiBAYXBpIHB1YmxpY1xuICovXG5cblJlcXVlc3QucHJvdG90eXBlLmF0dGFjaCA9IGZ1bmN0aW9uKGZpZWxkLCBmaWxlLCBvcHRpb25zKSB7XG4gIGlmIChmaWxlKSB7XG4gICAgaWYgKHRoaXMuX2RhdGEpIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcihcInN1cGVyYWdlbnQgY2FuJ3QgbWl4IC5zZW5kKCkgYW5kIC5hdHRhY2goKVwiKTtcbiAgICB9XG5cbiAgICB0aGlzLl9nZXRGb3JtRGF0YSgpLmFwcGVuZChmaWVsZCwgZmlsZSwgb3B0aW9ucyB8fCBmaWxlLm5hbWUpO1xuICB9XG5cbiAgcmV0dXJuIHRoaXM7XG59O1xuXG5SZXF1ZXN0LnByb3RvdHlwZS5fZ2V0Rm9ybURhdGEgPSBmdW5jdGlvbigpIHtcbiAgaWYgKCF0aGlzLl9mb3JtRGF0YSkge1xuICAgIHRoaXMuX2Zvcm1EYXRhID0gbmV3IHJvb3QuRm9ybURhdGEoKTtcbiAgfVxuXG4gIHJldHVybiB0aGlzLl9mb3JtRGF0YTtcbn07XG5cbi8qKlxuICogSW52b2tlIHRoZSBjYWxsYmFjayB3aXRoIGBlcnJgIGFuZCBgcmVzYFxuICogYW5kIGhhbmRsZSBhcml0eSBjaGVjay5cbiAqXG4gKiBAcGFyYW0ge0Vycm9yfSBlcnJcbiAqIEBwYXJhbSB7UmVzcG9uc2V9IHJlc1xuICogQGFwaSBwcml2YXRlXG4gKi9cblxuUmVxdWVzdC5wcm90b3R5cGUuY2FsbGJhY2sgPSBmdW5jdGlvbihlcnIsIHJlcykge1xuICBpZiAodGhpcy5fc2hvdWxkUmV0cnkoZXJyLCByZXMpKSB7XG4gICAgcmV0dXJuIHRoaXMuX3JldHJ5KCk7XG4gIH1cblxuICBjb25zdCBmbiA9IHRoaXMuX2NhbGxiYWNrO1xuICB0aGlzLmNsZWFyVGltZW91dCgpO1xuXG4gIGlmIChlcnIpIHtcbiAgICBpZiAodGhpcy5fbWF4UmV0cmllcykgZXJyLnJldHJpZXMgPSB0aGlzLl9yZXRyaWVzIC0gMTtcbiAgICB0aGlzLmVtaXQoJ2Vycm9yJywgZXJyKTtcbiAgfVxuXG4gIGZuKGVyciwgcmVzKTtcbn07XG5cbi8qKlxuICogSW52b2tlIGNhbGxiYWNrIHdpdGggeC1kb21haW4gZXJyb3IuXG4gKlxuICogQGFwaSBwcml2YXRlXG4gKi9cblxuUmVxdWVzdC5wcm90b3R5cGUuY3Jvc3NEb21haW5FcnJvciA9IGZ1bmN0aW9uKCkge1xuICBjb25zdCBlcnIgPSBuZXcgRXJyb3IoXG4gICAgJ1JlcXVlc3QgaGFzIGJlZW4gdGVybWluYXRlZFxcblBvc3NpYmxlIGNhdXNlczogdGhlIG5ldHdvcmsgaXMgb2ZmbGluZSwgT3JpZ2luIGlzIG5vdCBhbGxvd2VkIGJ5IEFjY2Vzcy1Db250cm9sLUFsbG93LU9yaWdpbiwgdGhlIHBhZ2UgaXMgYmVpbmcgdW5sb2FkZWQsIGV0Yy4nXG4gICk7XG4gIGVyci5jcm9zc0RvbWFpbiA9IHRydWU7XG5cbiAgZXJyLnN0YXR1cyA9IHRoaXMuc3RhdHVzO1xuICBlcnIubWV0aG9kID0gdGhpcy5tZXRob2Q7XG4gIGVyci51cmwgPSB0aGlzLnVybDtcblxuICB0aGlzLmNhbGxiYWNrKGVycik7XG59O1xuXG4vLyBUaGlzIG9ubHkgd2FybnMsIGJlY2F1c2UgdGhlIHJlcXVlc3QgaXMgc3RpbGwgbGlrZWx5IHRvIHdvcmtcblJlcXVlc3QucHJvdG90eXBlLmFnZW50ID0gZnVuY3Rpb24oKSB7XG4gIGNvbnNvbGUud2FybignVGhpcyBpcyBub3Qgc3VwcG9ydGVkIGluIGJyb3dzZXIgdmVyc2lvbiBvZiBzdXBlcmFnZW50Jyk7XG4gIHJldHVybiB0aGlzO1xufTtcblxuUmVxdWVzdC5wcm90b3R5cGUuY2EgPSBSZXF1ZXN0LnByb3RvdHlwZS5hZ2VudDtcblJlcXVlc3QucHJvdG90eXBlLmJ1ZmZlciA9IFJlcXVlc3QucHJvdG90eXBlLmNhO1xuXG4vLyBUaGlzIHRocm93cywgYmVjYXVzZSBpdCBjYW4ndCBzZW5kL3JlY2VpdmUgZGF0YSBhcyBleHBlY3RlZFxuUmVxdWVzdC5wcm90b3R5cGUud3JpdGUgPSAoKSA9PiB7XG4gIHRocm93IG5ldyBFcnJvcihcbiAgICAnU3RyZWFtaW5nIGlzIG5vdCBzdXBwb3J0ZWQgaW4gYnJvd3NlciB2ZXJzaW9uIG9mIHN1cGVyYWdlbnQnXG4gICk7XG59O1xuXG5SZXF1ZXN0LnByb3RvdHlwZS5waXBlID0gUmVxdWVzdC5wcm90b3R5cGUud3JpdGU7XG5cbi8qKlxuICogQ2hlY2sgaWYgYG9iamAgaXMgYSBob3N0IG9iamVjdCxcbiAqIHdlIGRvbid0IHdhbnQgdG8gc2VyaWFsaXplIHRoZXNlIDopXG4gKlxuICogQHBhcmFtIHtPYmplY3R9IG9iaiBob3N0IG9iamVjdFxuICogQHJldHVybiB7Qm9vbGVhbn0gaXMgYSBob3N0IG9iamVjdFxuICogQGFwaSBwcml2YXRlXG4gKi9cblJlcXVlc3QucHJvdG90eXBlLl9pc0hvc3QgPSBmdW5jdGlvbihvYmopIHtcbiAgLy8gTmF0aXZlIG9iamVjdHMgc3RyaW5naWZ5IHRvIFtvYmplY3QgRmlsZV0sIFtvYmplY3QgQmxvYl0sIFtvYmplY3QgRm9ybURhdGFdLCBldGMuXG4gIHJldHVybiAoXG4gICAgb2JqICYmXG4gICAgdHlwZW9mIG9iaiA9PT0gJ29iamVjdCcgJiZcbiAgICAhQXJyYXkuaXNBcnJheShvYmopICYmXG4gICAgT2JqZWN0LnByb3RvdHlwZS50b1N0cmluZy5jYWxsKG9iaikgIT09ICdbb2JqZWN0IE9iamVjdF0nXG4gICk7XG59O1xuXG4vKipcbiAqIEluaXRpYXRlIHJlcXVlc3QsIGludm9raW5nIGNhbGxiYWNrIGBmbihyZXMpYFxuICogd2l0aCBhbiBpbnN0YW5jZW9mIGBSZXNwb25zZWAuXG4gKlxuICogQHBhcmFtIHtGdW5jdGlvbn0gZm5cbiAqIEByZXR1cm4ge1JlcXVlc3R9IGZvciBjaGFpbmluZ1xuICogQGFwaSBwdWJsaWNcbiAqL1xuXG5SZXF1ZXN0LnByb3RvdHlwZS5lbmQgPSBmdW5jdGlvbihmbikge1xuICBpZiAodGhpcy5fZW5kQ2FsbGVkKSB7XG4gICAgY29uc29sZS53YXJuKFxuICAgICAgJ1dhcm5pbmc6IC5lbmQoKSB3YXMgY2FsbGVkIHR3aWNlLiBUaGlzIGlzIG5vdCBzdXBwb3J0ZWQgaW4gc3VwZXJhZ2VudCdcbiAgICApO1xuICB9XG5cbiAgdGhpcy5fZW5kQ2FsbGVkID0gdHJ1ZTtcblxuICAvLyBzdG9yZSBjYWxsYmFja1xuICB0aGlzLl9jYWxsYmFjayA9IGZuIHx8IG5vb3A7XG5cbiAgLy8gcXVlcnlzdHJpbmdcbiAgdGhpcy5fZmluYWxpemVRdWVyeVN0cmluZygpO1xuXG4gIHRoaXMuX2VuZCgpO1xufTtcblxuUmVxdWVzdC5wcm90b3R5cGUuX3NldFVwbG9hZFRpbWVvdXQgPSBmdW5jdGlvbigpIHtcbiAgY29uc3Qgc2VsZiA9IHRoaXM7XG5cbiAgLy8gdXBsb2FkIHRpbWVvdXQgaXQncyB3b2tycyBvbmx5IGlmIGRlYWRsaW5lIHRpbWVvdXQgaXMgb2ZmXG4gIGlmICh0aGlzLl91cGxvYWRUaW1lb3V0ICYmICF0aGlzLl91cGxvYWRUaW1lb3V0VGltZXIpIHtcbiAgICB0aGlzLl91cGxvYWRUaW1lb3V0VGltZXIgPSBzZXRUaW1lb3V0KCgpID0+IHtcbiAgICAgIHNlbGYuX3RpbWVvdXRFcnJvcihcbiAgICAgICAgJ1VwbG9hZCB0aW1lb3V0IG9mICcsXG4gICAgICAgIHNlbGYuX3VwbG9hZFRpbWVvdXQsXG4gICAgICAgICdFVElNRURPVVQnXG4gICAgICApO1xuICAgIH0sIHRoaXMuX3VwbG9hZFRpbWVvdXQpO1xuICB9XG59O1xuXG4vLyBlc2xpbnQtZGlzYWJsZS1uZXh0LWxpbmUgY29tcGxleGl0eVxuUmVxdWVzdC5wcm90b3R5cGUuX2VuZCA9IGZ1bmN0aW9uKCkge1xuICBpZiAodGhpcy5fYWJvcnRlZClcbiAgICByZXR1cm4gdGhpcy5jYWxsYmFjayhcbiAgICAgIG5ldyBFcnJvcignVGhlIHJlcXVlc3QgaGFzIGJlZW4gYWJvcnRlZCBldmVuIGJlZm9yZSAuZW5kKCkgd2FzIGNhbGxlZCcpXG4gICAgKTtcblxuICBjb25zdCBzZWxmID0gdGhpcztcbiAgdGhpcy54aHIgPSByZXF1ZXN0LmdldFhIUigpO1xuICBjb25zdCB7IHhociB9ID0gdGhpcztcbiAgbGV0IGRhdGEgPSB0aGlzLl9mb3JtRGF0YSB8fCB0aGlzLl9kYXRhO1xuXG4gIHRoaXMuX3NldFRpbWVvdXRzKCk7XG5cbiAgLy8gc3RhdGUgY2hhbmdlXG4gIHhoci5vbnJlYWR5c3RhdGVjaGFuZ2UgPSAoKSA9PiB7XG4gICAgY29uc3QgeyByZWFkeVN0YXRlIH0gPSB4aHI7XG4gICAgaWYgKHJlYWR5U3RhdGUgPj0gMiAmJiBzZWxmLl9yZXNwb25zZVRpbWVvdXRUaW1lcikge1xuICAgICAgY2xlYXJUaW1lb3V0KHNlbGYuX3Jlc3BvbnNlVGltZW91dFRpbWVyKTtcbiAgICB9XG5cbiAgICBpZiAocmVhZHlTdGF0ZSAhPT0gNCkge1xuICAgICAgcmV0dXJuO1xuICAgIH1cblxuICAgIC8vIEluIElFOSwgcmVhZHMgdG8gYW55IHByb3BlcnR5IChlLmcuIHN0YXR1cykgb2ZmIG9mIGFuIGFib3J0ZWQgWEhSIHdpbGxcbiAgICAvLyByZXN1bHQgaW4gdGhlIGVycm9yIFwiQ291bGQgbm90IGNvbXBsZXRlIHRoZSBvcGVyYXRpb24gZHVlIHRvIGVycm9yIGMwMGMwMjNmXCJcbiAgICBsZXQgc3RhdHVzO1xuICAgIHRyeSB7XG4gICAgICBzdGF0dXMgPSB4aHIuc3RhdHVzO1xuICAgIH0gY2F0Y2gge1xuICAgICAgc3RhdHVzID0gMDtcbiAgICB9XG5cbiAgICBpZiAoIXN0YXR1cykge1xuICAgICAgaWYgKHNlbGYudGltZWRvdXQgfHwgc2VsZi5fYWJvcnRlZCkgcmV0dXJuO1xuICAgICAgcmV0dXJuIHNlbGYuY3Jvc3NEb21haW5FcnJvcigpO1xuICAgIH1cblxuICAgIHNlbGYuZW1pdCgnZW5kJyk7XG4gIH07XG5cbiAgLy8gcHJvZ3Jlc3NcbiAgY29uc3QgaGFuZGxlUHJvZ3Jlc3MgPSAoZGlyZWN0aW9uLCBlKSA9PiB7XG4gICAgaWYgKGUudG90YWwgPiAwKSB7XG4gICAgICBlLnBlcmNlbnQgPSAoZS5sb2FkZWQgLyBlLnRvdGFsKSAqIDEwMDtcblxuICAgICAgaWYgKGUucGVyY2VudCA9PT0gMTAwKSB7XG4gICAgICAgIGNsZWFyVGltZW91dChzZWxmLl91cGxvYWRUaW1lb3V0VGltZXIpO1xuICAgICAgfVxuICAgIH1cblxuICAgIGUuZGlyZWN0aW9uID0gZGlyZWN0aW9uO1xuICAgIHNlbGYuZW1pdCgncHJvZ3Jlc3MnLCBlKTtcbiAgfTtcblxuICBpZiAodGhpcy5oYXNMaXN0ZW5lcnMoJ3Byb2dyZXNzJykpIHtcbiAgICB0cnkge1xuICAgICAgeGhyLmFkZEV2ZW50TGlzdGVuZXIoJ3Byb2dyZXNzJywgaGFuZGxlUHJvZ3Jlc3MuYmluZChudWxsLCAnZG93bmxvYWQnKSk7XG4gICAgICBpZiAoeGhyLnVwbG9hZCkge1xuICAgICAgICB4aHIudXBsb2FkLmFkZEV2ZW50TGlzdGVuZXIoXG4gICAgICAgICAgJ3Byb2dyZXNzJyxcbiAgICAgICAgICBoYW5kbGVQcm9ncmVzcy5iaW5kKG51bGwsICd1cGxvYWQnKVxuICAgICAgICApO1xuICAgICAgfVxuICAgIH0gY2F0Y2gge1xuICAgICAgLy8gQWNjZXNzaW5nIHhoci51cGxvYWQgZmFpbHMgaW4gSUUgZnJvbSBhIHdlYiB3b3JrZXIsIHNvIGp1c3QgcHJldGVuZCBpdCBkb2Vzbid0IGV4aXN0LlxuICAgICAgLy8gUmVwb3J0ZWQgaGVyZTpcbiAgICAgIC8vIGh0dHBzOi8vY29ubmVjdC5taWNyb3NvZnQuY29tL0lFL2ZlZWRiYWNrL2RldGFpbHMvODM3MjQ1L3htbGh0dHByZXF1ZXN0LXVwbG9hZC10aHJvd3MtaW52YWxpZC1hcmd1bWVudC13aGVuLXVzZWQtZnJvbS13ZWItd29ya2VyLWNvbnRleHRcbiAgICB9XG4gIH1cblxuICBpZiAoeGhyLnVwbG9hZCkge1xuICAgIHRoaXMuX3NldFVwbG9hZFRpbWVvdXQoKTtcbiAgfVxuXG4gIC8vIGluaXRpYXRlIHJlcXVlc3RcbiAgdHJ5IHtcbiAgICBpZiAodGhpcy51c2VybmFtZSAmJiB0aGlzLnBhc3N3b3JkKSB7XG4gICAgICB4aHIub3Blbih0aGlzLm1ldGhvZCwgdGhpcy51cmwsIHRydWUsIHRoaXMudXNlcm5hbWUsIHRoaXMucGFzc3dvcmQpO1xuICAgIH0gZWxzZSB7XG4gICAgICB4aHIub3Blbih0aGlzLm1ldGhvZCwgdGhpcy51cmwsIHRydWUpO1xuICAgIH1cbiAgfSBjYXRjaCAoZXJyKSB7XG4gICAgLy8gc2VlICMxMTQ5XG4gICAgcmV0dXJuIHRoaXMuY2FsbGJhY2soZXJyKTtcbiAgfVxuXG4gIC8vIENPUlNcbiAgaWYgKHRoaXMuX3dpdGhDcmVkZW50aWFscykgeGhyLndpdGhDcmVkZW50aWFscyA9IHRydWU7XG5cbiAgLy8gYm9keVxuICBpZiAoXG4gICAgIXRoaXMuX2Zvcm1EYXRhICYmXG4gICAgdGhpcy5tZXRob2QgIT09ICdHRVQnICYmXG4gICAgdGhpcy5tZXRob2QgIT09ICdIRUFEJyAmJlxuICAgIHR5cGVvZiBkYXRhICE9PSAnc3RyaW5nJyAmJlxuICAgICF0aGlzLl9pc0hvc3QoZGF0YSlcbiAgKSB7XG4gICAgLy8gc2VyaWFsaXplIHN0dWZmXG4gICAgY29uc3QgY29udGVudFR5cGUgPSB0aGlzLl9oZWFkZXJbJ2NvbnRlbnQtdHlwZSddO1xuICAgIGxldCBzZXJpYWxpemUgPVxuICAgICAgdGhpcy5fc2VyaWFsaXplciB8fFxuICAgICAgcmVxdWVzdC5zZXJpYWxpemVbY29udGVudFR5cGUgPyBjb250ZW50VHlwZS5zcGxpdCgnOycpWzBdIDogJyddO1xuICAgIGlmICghc2VyaWFsaXplICYmIGlzSlNPTihjb250ZW50VHlwZSkpIHtcbiAgICAgIHNlcmlhbGl6ZSA9IHJlcXVlc3Quc2VyaWFsaXplWydhcHBsaWNhdGlvbi9qc29uJ107XG4gICAgfVxuXG4gICAgaWYgKHNlcmlhbGl6ZSkgZGF0YSA9IHNlcmlhbGl6ZShkYXRhKTtcbiAgfVxuXG4gIC8vIHNldCBoZWFkZXIgZmllbGRzXG4gIGZvciAoY29uc3QgZmllbGQgaW4gdGhpcy5oZWFkZXIpIHtcbiAgICBpZiAodGhpcy5oZWFkZXJbZmllbGRdID09PSBudWxsKSBjb250aW51ZTtcblxuICAgIGlmIChPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwodGhpcy5oZWFkZXIsIGZpZWxkKSlcbiAgICAgIHhoci5zZXRSZXF1ZXN0SGVhZGVyKGZpZWxkLCB0aGlzLmhlYWRlcltmaWVsZF0pO1xuICB9XG5cbiAgaWYgKHRoaXMuX3Jlc3BvbnNlVHlwZSkge1xuICAgIHhoci5yZXNwb25zZVR5cGUgPSB0aGlzLl9yZXNwb25zZVR5cGU7XG4gIH1cblxuICAvLyBzZW5kIHN0dWZmXG4gIHRoaXMuZW1pdCgncmVxdWVzdCcsIHRoaXMpO1xuXG4gIC8vIElFMTEgeGhyLnNlbmQodW5kZWZpbmVkKSBzZW5kcyAndW5kZWZpbmVkJyBzdHJpbmcgYXMgUE9TVCBwYXlsb2FkIChpbnN0ZWFkIG9mIG5vdGhpbmcpXG4gIC8vIFdlIG5lZWQgbnVsbCBoZXJlIGlmIGRhdGEgaXMgdW5kZWZpbmVkXG4gIHhoci5zZW5kKHR5cGVvZiBkYXRhID09PSAndW5kZWZpbmVkJyA/IG51bGwgOiBkYXRhKTtcbn07XG5cbnJlcXVlc3QuYWdlbnQgPSAoKSA9PiBuZXcgQWdlbnQoKTtcblxuWydHRVQnLCAnUE9TVCcsICdPUFRJT05TJywgJ1BBVENIJywgJ1BVVCcsICdERUxFVEUnXS5mb3JFYWNoKG1ldGhvZCA9PiB7XG4gIEFnZW50LnByb3RvdHlwZVttZXRob2QudG9Mb3dlckNhc2UoKV0gPSBmdW5jdGlvbih1cmwsIGZuKSB7XG4gICAgY29uc3QgcmVxID0gbmV3IHJlcXVlc3QuUmVxdWVzdChtZXRob2QsIHVybCk7XG4gICAgdGhpcy5fc2V0RGVmYXVsdHMocmVxKTtcbiAgICBpZiAoZm4pIHtcbiAgICAgIHJlcS5lbmQoZm4pO1xuICAgIH1cblxuICAgIHJldHVybiByZXE7XG4gIH07XG59KTtcblxuQWdlbnQucHJvdG90eXBlLmRlbCA9IEFnZW50LnByb3RvdHlwZS5kZWxldGU7XG5cbi8qKlxuICogR0VUIGB1cmxgIHdpdGggb3B0aW9uYWwgY2FsbGJhY2sgYGZuKHJlcylgLlxuICpcbiAqIEBwYXJhbSB7U3RyaW5nfSB1cmxcbiAqIEBwYXJhbSB7TWl4ZWR8RnVuY3Rpb259IFtkYXRhXSBvciBmblxuICogQHBhcmFtIHtGdW5jdGlvbn0gW2ZuXVxuICogQHJldHVybiB7UmVxdWVzdH1cbiAqIEBhcGkgcHVibGljXG4gKi9cblxucmVxdWVzdC5nZXQgPSAodXJsLCBkYXRhLCBmbikgPT4ge1xuICBjb25zdCByZXEgPSByZXF1ZXN0KCdHRVQnLCB1cmwpO1xuICBpZiAodHlwZW9mIGRhdGEgPT09ICdmdW5jdGlvbicpIHtcbiAgICBmbiA9IGRhdGE7XG4gICAgZGF0YSA9IG51bGw7XG4gIH1cblxuICBpZiAoZGF0YSkgcmVxLnF1ZXJ5KGRhdGEpO1xuICBpZiAoZm4pIHJlcS5lbmQoZm4pO1xuICByZXR1cm4gcmVxO1xufTtcblxuLyoqXG4gKiBIRUFEIGB1cmxgIHdpdGggb3B0aW9uYWwgY2FsbGJhY2sgYGZuKHJlcylgLlxuICpcbiAqIEBwYXJhbSB7U3RyaW5nfSB1cmxcbiAqIEBwYXJhbSB7TWl4ZWR8RnVuY3Rpb259IFtkYXRhXSBvciBmblxuICogQHBhcmFtIHtGdW5jdGlvbn0gW2ZuXVxuICogQHJldHVybiB7UmVxdWVzdH1cbiAqIEBhcGkgcHVibGljXG4gKi9cblxucmVxdWVzdC5oZWFkID0gKHVybCwgZGF0YSwgZm4pID0+IHtcbiAgY29uc3QgcmVxID0gcmVxdWVzdCgnSEVBRCcsIHVybCk7XG4gIGlmICh0eXBlb2YgZGF0YSA9PT0gJ2Z1bmN0aW9uJykge1xuICAgIGZuID0gZGF0YTtcbiAgICBkYXRhID0gbnVsbDtcbiAgfVxuXG4gIGlmIChkYXRhKSByZXEucXVlcnkoZGF0YSk7XG4gIGlmIChmbikgcmVxLmVuZChmbik7XG4gIHJldHVybiByZXE7XG59O1xuXG4vKipcbiAqIE9QVElPTlMgcXVlcnkgdG8gYHVybGAgd2l0aCBvcHRpb25hbCBjYWxsYmFjayBgZm4ocmVzKWAuXG4gKlxuICogQHBhcmFtIHtTdHJpbmd9IHVybFxuICogQHBhcmFtIHtNaXhlZHxGdW5jdGlvbn0gW2RhdGFdIG9yIGZuXG4gKiBAcGFyYW0ge0Z1bmN0aW9ufSBbZm5dXG4gKiBAcmV0dXJuIHtSZXF1ZXN0fVxuICogQGFwaSBwdWJsaWNcbiAqL1xuXG5yZXF1ZXN0Lm9wdGlvbnMgPSAodXJsLCBkYXRhLCBmbikgPT4ge1xuICBjb25zdCByZXEgPSByZXF1ZXN0KCdPUFRJT05TJywgdXJsKTtcbiAgaWYgKHR5cGVvZiBkYXRhID09PSAnZnVuY3Rpb24nKSB7XG4gICAgZm4gPSBkYXRhO1xuICAgIGRhdGEgPSBudWxsO1xuICB9XG5cbiAgaWYgKGRhdGEpIHJlcS5zZW5kKGRhdGEpO1xuICBpZiAoZm4pIHJlcS5lbmQoZm4pO1xuICByZXR1cm4gcmVxO1xufTtcblxuLyoqXG4gKiBERUxFVEUgYHVybGAgd2l0aCBvcHRpb25hbCBgZGF0YWAgYW5kIGNhbGxiYWNrIGBmbihyZXMpYC5cbiAqXG4gKiBAcGFyYW0ge1N0cmluZ30gdXJsXG4gKiBAcGFyYW0ge01peGVkfSBbZGF0YV1cbiAqIEBwYXJhbSB7RnVuY3Rpb259IFtmbl1cbiAqIEByZXR1cm4ge1JlcXVlc3R9XG4gKiBAYXBpIHB1YmxpY1xuICovXG5cbmZ1bmN0aW9uIGRlbCh1cmwsIGRhdGEsIGZuKSB7XG4gIGNvbnN0IHJlcSA9IHJlcXVlc3QoJ0RFTEVURScsIHVybCk7XG4gIGlmICh0eXBlb2YgZGF0YSA9PT0gJ2Z1bmN0aW9uJykge1xuICAgIGZuID0gZGF0YTtcbiAgICBkYXRhID0gbnVsbDtcbiAgfVxuXG4gIGlmIChkYXRhKSByZXEuc2VuZChkYXRhKTtcbiAgaWYgKGZuKSByZXEuZW5kKGZuKTtcbiAgcmV0dXJuIHJlcTtcbn1cblxucmVxdWVzdC5kZWwgPSBkZWw7XG5yZXF1ZXN0LmRlbGV0ZSA9IGRlbDtcblxuLyoqXG4gKiBQQVRDSCBgdXJsYCB3aXRoIG9wdGlvbmFsIGBkYXRhYCBhbmQgY2FsbGJhY2sgYGZuKHJlcylgLlxuICpcbiAqIEBwYXJhbSB7U3RyaW5nfSB1cmxcbiAqIEBwYXJhbSB7TWl4ZWR9IFtkYXRhXVxuICogQHBhcmFtIHtGdW5jdGlvbn0gW2ZuXVxuICogQHJldHVybiB7UmVxdWVzdH1cbiAqIEBhcGkgcHVibGljXG4gKi9cblxucmVxdWVzdC5wYXRjaCA9ICh1cmwsIGRhdGEsIGZuKSA9PiB7XG4gIGNvbnN0IHJlcSA9IHJlcXVlc3QoJ1BBVENIJywgdXJsKTtcbiAgaWYgKHR5cGVvZiBkYXRhID09PSAnZnVuY3Rpb24nKSB7XG4gICAgZm4gPSBkYXRhO1xuICAgIGRhdGEgPSBudWxsO1xuICB9XG5cbiAgaWYgKGRhdGEpIHJlcS5zZW5kKGRhdGEpO1xuICBpZiAoZm4pIHJlcS5lbmQoZm4pO1xuICByZXR1cm4gcmVxO1xufTtcblxuLyoqXG4gKiBQT1NUIGB1cmxgIHdpdGggb3B0aW9uYWwgYGRhdGFgIGFuZCBjYWxsYmFjayBgZm4ocmVzKWAuXG4gKlxuICogQHBhcmFtIHtTdHJpbmd9IHVybFxuICogQHBhcmFtIHtNaXhlZH0gW2RhdGFdXG4gKiBAcGFyYW0ge0Z1bmN0aW9ufSBbZm5dXG4gKiBAcmV0dXJuIHtSZXF1ZXN0fVxuICogQGFwaSBwdWJsaWNcbiAqL1xuXG5yZXF1ZXN0LnBvc3QgPSAodXJsLCBkYXRhLCBmbikgPT4ge1xuICBjb25zdCByZXEgPSByZXF1ZXN0KCdQT1NUJywgdXJsKTtcbiAgaWYgKHR5cGVvZiBkYXRhID09PSAnZnVuY3Rpb24nKSB7XG4gICAgZm4gPSBkYXRhO1xuICAgIGRhdGEgPSBudWxsO1xuICB9XG5cbiAgaWYgKGRhdGEpIHJlcS5zZW5kKGRhdGEpO1xuICBpZiAoZm4pIHJlcS5lbmQoZm4pO1xuICByZXR1cm4gcmVxO1xufTtcblxuLyoqXG4gKiBQVVQgYHVybGAgd2l0aCBvcHRpb25hbCBgZGF0YWAgYW5kIGNhbGxiYWNrIGBmbihyZXMpYC5cbiAqXG4gKiBAcGFyYW0ge1N0cmluZ30gdXJsXG4gKiBAcGFyYW0ge01peGVkfEZ1bmN0aW9ufSBbZGF0YV0gb3IgZm5cbiAqIEBwYXJhbSB7RnVuY3Rpb259IFtmbl1cbiAqIEByZXR1cm4ge1JlcXVlc3R9XG4gKiBAYXBpIHB1YmxpY1xuICovXG5cbnJlcXVlc3QucHV0ID0gKHVybCwgZGF0YSwgZm4pID0+IHtcbiAgY29uc3QgcmVxID0gcmVxdWVzdCgnUFVUJywgdXJsKTtcbiAgaWYgKHR5cGVvZiBkYXRhID09PSAnZnVuY3Rpb24nKSB7XG4gICAgZm4gPSBkYXRhO1xuICAgIGRhdGEgPSBudWxsO1xuICB9XG5cbiAgaWYgKGRhdGEpIHJlcS5zZW5kKGRhdGEpO1xuICBpZiAoZm4pIHJlcS5lbmQoZm4pO1xuICByZXR1cm4gcmVxO1xufTtcbiJdfQ== \ No newline at end of file diff --git a/node_modules/superagent/lib/is-object.js b/node_modules/superagent/lib/is-object.js new file mode 100644 index 000000000..b1a6ec2de --- /dev/null +++ b/node_modules/superagent/lib/is-object.js @@ -0,0 +1,17 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Check if `obj` is an object. + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ +function isObject(obj) { + return obj !== null && _typeof(obj) === 'object'; +} + +module.exports = isObject; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uL3NyYy9pcy1vYmplY3QuanMiXSwibmFtZXMiOlsiaXNPYmplY3QiLCJvYmoiLCJtb2R1bGUiLCJleHBvcnRzIl0sIm1hcHBpbmdzIjoiOzs7O0FBQUE7Ozs7Ozs7QUFRQSxTQUFTQSxRQUFULENBQWtCQyxHQUFsQixFQUF1QjtBQUNyQixTQUFPQSxHQUFHLEtBQUssSUFBUixJQUFnQixRQUFPQSxHQUFQLE1BQWUsUUFBdEM7QUFDRDs7QUFFREMsTUFBTSxDQUFDQyxPQUFQLEdBQWlCSCxRQUFqQiIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQ2hlY2sgaWYgYG9iamAgaXMgYW4gb2JqZWN0LlxuICpcbiAqIEBwYXJhbSB7T2JqZWN0fSBvYmpcbiAqIEByZXR1cm4ge0Jvb2xlYW59XG4gKiBAYXBpIHByaXZhdGVcbiAqL1xuXG5mdW5jdGlvbiBpc09iamVjdChvYmopIHtcbiAgcmV0dXJuIG9iaiAhPT0gbnVsbCAmJiB0eXBlb2Ygb2JqID09PSAnb2JqZWN0Jztcbn1cblxubW9kdWxlLmV4cG9ydHMgPSBpc09iamVjdDtcbiJdfQ== \ No newline at end of file diff --git a/node_modules/superagent/lib/node/agent.js b/node_modules/superagent/lib/node/agent.js new file mode 100644 index 000000000..e18e44c20 --- /dev/null +++ b/node_modules/superagent/lib/node/agent.js @@ -0,0 +1,113 @@ +"use strict"; + +/** + * Module dependencies. + */ +// eslint-disable-next-line node/no-deprecated-api +var _require = require('url'), + parse = _require.parse; + +var _require2 = require('cookiejar'), + CookieJar = _require2.CookieJar; + +var _require3 = require('cookiejar'), + CookieAccessInfo = _require3.CookieAccessInfo; + +var methods = require('methods'); + +var request = require('../..'); + +var AgentBase = require('../agent-base'); +/** + * Expose `Agent`. + */ + + +module.exports = Agent; +/** + * Initialize a new `Agent`. + * + * @api public + */ + +function Agent(options) { + if (!(this instanceof Agent)) { + return new Agent(options); + } + + AgentBase.call(this); + this.jar = new CookieJar(); + + if (options) { + if (options.ca) { + this.ca(options.ca); + } + + if (options.key) { + this.key(options.key); + } + + if (options.pfx) { + this.pfx(options.pfx); + } + + if (options.cert) { + this.cert(options.cert); + } + + if (options.rejectUnauthorized === false) { + this.disableTLSCerts(); + } + } +} + +Agent.prototype = Object.create(AgentBase.prototype); +/** + * Save the cookies in the given `res` to + * the agent's cookie jar for persistence. + * + * @param {Response} res + * @api private + */ + +Agent.prototype._saveCookies = function (res) { + var cookies = res.headers['set-cookie']; + if (cookies) this.jar.setCookies(cookies); +}; +/** + * Attach cookies when available to the given `req`. + * + * @param {Request} req + * @api private + */ + + +Agent.prototype._attachCookies = function (req) { + var url = parse(req.url); + var access = new CookieAccessInfo(url.hostname, url.pathname, url.protocol === 'https:'); + var cookies = this.jar.getCookies(access).toValueString(); + req.cookies = cookies; +}; + +methods.forEach(function (name) { + var method = name.toUpperCase(); + + Agent.prototype[name] = function (url, fn) { + var req = new request.Request(method, url); + req.on('response', this._saveCookies.bind(this)); + req.on('redirect', this._saveCookies.bind(this)); + req.on('redirect', this._attachCookies.bind(this, req)); + + this._setDefaults(req); + + this._attachCookies(req); + + if (fn) { + req.end(fn); + } + + return req; + }; +}); +Agent.prototype.del = Agent.prototype.delete; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9ub2RlL2FnZW50LmpzIl0sIm5hbWVzIjpbInJlcXVpcmUiLCJwYXJzZSIsIkNvb2tpZUphciIsIkNvb2tpZUFjY2Vzc0luZm8iLCJtZXRob2RzIiwicmVxdWVzdCIsIkFnZW50QmFzZSIsIm1vZHVsZSIsImV4cG9ydHMiLCJBZ2VudCIsIm9wdGlvbnMiLCJjYWxsIiwiamFyIiwiY2EiLCJrZXkiLCJwZngiLCJjZXJ0IiwicmVqZWN0VW5hdXRob3JpemVkIiwiZGlzYWJsZVRMU0NlcnRzIiwicHJvdG90eXBlIiwiT2JqZWN0IiwiY3JlYXRlIiwiX3NhdmVDb29raWVzIiwicmVzIiwiY29va2llcyIsImhlYWRlcnMiLCJzZXRDb29raWVzIiwiX2F0dGFjaENvb2tpZXMiLCJyZXEiLCJ1cmwiLCJhY2Nlc3MiLCJob3N0bmFtZSIsInBhdGhuYW1lIiwicHJvdG9jb2wiLCJnZXRDb29raWVzIiwidG9WYWx1ZVN0cmluZyIsImZvckVhY2giLCJuYW1lIiwibWV0aG9kIiwidG9VcHBlckNhc2UiLCJmbiIsIlJlcXVlc3QiLCJvbiIsImJpbmQiLCJfc2V0RGVmYXVsdHMiLCJlbmQiLCJkZWwiLCJkZWxldGUiXSwibWFwcGluZ3MiOiI7O0FBQUE7OztBQUlBO2VBQ2tCQSxPQUFPLENBQUMsS0FBRCxDO0lBQWpCQyxLLFlBQUFBLEs7O2dCQUNjRCxPQUFPLENBQUMsV0FBRCxDO0lBQXJCRSxTLGFBQUFBLFM7O2dCQUNxQkYsT0FBTyxDQUFDLFdBQUQsQztJQUE1QkcsZ0IsYUFBQUEsZ0I7O0FBQ1IsSUFBTUMsT0FBTyxHQUFHSixPQUFPLENBQUMsU0FBRCxDQUF2Qjs7QUFDQSxJQUFNSyxPQUFPLEdBQUdMLE9BQU8sQ0FBQyxPQUFELENBQXZCOztBQUNBLElBQU1NLFNBQVMsR0FBR04sT0FBTyxDQUFDLGVBQUQsQ0FBekI7QUFFQTs7Ozs7QUFJQU8sTUFBTSxDQUFDQyxPQUFQLEdBQWlCQyxLQUFqQjtBQUVBOzs7Ozs7QUFNQSxTQUFTQSxLQUFULENBQWVDLE9BQWYsRUFBd0I7QUFDdEIsTUFBSSxFQUFFLGdCQUFnQkQsS0FBbEIsQ0FBSixFQUE4QjtBQUM1QixXQUFPLElBQUlBLEtBQUosQ0FBVUMsT0FBVixDQUFQO0FBQ0Q7O0FBRURKLEVBQUFBLFNBQVMsQ0FBQ0ssSUFBVixDQUFlLElBQWY7QUFDQSxPQUFLQyxHQUFMLEdBQVcsSUFBSVYsU0FBSixFQUFYOztBQUVBLE1BQUlRLE9BQUosRUFBYTtBQUNYLFFBQUlBLE9BQU8sQ0FBQ0csRUFBWixFQUFnQjtBQUNkLFdBQUtBLEVBQUwsQ0FBUUgsT0FBTyxDQUFDRyxFQUFoQjtBQUNEOztBQUVELFFBQUlILE9BQU8sQ0FBQ0ksR0FBWixFQUFpQjtBQUNmLFdBQUtBLEdBQUwsQ0FBU0osT0FBTyxDQUFDSSxHQUFqQjtBQUNEOztBQUVELFFBQUlKLE9BQU8sQ0FBQ0ssR0FBWixFQUFpQjtBQUNmLFdBQUtBLEdBQUwsQ0FBU0wsT0FBTyxDQUFDSyxHQUFqQjtBQUNEOztBQUVELFFBQUlMLE9BQU8sQ0FBQ00sSUFBWixFQUFrQjtBQUNoQixXQUFLQSxJQUFMLENBQVVOLE9BQU8sQ0FBQ00sSUFBbEI7QUFDRDs7QUFFRCxRQUFJTixPQUFPLENBQUNPLGtCQUFSLEtBQStCLEtBQW5DLEVBQTBDO0FBQ3hDLFdBQUtDLGVBQUw7QUFDRDtBQUNGO0FBQ0Y7O0FBRURULEtBQUssQ0FBQ1UsU0FBTixHQUFrQkMsTUFBTSxDQUFDQyxNQUFQLENBQWNmLFNBQVMsQ0FBQ2EsU0FBeEIsQ0FBbEI7QUFFQTs7Ozs7Ozs7QUFRQVYsS0FBSyxDQUFDVSxTQUFOLENBQWdCRyxZQUFoQixHQUErQixVQUFTQyxHQUFULEVBQWM7QUFDM0MsTUFBTUMsT0FBTyxHQUFHRCxHQUFHLENBQUNFLE9BQUosQ0FBWSxZQUFaLENBQWhCO0FBQ0EsTUFBSUQsT0FBSixFQUFhLEtBQUtaLEdBQUwsQ0FBU2MsVUFBVCxDQUFvQkYsT0FBcEI7QUFDZCxDQUhEO0FBS0E7Ozs7Ozs7O0FBT0FmLEtBQUssQ0FBQ1UsU0FBTixDQUFnQlEsY0FBaEIsR0FBaUMsVUFBU0MsR0FBVCxFQUFjO0FBQzdDLE1BQU1DLEdBQUcsR0FBRzVCLEtBQUssQ0FBQzJCLEdBQUcsQ0FBQ0MsR0FBTCxDQUFqQjtBQUNBLE1BQU1DLE1BQU0sR0FBRyxJQUFJM0IsZ0JBQUosQ0FDYjBCLEdBQUcsQ0FBQ0UsUUFEUyxFQUViRixHQUFHLENBQUNHLFFBRlMsRUFHYkgsR0FBRyxDQUFDSSxRQUFKLEtBQWlCLFFBSEosQ0FBZjtBQUtBLE1BQU1ULE9BQU8sR0FBRyxLQUFLWixHQUFMLENBQVNzQixVQUFULENBQW9CSixNQUFwQixFQUE0QkssYUFBNUIsRUFBaEI7QUFDQVAsRUFBQUEsR0FBRyxDQUFDSixPQUFKLEdBQWNBLE9BQWQ7QUFDRCxDQVREOztBQVdBcEIsT0FBTyxDQUFDZ0MsT0FBUixDQUFnQixVQUFBQyxJQUFJLEVBQUk7QUFDdEIsTUFBTUMsTUFBTSxHQUFHRCxJQUFJLENBQUNFLFdBQUwsRUFBZjs7QUFDQTlCLEVBQUFBLEtBQUssQ0FBQ1UsU0FBTixDQUFnQmtCLElBQWhCLElBQXdCLFVBQVNSLEdBQVQsRUFBY1csRUFBZCxFQUFrQjtBQUN4QyxRQUFNWixHQUFHLEdBQUcsSUFBSXZCLE9BQU8sQ0FBQ29DLE9BQVosQ0FBb0JILE1BQXBCLEVBQTRCVCxHQUE1QixDQUFaO0FBRUFELElBQUFBLEdBQUcsQ0FBQ2MsRUFBSixDQUFPLFVBQVAsRUFBbUIsS0FBS3BCLFlBQUwsQ0FBa0JxQixJQUFsQixDQUF1QixJQUF2QixDQUFuQjtBQUNBZixJQUFBQSxHQUFHLENBQUNjLEVBQUosQ0FBTyxVQUFQLEVBQW1CLEtBQUtwQixZQUFMLENBQWtCcUIsSUFBbEIsQ0FBdUIsSUFBdkIsQ0FBbkI7QUFDQWYsSUFBQUEsR0FBRyxDQUFDYyxFQUFKLENBQU8sVUFBUCxFQUFtQixLQUFLZixjQUFMLENBQW9CZ0IsSUFBcEIsQ0FBeUIsSUFBekIsRUFBK0JmLEdBQS9CLENBQW5COztBQUNBLFNBQUtnQixZQUFMLENBQWtCaEIsR0FBbEI7O0FBQ0EsU0FBS0QsY0FBTCxDQUFvQkMsR0FBcEI7O0FBRUEsUUFBSVksRUFBSixFQUFRO0FBQ05aLE1BQUFBLEdBQUcsQ0FBQ2lCLEdBQUosQ0FBUUwsRUFBUjtBQUNEOztBQUVELFdBQU9aLEdBQVA7QUFDRCxHQWREO0FBZUQsQ0FqQkQ7QUFtQkFuQixLQUFLLENBQUNVLFNBQU4sQ0FBZ0IyQixHQUFoQixHQUFzQnJDLEtBQUssQ0FBQ1UsU0FBTixDQUFnQjRCLE1BQXRDIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBNb2R1bGUgZGVwZW5kZW5jaWVzLlxuICovXG5cbi8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBub2RlL25vLWRlcHJlY2F0ZWQtYXBpXG5jb25zdCB7IHBhcnNlIH0gPSByZXF1aXJlKCd1cmwnKTtcbmNvbnN0IHsgQ29va2llSmFyIH0gPSByZXF1aXJlKCdjb29raWVqYXInKTtcbmNvbnN0IHsgQ29va2llQWNjZXNzSW5mbyB9ID0gcmVxdWlyZSgnY29va2llamFyJyk7XG5jb25zdCBtZXRob2RzID0gcmVxdWlyZSgnbWV0aG9kcycpO1xuY29uc3QgcmVxdWVzdCA9IHJlcXVpcmUoJy4uLy4uJyk7XG5jb25zdCBBZ2VudEJhc2UgPSByZXF1aXJlKCcuLi9hZ2VudC1iYXNlJyk7XG5cbi8qKlxuICogRXhwb3NlIGBBZ2VudGAuXG4gKi9cblxubW9kdWxlLmV4cG9ydHMgPSBBZ2VudDtcblxuLyoqXG4gKiBJbml0aWFsaXplIGEgbmV3IGBBZ2VudGAuXG4gKlxuICogQGFwaSBwdWJsaWNcbiAqL1xuXG5mdW5jdGlvbiBBZ2VudChvcHRpb25zKSB7XG4gIGlmICghKHRoaXMgaW5zdGFuY2VvZiBBZ2VudCkpIHtcbiAgICByZXR1cm4gbmV3IEFnZW50KG9wdGlvbnMpO1xuICB9XG5cbiAgQWdlbnRCYXNlLmNhbGwodGhpcyk7XG4gIHRoaXMuamFyID0gbmV3IENvb2tpZUphcigpO1xuXG4gIGlmIChvcHRpb25zKSB7XG4gICAgaWYgKG9wdGlvbnMuY2EpIHtcbiAgICAgIHRoaXMuY2Eob3B0aW9ucy5jYSk7XG4gICAgfVxuXG4gICAgaWYgKG9wdGlvbnMua2V5KSB7XG4gICAgICB0aGlzLmtleShvcHRpb25zLmtleSk7XG4gICAgfVxuXG4gICAgaWYgKG9wdGlvbnMucGZ4KSB7XG4gICAgICB0aGlzLnBmeChvcHRpb25zLnBmeCk7XG4gICAgfVxuXG4gICAgaWYgKG9wdGlvbnMuY2VydCkge1xuICAgICAgdGhpcy5jZXJ0KG9wdGlvbnMuY2VydCk7XG4gICAgfVxuXG4gICAgaWYgKG9wdGlvbnMucmVqZWN0VW5hdXRob3JpemVkID09PSBmYWxzZSkge1xuICAgICAgdGhpcy5kaXNhYmxlVExTQ2VydHMoKTtcbiAgICB9XG4gIH1cbn1cblxuQWdlbnQucHJvdG90eXBlID0gT2JqZWN0LmNyZWF0ZShBZ2VudEJhc2UucHJvdG90eXBlKTtcblxuLyoqXG4gKiBTYXZlIHRoZSBjb29raWVzIGluIHRoZSBnaXZlbiBgcmVzYCB0b1xuICogdGhlIGFnZW50J3MgY29va2llIGphciBmb3IgcGVyc2lzdGVuY2UuXG4gKlxuICogQHBhcmFtIHtSZXNwb25zZX0gcmVzXG4gKiBAYXBpIHByaXZhdGVcbiAqL1xuXG5BZ2VudC5wcm90b3R5cGUuX3NhdmVDb29raWVzID0gZnVuY3Rpb24ocmVzKSB7XG4gIGNvbnN0IGNvb2tpZXMgPSByZXMuaGVhZGVyc1snc2V0LWNvb2tpZSddO1xuICBpZiAoY29va2llcykgdGhpcy5qYXIuc2V0Q29va2llcyhjb29raWVzKTtcbn07XG5cbi8qKlxuICogQXR0YWNoIGNvb2tpZXMgd2hlbiBhdmFpbGFibGUgdG8gdGhlIGdpdmVuIGByZXFgLlxuICpcbiAqIEBwYXJhbSB7UmVxdWVzdH0gcmVxXG4gKiBAYXBpIHByaXZhdGVcbiAqL1xuXG5BZ2VudC5wcm90b3R5cGUuX2F0dGFjaENvb2tpZXMgPSBmdW5jdGlvbihyZXEpIHtcbiAgY29uc3QgdXJsID0gcGFyc2UocmVxLnVybCk7XG4gIGNvbnN0IGFjY2VzcyA9IG5ldyBDb29raWVBY2Nlc3NJbmZvKFxuICAgIHVybC5ob3N0bmFtZSxcbiAgICB1cmwucGF0aG5hbWUsXG4gICAgdXJsLnByb3RvY29sID09PSAnaHR0cHM6J1xuICApO1xuICBjb25zdCBjb29raWVzID0gdGhpcy5qYXIuZ2V0Q29va2llcyhhY2Nlc3MpLnRvVmFsdWVTdHJpbmcoKTtcbiAgcmVxLmNvb2tpZXMgPSBjb29raWVzO1xufTtcblxubWV0aG9kcy5mb3JFYWNoKG5hbWUgPT4ge1xuICBjb25zdCBtZXRob2QgPSBuYW1lLnRvVXBwZXJDYXNlKCk7XG4gIEFnZW50LnByb3RvdHlwZVtuYW1lXSA9IGZ1bmN0aW9uKHVybCwgZm4pIHtcbiAgICBjb25zdCByZXEgPSBuZXcgcmVxdWVzdC5SZXF1ZXN0KG1ldGhvZCwgdXJsKTtcblxuICAgIHJlcS5vbigncmVzcG9uc2UnLCB0aGlzLl9zYXZlQ29va2llcy5iaW5kKHRoaXMpKTtcbiAgICByZXEub24oJ3JlZGlyZWN0JywgdGhpcy5fc2F2ZUNvb2tpZXMuYmluZCh0aGlzKSk7XG4gICAgcmVxLm9uKCdyZWRpcmVjdCcsIHRoaXMuX2F0dGFjaENvb2tpZXMuYmluZCh0aGlzLCByZXEpKTtcbiAgICB0aGlzLl9zZXREZWZhdWx0cyhyZXEpO1xuICAgIHRoaXMuX2F0dGFjaENvb2tpZXMocmVxKTtcblxuICAgIGlmIChmbikge1xuICAgICAgcmVxLmVuZChmbik7XG4gICAgfVxuXG4gICAgcmV0dXJuIHJlcTtcbiAgfTtcbn0pO1xuXG5BZ2VudC5wcm90b3R5cGUuZGVsID0gQWdlbnQucHJvdG90eXBlLmRlbGV0ZTtcbiJdfQ== \ No newline at end of file diff --git a/node_modules/superagent/lib/node/http2wrapper.js b/node_modules/superagent/lib/node/http2wrapper.js new file mode 100644 index 000000000..7aaca2877 --- /dev/null +++ b/node_modules/superagent/lib/node/http2wrapper.js @@ -0,0 +1,218 @@ +"use strict"; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var Stream = require('stream'); + +var util = require('util'); + +var net = require('net'); + +var tls = require('tls'); // eslint-disable-next-line node/no-deprecated-api + + +var _require = require('url'), + parse = _require.parse; + +var semver = require('semver'); + +var http2; +if (semver.gte(process.version, 'v10.10.0')) http2 = require('http2');else throw new Error('superagent: this version of Node.js does not support http2'); +var _http2$constants = http2.constants, + HTTP2_HEADER_PATH = _http2$constants.HTTP2_HEADER_PATH, + HTTP2_HEADER_STATUS = _http2$constants.HTTP2_HEADER_STATUS, + HTTP2_HEADER_METHOD = _http2$constants.HTTP2_HEADER_METHOD, + HTTP2_HEADER_AUTHORITY = _http2$constants.HTTP2_HEADER_AUTHORITY, + HTTP2_HEADER_HOST = _http2$constants.HTTP2_HEADER_HOST, + HTTP2_HEADER_SET_COOKIE = _http2$constants.HTTP2_HEADER_SET_COOKIE, + NGHTTP2_CANCEL = _http2$constants.NGHTTP2_CANCEL; + +function setProtocol(protocol) { + return { + request: function request(options) { + return new Request(protocol, options); + } + }; +} + +function Request(protocol, options) { + var _this = this; + + Stream.call(this); + var defaultPort = protocol === 'https:' ? 443 : 80; + var defaultHost = 'localhost'; + var port = options.port || defaultPort; + var host = options.host || defaultHost; + delete options.port; + delete options.host; + this.method = options.method; + this.path = options.path; + this.protocol = protocol; + this.host = host; + delete options.method; + delete options.path; + + var sessionOptions = _objectSpread({}, options); + + if (options.socketPath) { + sessionOptions.socketPath = options.socketPath; + sessionOptions.createConnection = this.createUnixConnection.bind(this); + } + + this._headers = {}; + var session = http2.connect("".concat(protocol, "//").concat(host, ":").concat(port), sessionOptions); + this.setHeader('host', "".concat(host, ":").concat(port)); + session.on('error', function (err) { + return _this.emit('error', err); + }); + this.session = session; +} +/** + * Inherit from `Stream` (which inherits from `EventEmitter`). + */ + + +util.inherits(Request, Stream); + +Request.prototype.createUnixConnection = function (authority, options) { + switch (this.protocol) { + case 'http:': + return net.connect(options.socketPath); + + case 'https:': + options.ALPNProtocols = ['h2']; + options.servername = this.host; + options.allowHalfOpen = true; + return tls.connect(options.socketPath, options); + + default: + throw new Error('Unsupported protocol', this.protocol); + } +}; // eslint-disable-next-line no-unused-vars + + +Request.prototype.setNoDelay = function (bool) {// We can not use setNoDelay with HTTP/2. + // Node 10 limits http2session.socket methods to ones safe to use with HTTP/2. + // See also https://nodejs.org/api/http2.html#http2_http2session_socket +}; + +Request.prototype.getFrame = function () { + var _method, + _this2 = this; + + if (this.frame) { + return this.frame; + } + + var method = (_method = {}, _defineProperty(_method, HTTP2_HEADER_PATH, this.path), _defineProperty(_method, HTTP2_HEADER_METHOD, this.method), _method); + var headers = this.mapToHttp2Header(this._headers); + headers = Object.assign(headers, method); + var frame = this.session.request(headers); // eslint-disable-next-line no-unused-vars + + frame.once('response', function (headers, flags) { + headers = _this2.mapToHttpHeader(headers); + frame.headers = headers; + frame.statusCode = headers[HTTP2_HEADER_STATUS]; + frame.status = frame.statusCode; + + _this2.emit('response', frame); + }); + this._headerSent = true; + frame.once('drain', function () { + return _this2.emit('drain'); + }); + frame.on('error', function (err) { + return _this2.emit('error', err); + }); + frame.on('close', function () { + return _this2.session.close(); + }); + this.frame = frame; + return frame; +}; + +Request.prototype.mapToHttpHeader = function (headers) { + var keys = Object.keys(headers); + var http2Headers = {}; + + for (var _i = 0, _keys = keys; _i < _keys.length; _i++) { + var key = _keys[_i]; + var value = headers[key]; + key = key.toLowerCase(); + + switch (key) { + case HTTP2_HEADER_SET_COOKIE: + value = Array.isArray(value) ? value : [value]; + break; + + default: + break; + } + + http2Headers[key] = value; + } + + return http2Headers; +}; + +Request.prototype.mapToHttp2Header = function (headers) { + var keys = Object.keys(headers); + var http2Headers = {}; + + for (var _i2 = 0, _keys2 = keys; _i2 < _keys2.length; _i2++) { + var key = _keys2[_i2]; + var value = headers[key]; + key = key.toLowerCase(); + + switch (key) { + case HTTP2_HEADER_HOST: + key = HTTP2_HEADER_AUTHORITY; + value = /^http:\/\/|^https:\/\//.test(value) ? parse(value).host : value; + break; + + default: + break; + } + + http2Headers[key] = value; + } + + return http2Headers; +}; + +Request.prototype.setHeader = function (name, value) { + this._headers[name.toLowerCase()] = value; +}; + +Request.prototype.getHeader = function (name) { + return this._headers[name.toLowerCase()]; +}; + +Request.prototype.write = function (data, encoding) { + var frame = this.getFrame(); + return frame.write(data, encoding); +}; + +Request.prototype.pipe = function (stream, options) { + var frame = this.getFrame(); + return frame.pipe(stream, options); +}; + +Request.prototype.end = function (data) { + var frame = this.getFrame(); + frame.end(data); +}; // eslint-disable-next-line no-unused-vars + + +Request.prototype.abort = function (data) { + var frame = this.getFrame(); + frame.close(NGHTTP2_CANCEL); + this.session.destroy(); +}; + +exports.setProtocol = setProtocol; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9ub2RlL2h0dHAyd3JhcHBlci5qcyJdLCJuYW1lcyI6WyJTdHJlYW0iLCJyZXF1aXJlIiwidXRpbCIsIm5ldCIsInRscyIsInBhcnNlIiwic2VtdmVyIiwiaHR0cDIiLCJndGUiLCJwcm9jZXNzIiwidmVyc2lvbiIsIkVycm9yIiwiY29uc3RhbnRzIiwiSFRUUDJfSEVBREVSX1BBVEgiLCJIVFRQMl9IRUFERVJfU1RBVFVTIiwiSFRUUDJfSEVBREVSX01FVEhPRCIsIkhUVFAyX0hFQURFUl9BVVRIT1JJVFkiLCJIVFRQMl9IRUFERVJfSE9TVCIsIkhUVFAyX0hFQURFUl9TRVRfQ09PS0lFIiwiTkdIVFRQMl9DQU5DRUwiLCJzZXRQcm90b2NvbCIsInByb3RvY29sIiwicmVxdWVzdCIsIm9wdGlvbnMiLCJSZXF1ZXN0IiwiY2FsbCIsImRlZmF1bHRQb3J0IiwiZGVmYXVsdEhvc3QiLCJwb3J0IiwiaG9zdCIsIm1ldGhvZCIsInBhdGgiLCJzZXNzaW9uT3B0aW9ucyIsInNvY2tldFBhdGgiLCJjcmVhdGVDb25uZWN0aW9uIiwiY3JlYXRlVW5peENvbm5lY3Rpb24iLCJiaW5kIiwiX2hlYWRlcnMiLCJzZXNzaW9uIiwiY29ubmVjdCIsInNldEhlYWRlciIsIm9uIiwiZXJyIiwiZW1pdCIsImluaGVyaXRzIiwicHJvdG90eXBlIiwiYXV0aG9yaXR5IiwiQUxQTlByb3RvY29scyIsInNlcnZlcm5hbWUiLCJhbGxvd0hhbGZPcGVuIiwic2V0Tm9EZWxheSIsImJvb2wiLCJnZXRGcmFtZSIsImZyYW1lIiwiaGVhZGVycyIsIm1hcFRvSHR0cDJIZWFkZXIiLCJPYmplY3QiLCJhc3NpZ24iLCJvbmNlIiwiZmxhZ3MiLCJtYXBUb0h0dHBIZWFkZXIiLCJzdGF0dXNDb2RlIiwic3RhdHVzIiwiX2hlYWRlclNlbnQiLCJjbG9zZSIsImtleXMiLCJodHRwMkhlYWRlcnMiLCJrZXkiLCJ2YWx1ZSIsInRvTG93ZXJDYXNlIiwiQXJyYXkiLCJpc0FycmF5IiwidGVzdCIsIm5hbWUiLCJnZXRIZWFkZXIiLCJ3cml0ZSIsImRhdGEiLCJlbmNvZGluZyIsInBpcGUiLCJzdHJlYW0iLCJlbmQiLCJhYm9ydCIsImRlc3Ryb3kiLCJleHBvcnRzIl0sIm1hcHBpbmdzIjoiOzs7Ozs7OztBQUFBLElBQU1BLE1BQU0sR0FBR0MsT0FBTyxDQUFDLFFBQUQsQ0FBdEI7O0FBQ0EsSUFBTUMsSUFBSSxHQUFHRCxPQUFPLENBQUMsTUFBRCxDQUFwQjs7QUFDQSxJQUFNRSxHQUFHLEdBQUdGLE9BQU8sQ0FBQyxLQUFELENBQW5COztBQUNBLElBQU1HLEdBQUcsR0FBR0gsT0FBTyxDQUFDLEtBQUQsQ0FBbkIsQyxDQUNBOzs7ZUFDa0JBLE9BQU8sQ0FBQyxLQUFELEM7SUFBakJJLEssWUFBQUEsSzs7QUFDUixJQUFNQyxNQUFNLEdBQUdMLE9BQU8sQ0FBQyxRQUFELENBQXRCOztBQUVBLElBQUlNLEtBQUo7QUFDQSxJQUFJRCxNQUFNLENBQUNFLEdBQVAsQ0FBV0MsT0FBTyxDQUFDQyxPQUFuQixFQUE0QixVQUE1QixDQUFKLEVBQTZDSCxLQUFLLEdBQUdOLE9BQU8sQ0FBQyxPQUFELENBQWYsQ0FBN0MsS0FFRSxNQUFNLElBQUlVLEtBQUosQ0FBVSw0REFBVixDQUFOO3VCQVVFSixLQUFLLENBQUNLLFM7SUFQUkMsaUIsb0JBQUFBLGlCO0lBQ0FDLG1CLG9CQUFBQSxtQjtJQUNBQyxtQixvQkFBQUEsbUI7SUFDQUMsc0Isb0JBQUFBLHNCO0lBQ0FDLGlCLG9CQUFBQSxpQjtJQUNBQyx1QixvQkFBQUEsdUI7SUFDQUMsYyxvQkFBQUEsYzs7QUFHRixTQUFTQyxXQUFULENBQXFCQyxRQUFyQixFQUErQjtBQUM3QixTQUFPO0FBQ0xDLElBQUFBLE9BREssbUJBQ0dDLE9BREgsRUFDWTtBQUNmLGFBQU8sSUFBSUMsT0FBSixDQUFZSCxRQUFaLEVBQXNCRSxPQUF0QixDQUFQO0FBQ0Q7QUFISSxHQUFQO0FBS0Q7O0FBRUQsU0FBU0MsT0FBVCxDQUFpQkgsUUFBakIsRUFBMkJFLE9BQTNCLEVBQW9DO0FBQUE7O0FBQ2xDdkIsRUFBQUEsTUFBTSxDQUFDeUIsSUFBUCxDQUFZLElBQVo7QUFDQSxNQUFNQyxXQUFXLEdBQUdMLFFBQVEsS0FBSyxRQUFiLEdBQXdCLEdBQXhCLEdBQThCLEVBQWxEO0FBQ0EsTUFBTU0sV0FBVyxHQUFHLFdBQXBCO0FBQ0EsTUFBTUMsSUFBSSxHQUFHTCxPQUFPLENBQUNLLElBQVIsSUFBZ0JGLFdBQTdCO0FBQ0EsTUFBTUcsSUFBSSxHQUFHTixPQUFPLENBQUNNLElBQVIsSUFBZ0JGLFdBQTdCO0FBRUEsU0FBT0osT0FBTyxDQUFDSyxJQUFmO0FBQ0EsU0FBT0wsT0FBTyxDQUFDTSxJQUFmO0FBRUEsT0FBS0MsTUFBTCxHQUFjUCxPQUFPLENBQUNPLE1BQXRCO0FBQ0EsT0FBS0MsSUFBTCxHQUFZUixPQUFPLENBQUNRLElBQXBCO0FBQ0EsT0FBS1YsUUFBTCxHQUFnQkEsUUFBaEI7QUFDQSxPQUFLUSxJQUFMLEdBQVlBLElBQVo7QUFFQSxTQUFPTixPQUFPLENBQUNPLE1BQWY7QUFDQSxTQUFPUCxPQUFPLENBQUNRLElBQWY7O0FBRUEsTUFBTUMsY0FBYyxxQkFBUVQsT0FBUixDQUFwQjs7QUFDQSxNQUFJQSxPQUFPLENBQUNVLFVBQVosRUFBd0I7QUFDdEJELElBQUFBLGNBQWMsQ0FBQ0MsVUFBZixHQUE0QlYsT0FBTyxDQUFDVSxVQUFwQztBQUNBRCxJQUFBQSxjQUFjLENBQUNFLGdCQUFmLEdBQWtDLEtBQUtDLG9CQUFMLENBQTBCQyxJQUExQixDQUErQixJQUEvQixDQUFsQztBQUNEOztBQUVELE9BQUtDLFFBQUwsR0FBZ0IsRUFBaEI7QUFFQSxNQUFNQyxPQUFPLEdBQUcvQixLQUFLLENBQUNnQyxPQUFOLFdBQWlCbEIsUUFBakIsZUFBOEJRLElBQTlCLGNBQXNDRCxJQUF0QyxHQUE4Q0ksY0FBOUMsQ0FBaEI7QUFDQSxPQUFLUSxTQUFMLENBQWUsTUFBZixZQUEwQlgsSUFBMUIsY0FBa0NELElBQWxDO0FBRUFVLEVBQUFBLE9BQU8sQ0FBQ0csRUFBUixDQUFXLE9BQVgsRUFBb0IsVUFBQUMsR0FBRztBQUFBLFdBQUksS0FBSSxDQUFDQyxJQUFMLENBQVUsT0FBVixFQUFtQkQsR0FBbkIsQ0FBSjtBQUFBLEdBQXZCO0FBRUEsT0FBS0osT0FBTCxHQUFlQSxPQUFmO0FBQ0Q7QUFFRDs7Ozs7QUFHQXBDLElBQUksQ0FBQzBDLFFBQUwsQ0FBY3BCLE9BQWQsRUFBdUJ4QixNQUF2Qjs7QUFFQXdCLE9BQU8sQ0FBQ3FCLFNBQVIsQ0FBa0JWLG9CQUFsQixHQUF5QyxVQUFTVyxTQUFULEVBQW9CdkIsT0FBcEIsRUFBNkI7QUFDcEUsVUFBUSxLQUFLRixRQUFiO0FBQ0UsU0FBSyxPQUFMO0FBQ0UsYUFBT2xCLEdBQUcsQ0FBQ29DLE9BQUosQ0FBWWhCLE9BQU8sQ0FBQ1UsVUFBcEIsQ0FBUDs7QUFDRixTQUFLLFFBQUw7QUFDRVYsTUFBQUEsT0FBTyxDQUFDd0IsYUFBUixHQUF3QixDQUFDLElBQUQsQ0FBeEI7QUFDQXhCLE1BQUFBLE9BQU8sQ0FBQ3lCLFVBQVIsR0FBcUIsS0FBS25CLElBQTFCO0FBQ0FOLE1BQUFBLE9BQU8sQ0FBQzBCLGFBQVIsR0FBd0IsSUFBeEI7QUFDQSxhQUFPN0MsR0FBRyxDQUFDbUMsT0FBSixDQUFZaEIsT0FBTyxDQUFDVSxVQUFwQixFQUFnQ1YsT0FBaEMsQ0FBUDs7QUFDRjtBQUNFLFlBQU0sSUFBSVosS0FBSixDQUFVLHNCQUFWLEVBQWtDLEtBQUtVLFFBQXZDLENBQU47QUFUSjtBQVdELENBWkQsQyxDQWNBOzs7QUFDQUcsT0FBTyxDQUFDcUIsU0FBUixDQUFrQkssVUFBbEIsR0FBK0IsVUFBU0MsSUFBVCxFQUFlLENBQzVDO0FBQ0E7QUFDQTtBQUNELENBSkQ7O0FBTUEzQixPQUFPLENBQUNxQixTQUFSLENBQWtCTyxRQUFsQixHQUE2QixZQUFXO0FBQUE7QUFBQTs7QUFDdEMsTUFBSSxLQUFLQyxLQUFULEVBQWdCO0FBQ2QsV0FBTyxLQUFLQSxLQUFaO0FBQ0Q7O0FBRUQsTUFBTXZCLE1BQU0sMkNBQ1RqQixpQkFEUyxFQUNXLEtBQUtrQixJQURoQiw0QkFFVGhCLG1CQUZTLEVBRWEsS0FBS2UsTUFGbEIsV0FBWjtBQUtBLE1BQUl3QixPQUFPLEdBQUcsS0FBS0MsZ0JBQUwsQ0FBc0IsS0FBS2xCLFFBQTNCLENBQWQ7QUFFQWlCLEVBQUFBLE9BQU8sR0FBR0UsTUFBTSxDQUFDQyxNQUFQLENBQWNILE9BQWQsRUFBdUJ4QixNQUF2QixDQUFWO0FBRUEsTUFBTXVCLEtBQUssR0FBRyxLQUFLZixPQUFMLENBQWFoQixPQUFiLENBQXFCZ0MsT0FBckIsQ0FBZCxDQWRzQyxDQWV0Qzs7QUFDQUQsRUFBQUEsS0FBSyxDQUFDSyxJQUFOLENBQVcsVUFBWCxFQUF1QixVQUFDSixPQUFELEVBQVVLLEtBQVYsRUFBb0I7QUFDekNMLElBQUFBLE9BQU8sR0FBRyxNQUFJLENBQUNNLGVBQUwsQ0FBcUJOLE9BQXJCLENBQVY7QUFDQUQsSUFBQUEsS0FBSyxDQUFDQyxPQUFOLEdBQWdCQSxPQUFoQjtBQUNBRCxJQUFBQSxLQUFLLENBQUNRLFVBQU4sR0FBbUJQLE9BQU8sQ0FBQ3hDLG1CQUFELENBQTFCO0FBQ0F1QyxJQUFBQSxLQUFLLENBQUNTLE1BQU4sR0FBZVQsS0FBSyxDQUFDUSxVQUFyQjs7QUFDQSxJQUFBLE1BQUksQ0FBQ2xCLElBQUwsQ0FBVSxVQUFWLEVBQXNCVSxLQUF0QjtBQUNELEdBTkQ7QUFRQSxPQUFLVSxXQUFMLEdBQW1CLElBQW5CO0FBRUFWLEVBQUFBLEtBQUssQ0FBQ0ssSUFBTixDQUFXLE9BQVgsRUFBb0I7QUFBQSxXQUFNLE1BQUksQ0FBQ2YsSUFBTCxDQUFVLE9BQVYsQ0FBTjtBQUFBLEdBQXBCO0FBQ0FVLEVBQUFBLEtBQUssQ0FBQ1osRUFBTixDQUFTLE9BQVQsRUFBa0IsVUFBQUMsR0FBRztBQUFBLFdBQUksTUFBSSxDQUFDQyxJQUFMLENBQVUsT0FBVixFQUFtQkQsR0FBbkIsQ0FBSjtBQUFBLEdBQXJCO0FBQ0FXLEVBQUFBLEtBQUssQ0FBQ1osRUFBTixDQUFTLE9BQVQsRUFBa0I7QUFBQSxXQUFNLE1BQUksQ0FBQ0gsT0FBTCxDQUFhMEIsS0FBYixFQUFOO0FBQUEsR0FBbEI7QUFFQSxPQUFLWCxLQUFMLEdBQWFBLEtBQWI7QUFDQSxTQUFPQSxLQUFQO0FBQ0QsQ0FoQ0Q7O0FBa0NBN0IsT0FBTyxDQUFDcUIsU0FBUixDQUFrQmUsZUFBbEIsR0FBb0MsVUFBU04sT0FBVCxFQUFrQjtBQUNwRCxNQUFNVyxJQUFJLEdBQUdULE1BQU0sQ0FBQ1MsSUFBUCxDQUFZWCxPQUFaLENBQWI7QUFDQSxNQUFNWSxZQUFZLEdBQUcsRUFBckI7O0FBQ0EsMkJBQWdCRCxJQUFoQiwyQkFBc0I7QUFBakIsUUFBSUUsR0FBRyxZQUFQO0FBQ0gsUUFBSUMsS0FBSyxHQUFHZCxPQUFPLENBQUNhLEdBQUQsQ0FBbkI7QUFDQUEsSUFBQUEsR0FBRyxHQUFHQSxHQUFHLENBQUNFLFdBQUosRUFBTjs7QUFDQSxZQUFRRixHQUFSO0FBQ0UsV0FBS2pELHVCQUFMO0FBQ0VrRCxRQUFBQSxLQUFLLEdBQUdFLEtBQUssQ0FBQ0MsT0FBTixDQUFjSCxLQUFkLElBQXVCQSxLQUF2QixHQUErQixDQUFDQSxLQUFELENBQXZDO0FBQ0E7O0FBQ0Y7QUFDRTtBQUxKOztBQVFBRixJQUFBQSxZQUFZLENBQUNDLEdBQUQsQ0FBWixHQUFvQkMsS0FBcEI7QUFDRDs7QUFFRCxTQUFPRixZQUFQO0FBQ0QsQ0FsQkQ7O0FBb0JBMUMsT0FBTyxDQUFDcUIsU0FBUixDQUFrQlUsZ0JBQWxCLEdBQXFDLFVBQVNELE9BQVQsRUFBa0I7QUFDckQsTUFBTVcsSUFBSSxHQUFHVCxNQUFNLENBQUNTLElBQVAsQ0FBWVgsT0FBWixDQUFiO0FBQ0EsTUFBTVksWUFBWSxHQUFHLEVBQXJCOztBQUNBLDZCQUFnQkQsSUFBaEIsOEJBQXNCO0FBQWpCLFFBQUlFLEdBQUcsY0FBUDtBQUNILFFBQUlDLEtBQUssR0FBR2QsT0FBTyxDQUFDYSxHQUFELENBQW5CO0FBQ0FBLElBQUFBLEdBQUcsR0FBR0EsR0FBRyxDQUFDRSxXQUFKLEVBQU47O0FBQ0EsWUFBUUYsR0FBUjtBQUNFLFdBQUtsRCxpQkFBTDtBQUNFa0QsUUFBQUEsR0FBRyxHQUFHbkQsc0JBQU47QUFDQW9ELFFBQUFBLEtBQUssR0FBRyx5QkFBeUJJLElBQXpCLENBQThCSixLQUE5QixJQUNKL0QsS0FBSyxDQUFDK0QsS0FBRCxDQUFMLENBQWF2QyxJQURULEdBRUp1QyxLQUZKO0FBR0E7O0FBQ0Y7QUFDRTtBQVJKOztBQVdBRixJQUFBQSxZQUFZLENBQUNDLEdBQUQsQ0FBWixHQUFvQkMsS0FBcEI7QUFDRDs7QUFFRCxTQUFPRixZQUFQO0FBQ0QsQ0FyQkQ7O0FBdUJBMUMsT0FBTyxDQUFDcUIsU0FBUixDQUFrQkwsU0FBbEIsR0FBOEIsVUFBU2lDLElBQVQsRUFBZUwsS0FBZixFQUFzQjtBQUNsRCxPQUFLL0IsUUFBTCxDQUFjb0MsSUFBSSxDQUFDSixXQUFMLEVBQWQsSUFBb0NELEtBQXBDO0FBQ0QsQ0FGRDs7QUFJQTVDLE9BQU8sQ0FBQ3FCLFNBQVIsQ0FBa0I2QixTQUFsQixHQUE4QixVQUFTRCxJQUFULEVBQWU7QUFDM0MsU0FBTyxLQUFLcEMsUUFBTCxDQUFjb0MsSUFBSSxDQUFDSixXQUFMLEVBQWQsQ0FBUDtBQUNELENBRkQ7O0FBSUE3QyxPQUFPLENBQUNxQixTQUFSLENBQWtCOEIsS0FBbEIsR0FBMEIsVUFBU0MsSUFBVCxFQUFlQyxRQUFmLEVBQXlCO0FBQ2pELE1BQU14QixLQUFLLEdBQUcsS0FBS0QsUUFBTCxFQUFkO0FBQ0EsU0FBT0MsS0FBSyxDQUFDc0IsS0FBTixDQUFZQyxJQUFaLEVBQWtCQyxRQUFsQixDQUFQO0FBQ0QsQ0FIRDs7QUFLQXJELE9BQU8sQ0FBQ3FCLFNBQVIsQ0FBa0JpQyxJQUFsQixHQUF5QixVQUFTQyxNQUFULEVBQWlCeEQsT0FBakIsRUFBMEI7QUFDakQsTUFBTThCLEtBQUssR0FBRyxLQUFLRCxRQUFMLEVBQWQ7QUFDQSxTQUFPQyxLQUFLLENBQUN5QixJQUFOLENBQVdDLE1BQVgsRUFBbUJ4RCxPQUFuQixDQUFQO0FBQ0QsQ0FIRDs7QUFLQUMsT0FBTyxDQUFDcUIsU0FBUixDQUFrQm1DLEdBQWxCLEdBQXdCLFVBQVNKLElBQVQsRUFBZTtBQUNyQyxNQUFNdkIsS0FBSyxHQUFHLEtBQUtELFFBQUwsRUFBZDtBQUNBQyxFQUFBQSxLQUFLLENBQUMyQixHQUFOLENBQVVKLElBQVY7QUFDRCxDQUhELEMsQ0FLQTs7O0FBQ0FwRCxPQUFPLENBQUNxQixTQUFSLENBQWtCb0MsS0FBbEIsR0FBMEIsVUFBU0wsSUFBVCxFQUFlO0FBQ3ZDLE1BQU12QixLQUFLLEdBQUcsS0FBS0QsUUFBTCxFQUFkO0FBQ0FDLEVBQUFBLEtBQUssQ0FBQ1csS0FBTixDQUFZN0MsY0FBWjtBQUNBLE9BQUttQixPQUFMLENBQWE0QyxPQUFiO0FBQ0QsQ0FKRDs7QUFNQUMsT0FBTyxDQUFDL0QsV0FBUixHQUFzQkEsV0FBdEIiLCJzb3VyY2VzQ29udGVudCI6WyJjb25zdCBTdHJlYW0gPSByZXF1aXJlKCdzdHJlYW0nKTtcbmNvbnN0IHV0aWwgPSByZXF1aXJlKCd1dGlsJyk7XG5jb25zdCBuZXQgPSByZXF1aXJlKCduZXQnKTtcbmNvbnN0IHRscyA9IHJlcXVpcmUoJ3RscycpO1xuLy8gZXNsaW50LWRpc2FibGUtbmV4dC1saW5lIG5vZGUvbm8tZGVwcmVjYXRlZC1hcGlcbmNvbnN0IHsgcGFyc2UgfSA9IHJlcXVpcmUoJ3VybCcpO1xuY29uc3Qgc2VtdmVyID0gcmVxdWlyZSgnc2VtdmVyJyk7XG5cbmxldCBodHRwMjtcbmlmIChzZW12ZXIuZ3RlKHByb2Nlc3MudmVyc2lvbiwgJ3YxMC4xMC4wJykpIGh0dHAyID0gcmVxdWlyZSgnaHR0cDInKTtcbmVsc2VcbiAgdGhyb3cgbmV3IEVycm9yKCdzdXBlcmFnZW50OiB0aGlzIHZlcnNpb24gb2YgTm9kZS5qcyBkb2VzIG5vdCBzdXBwb3J0IGh0dHAyJyk7XG5cbmNvbnN0IHtcbiAgSFRUUDJfSEVBREVSX1BBVEgsXG4gIEhUVFAyX0hFQURFUl9TVEFUVVMsXG4gIEhUVFAyX0hFQURFUl9NRVRIT0QsXG4gIEhUVFAyX0hFQURFUl9BVVRIT1JJVFksXG4gIEhUVFAyX0hFQURFUl9IT1NULFxuICBIVFRQMl9IRUFERVJfU0VUX0NPT0tJRSxcbiAgTkdIVFRQMl9DQU5DRUxcbn0gPSBodHRwMi5jb25zdGFudHM7XG5cbmZ1bmN0aW9uIHNldFByb3RvY29sKHByb3RvY29sKSB7XG4gIHJldHVybiB7XG4gICAgcmVxdWVzdChvcHRpb25zKSB7XG4gICAgICByZXR1cm4gbmV3IFJlcXVlc3QocHJvdG9jb2wsIG9wdGlvbnMpO1xuICAgIH1cbiAgfTtcbn1cblxuZnVuY3Rpb24gUmVxdWVzdChwcm90b2NvbCwgb3B0aW9ucykge1xuICBTdHJlYW0uY2FsbCh0aGlzKTtcbiAgY29uc3QgZGVmYXVsdFBvcnQgPSBwcm90b2NvbCA9PT0gJ2h0dHBzOicgPyA0NDMgOiA4MDtcbiAgY29uc3QgZGVmYXVsdEhvc3QgPSAnbG9jYWxob3N0JztcbiAgY29uc3QgcG9ydCA9IG9wdGlvbnMucG9ydCB8fCBkZWZhdWx0UG9ydDtcbiAgY29uc3QgaG9zdCA9IG9wdGlvbnMuaG9zdCB8fCBkZWZhdWx0SG9zdDtcblxuICBkZWxldGUgb3B0aW9ucy5wb3J0O1xuICBkZWxldGUgb3B0aW9ucy5ob3N0O1xuXG4gIHRoaXMubWV0aG9kID0gb3B0aW9ucy5tZXRob2Q7XG4gIHRoaXMucGF0aCA9IG9wdGlvbnMucGF0aDtcbiAgdGhpcy5wcm90b2NvbCA9IHByb3RvY29sO1xuICB0aGlzLmhvc3QgPSBob3N0O1xuXG4gIGRlbGV0ZSBvcHRpb25zLm1ldGhvZDtcbiAgZGVsZXRlIG9wdGlvbnMucGF0aDtcblxuICBjb25zdCBzZXNzaW9uT3B0aW9ucyA9IHsgLi4ub3B0aW9ucyB9O1xuICBpZiAob3B0aW9ucy5zb2NrZXRQYXRoKSB7XG4gICAgc2Vzc2lvbk9wdGlvbnMuc29ja2V0UGF0aCA9IG9wdGlvbnMuc29ja2V0UGF0aDtcbiAgICBzZXNzaW9uT3B0aW9ucy5jcmVhdGVDb25uZWN0aW9uID0gdGhpcy5jcmVhdGVVbml4Q29ubmVjdGlvbi5iaW5kKHRoaXMpO1xuICB9XG5cbiAgdGhpcy5faGVhZGVycyA9IHt9O1xuXG4gIGNvbnN0IHNlc3Npb24gPSBodHRwMi5jb25uZWN0KGAke3Byb3RvY29sfS8vJHtob3N0fToke3BvcnR9YCwgc2Vzc2lvbk9wdGlvbnMpO1xuICB0aGlzLnNldEhlYWRlcignaG9zdCcsIGAke2hvc3R9OiR7cG9ydH1gKTtcblxuICBzZXNzaW9uLm9uKCdlcnJvcicsIGVyciA9PiB0aGlzLmVtaXQoJ2Vycm9yJywgZXJyKSk7XG5cbiAgdGhpcy5zZXNzaW9uID0gc2Vzc2lvbjtcbn1cblxuLyoqXG4gKiBJbmhlcml0IGZyb20gYFN0cmVhbWAgKHdoaWNoIGluaGVyaXRzIGZyb20gYEV2ZW50RW1pdHRlcmApLlxuICovXG51dGlsLmluaGVyaXRzKFJlcXVlc3QsIFN0cmVhbSk7XG5cblJlcXVlc3QucHJvdG90eXBlLmNyZWF0ZVVuaXhDb25uZWN0aW9uID0gZnVuY3Rpb24oYXV0aG9yaXR5LCBvcHRpb25zKSB7XG4gIHN3aXRjaCAodGhpcy5wcm90b2NvbCkge1xuICAgIGNhc2UgJ2h0dHA6JzpcbiAgICAgIHJldHVybiBuZXQuY29ubmVjdChvcHRpb25zLnNvY2tldFBhdGgpO1xuICAgIGNhc2UgJ2h0dHBzOic6XG4gICAgICBvcHRpb25zLkFMUE5Qcm90b2NvbHMgPSBbJ2gyJ107XG4gICAgICBvcHRpb25zLnNlcnZlcm5hbWUgPSB0aGlzLmhvc3Q7XG4gICAgICBvcHRpb25zLmFsbG93SGFsZk9wZW4gPSB0cnVlO1xuICAgICAgcmV0dXJuIHRscy5jb25uZWN0KG9wdGlvbnMuc29ja2V0UGF0aCwgb3B0aW9ucyk7XG4gICAgZGVmYXVsdDpcbiAgICAgIHRocm93IG5ldyBFcnJvcignVW5zdXBwb3J0ZWQgcHJvdG9jb2wnLCB0aGlzLnByb3RvY29sKTtcbiAgfVxufTtcblxuLy8gZXNsaW50LWRpc2FibGUtbmV4dC1saW5lIG5vLXVudXNlZC12YXJzXG5SZXF1ZXN0LnByb3RvdHlwZS5zZXROb0RlbGF5ID0gZnVuY3Rpb24oYm9vbCkge1xuICAvLyBXZSBjYW4gbm90IHVzZSBzZXROb0RlbGF5IHdpdGggSFRUUC8yLlxuICAvLyBOb2RlIDEwIGxpbWl0cyBodHRwMnNlc3Npb24uc29ja2V0IG1ldGhvZHMgdG8gb25lcyBzYWZlIHRvIHVzZSB3aXRoIEhUVFAvMi5cbiAgLy8gU2VlIGFsc28gaHR0cHM6Ly9ub2RlanMub3JnL2FwaS9odHRwMi5odG1sI2h0dHAyX2h0dHAyc2Vzc2lvbl9zb2NrZXRcbn07XG5cblJlcXVlc3QucHJvdG90eXBlLmdldEZyYW1lID0gZnVuY3Rpb24oKSB7XG4gIGlmICh0aGlzLmZyYW1lKSB7XG4gICAgcmV0dXJuIHRoaXMuZnJhbWU7XG4gIH1cblxuICBjb25zdCBtZXRob2QgPSB7XG4gICAgW0hUVFAyX0hFQURFUl9QQVRIXTogdGhpcy5wYXRoLFxuICAgIFtIVFRQMl9IRUFERVJfTUVUSE9EXTogdGhpcy5tZXRob2RcbiAgfTtcblxuICBsZXQgaGVhZGVycyA9IHRoaXMubWFwVG9IdHRwMkhlYWRlcih0aGlzLl9oZWFkZXJzKTtcblxuICBoZWFkZXJzID0gT2JqZWN0LmFzc2lnbihoZWFkZXJzLCBtZXRob2QpO1xuXG4gIGNvbnN0IGZyYW1lID0gdGhpcy5zZXNzaW9uLnJlcXVlc3QoaGVhZGVycyk7XG4gIC8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBuby11bnVzZWQtdmFyc1xuICBmcmFtZS5vbmNlKCdyZXNwb25zZScsIChoZWFkZXJzLCBmbGFncykgPT4ge1xuICAgIGhlYWRlcnMgPSB0aGlzLm1hcFRvSHR0cEhlYWRlcihoZWFkZXJzKTtcbiAgICBmcmFtZS5oZWFkZXJzID0gaGVhZGVycztcbiAgICBmcmFtZS5zdGF0dXNDb2RlID0gaGVhZGVyc1tIVFRQMl9IRUFERVJfU1RBVFVTXTtcbiAgICBmcmFtZS5zdGF0dXMgPSBmcmFtZS5zdGF0dXNDb2RlO1xuICAgIHRoaXMuZW1pdCgncmVzcG9uc2UnLCBmcmFtZSk7XG4gIH0pO1xuXG4gIHRoaXMuX2hlYWRlclNlbnQgPSB0cnVlO1xuXG4gIGZyYW1lLm9uY2UoJ2RyYWluJywgKCkgPT4gdGhpcy5lbWl0KCdkcmFpbicpKTtcbiAgZnJhbWUub24oJ2Vycm9yJywgZXJyID0+IHRoaXMuZW1pdCgnZXJyb3InLCBlcnIpKTtcbiAgZnJhbWUub24oJ2Nsb3NlJywgKCkgPT4gdGhpcy5zZXNzaW9uLmNsb3NlKCkpO1xuXG4gIHRoaXMuZnJhbWUgPSBmcmFtZTtcbiAgcmV0dXJuIGZyYW1lO1xufTtcblxuUmVxdWVzdC5wcm90b3R5cGUubWFwVG9IdHRwSGVhZGVyID0gZnVuY3Rpb24oaGVhZGVycykge1xuICBjb25zdCBrZXlzID0gT2JqZWN0LmtleXMoaGVhZGVycyk7XG4gIGNvbnN0IGh0dHAySGVhZGVycyA9IHt9O1xuICBmb3IgKGxldCBrZXkgb2Yga2V5cykge1xuICAgIGxldCB2YWx1ZSA9IGhlYWRlcnNba2V5XTtcbiAgICBrZXkgPSBrZXkudG9Mb3dlckNhc2UoKTtcbiAgICBzd2l0Y2ggKGtleSkge1xuICAgICAgY2FzZSBIVFRQMl9IRUFERVJfU0VUX0NPT0tJRTpcbiAgICAgICAgdmFsdWUgPSBBcnJheS5pc0FycmF5KHZhbHVlKSA/IHZhbHVlIDogW3ZhbHVlXTtcbiAgICAgICAgYnJlYWs7XG4gICAgICBkZWZhdWx0OlxuICAgICAgICBicmVhaztcbiAgICB9XG5cbiAgICBodHRwMkhlYWRlcnNba2V5XSA9IHZhbHVlO1xuICB9XG5cbiAgcmV0dXJuIGh0dHAySGVhZGVycztcbn07XG5cblJlcXVlc3QucHJvdG90eXBlLm1hcFRvSHR0cDJIZWFkZXIgPSBmdW5jdGlvbihoZWFkZXJzKSB7XG4gIGNvbnN0IGtleXMgPSBPYmplY3Qua2V5cyhoZWFkZXJzKTtcbiAgY29uc3QgaHR0cDJIZWFkZXJzID0ge307XG4gIGZvciAobGV0IGtleSBvZiBrZXlzKSB7XG4gICAgbGV0IHZhbHVlID0gaGVhZGVyc1trZXldO1xuICAgIGtleSA9IGtleS50b0xvd2VyQ2FzZSgpO1xuICAgIHN3aXRjaCAoa2V5KSB7XG4gICAgICBjYXNlIEhUVFAyX0hFQURFUl9IT1NUOlxuICAgICAgICBrZXkgPSBIVFRQMl9IRUFERVJfQVVUSE9SSVRZO1xuICAgICAgICB2YWx1ZSA9IC9eaHR0cDpcXC9cXC98Xmh0dHBzOlxcL1xcLy8udGVzdCh2YWx1ZSlcbiAgICAgICAgICA/IHBhcnNlKHZhbHVlKS5ob3N0XG4gICAgICAgICAgOiB2YWx1ZTtcbiAgICAgICAgYnJlYWs7XG4gICAgICBkZWZhdWx0OlxuICAgICAgICBicmVhaztcbiAgICB9XG5cbiAgICBodHRwMkhlYWRlcnNba2V5XSA9IHZhbHVlO1xuICB9XG5cbiAgcmV0dXJuIGh0dHAySGVhZGVycztcbn07XG5cblJlcXVlc3QucHJvdG90eXBlLnNldEhlYWRlciA9IGZ1bmN0aW9uKG5hbWUsIHZhbHVlKSB7XG4gIHRoaXMuX2hlYWRlcnNbbmFtZS50b0xvd2VyQ2FzZSgpXSA9IHZhbHVlO1xufTtcblxuUmVxdWVzdC5wcm90b3R5cGUuZ2V0SGVhZGVyID0gZnVuY3Rpb24obmFtZSkge1xuICByZXR1cm4gdGhpcy5faGVhZGVyc1tuYW1lLnRvTG93ZXJDYXNlKCldO1xufTtcblxuUmVxdWVzdC5wcm90b3R5cGUud3JpdGUgPSBmdW5jdGlvbihkYXRhLCBlbmNvZGluZykge1xuICBjb25zdCBmcmFtZSA9IHRoaXMuZ2V0RnJhbWUoKTtcbiAgcmV0dXJuIGZyYW1lLndyaXRlKGRhdGEsIGVuY29kaW5nKTtcbn07XG5cblJlcXVlc3QucHJvdG90eXBlLnBpcGUgPSBmdW5jdGlvbihzdHJlYW0sIG9wdGlvbnMpIHtcbiAgY29uc3QgZnJhbWUgPSB0aGlzLmdldEZyYW1lKCk7XG4gIHJldHVybiBmcmFtZS5waXBlKHN0cmVhbSwgb3B0aW9ucyk7XG59O1xuXG5SZXF1ZXN0LnByb3RvdHlwZS5lbmQgPSBmdW5jdGlvbihkYXRhKSB7XG4gIGNvbnN0IGZyYW1lID0gdGhpcy5nZXRGcmFtZSgpO1xuICBmcmFtZS5lbmQoZGF0YSk7XG59O1xuXG4vLyBlc2xpbnQtZGlzYWJsZS1uZXh0LWxpbmUgbm8tdW51c2VkLXZhcnNcblJlcXVlc3QucHJvdG90eXBlLmFib3J0ID0gZnVuY3Rpb24oZGF0YSkge1xuICBjb25zdCBmcmFtZSA9IHRoaXMuZ2V0RnJhbWUoKTtcbiAgZnJhbWUuY2xvc2UoTkdIVFRQMl9DQU5DRUwpO1xuICB0aGlzLnNlc3Npb24uZGVzdHJveSgpO1xufTtcblxuZXhwb3J0cy5zZXRQcm90b2NvbCA9IHNldFByb3RvY29sO1xuIl19 \ No newline at end of file diff --git a/node_modules/superagent/lib/node/index.js b/node_modules/superagent/lib/node/index.js new file mode 100644 index 000000000..3ebde21ab --- /dev/null +++ b/node_modules/superagent/lib/node/index.js @@ -0,0 +1,1376 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Module dependencies. + */ +// eslint-disable-next-line node/no-deprecated-api +var _require = require('url'), + parse = _require.parse, + format = _require.format, + resolve = _require.resolve; + +var Stream = require('stream'); + +var https = require('https'); + +var http = require('http'); + +var fs = require('fs'); + +var zlib = require('zlib'); + +var util = require('util'); + +var qs = require('qs'); + +var mime = require('mime'); + +var methods = require('methods'); + +var FormData = require('form-data'); + +var formidable = require('formidable'); + +var debug = require('debug')('superagent'); + +var CookieJar = require('cookiejar'); + +var semver = require('semver'); + +var safeStringify = require('fast-safe-stringify'); + +var utils = require('../utils'); + +var RequestBase = require('../request-base'); + +var _require2 = require('./unzip'), + unzip = _require2.unzip; + +var Response = require('./response'); + +var http2; +if (semver.gte(process.version, 'v10.10.0')) http2 = require('./http2wrapper'); + +function request(method, url) { + // callback + if (typeof url === 'function') { + return new exports.Request('GET', method).end(url); + } // url first + + + if (arguments.length === 1) { + return new exports.Request('GET', method); + } + + return new exports.Request(method, url); +} + +module.exports = request; +exports = module.exports; +/** + * Expose `Request`. + */ + +exports.Request = Request; +/** + * Expose the agent function + */ + +exports.agent = require('./agent'); +/** + * Noop. + */ + +function noop() {} +/** + * Expose `Response`. + */ + + +exports.Response = Response; +/** + * Define "form" mime type. + */ + +mime.define({ + 'application/x-www-form-urlencoded': ['form', 'urlencoded', 'form-data'] +}, true); +/** + * Protocol map. + */ + +exports.protocols = { + 'http:': http, + 'https:': https, + 'http2:': http2 +}; +/** + * Default serialization map. + * + * superagent.serialize['application/xml'] = function(obj){ + * return 'generated xml here'; + * }; + * + */ + +exports.serialize = { + 'application/x-www-form-urlencoded': qs.stringify, + 'application/json': safeStringify +}; +/** + * Default parsers. + * + * superagent.parse['application/xml'] = function(res, fn){ + * fn(null, res); + * }; + * + */ + +exports.parse = require('./parsers'); +/** + * Default buffering map. Can be used to set certain + * response types to buffer/not buffer. + * + * superagent.buffer['application/xml'] = true; + */ + +exports.buffer = {}; +/** + * Initialize internal header tracking properties on a request instance. + * + * @param {Object} req the instance + * @api private + */ + +function _initHeaders(req) { + req._header = {// coerces header names to lowercase + }; + req.header = {// preserves header name case + }; +} +/** + * Initialize a new `Request` with the given `method` and `url`. + * + * @param {String} method + * @param {String|Object} url + * @api public + */ + + +function Request(method, url) { + Stream.call(this); + if (typeof url !== 'string') url = format(url); + this._enableHttp2 = Boolean(process.env.HTTP2_TEST); // internal only + + this._agent = false; + this._formData = null; + this.method = method; + this.url = url; + + _initHeaders(this); + + this.writable = true; + this._redirects = 0; + this.redirects(method === 'HEAD' ? 0 : 5); + this.cookies = ''; + this.qs = {}; + this._query = []; + this.qsRaw = this._query; // Unused, for backwards compatibility only + + this._redirectList = []; + this._streamRequest = false; + this.once('end', this.clearTimeout.bind(this)); +} +/** + * Inherit from `Stream` (which inherits from `EventEmitter`). + * Mixin `RequestBase`. + */ + + +util.inherits(Request, Stream); // eslint-disable-next-line new-cap + +RequestBase(Request.prototype); +/** + * Enable or Disable http2. + * + * Enable http2. + * + * ``` js + * request.get('http://localhost/') + * .http2() + * .end(callback); + * + * request.get('http://localhost/') + * .http2(true) + * .end(callback); + * ``` + * + * Disable http2. + * + * ``` js + * request = request.http2(); + * request.get('http://localhost/') + * .http2(false) + * .end(callback); + * ``` + * + * @param {Boolean} enable + * @return {Request} for chaining + * @api public + */ + +Request.prototype.http2 = function (bool) { + if (exports.protocols['http2:'] === undefined) { + throw new Error('superagent: this version of Node.js does not support http2'); + } + + this._enableHttp2 = bool === undefined ? true : bool; + return this; +}; +/** + * Queue the given `file` as an attachment to the specified `field`, + * with optional `options` (or filename). + * + * ``` js + * request.post('http://localhost/upload') + * .attach('field', Buffer.from('Hello world'), 'hello.html') + * .end(callback); + * ``` + * + * A filename may also be used: + * + * ``` js + * request.post('http://localhost/upload') + * .attach('files', 'image.jpg') + * .end(callback); + * ``` + * + * @param {String} field + * @param {String|fs.ReadStream|Buffer} file + * @param {String|Object} options + * @return {Request} for chaining + * @api public + */ + + +Request.prototype.attach = function (field, file, options) { + if (file) { + if (this._data) { + throw new Error("superagent can't mix .send() and .attach()"); + } + + var o = options || {}; + + if (typeof options === 'string') { + o = { + filename: options + }; + } + + if (typeof file === 'string') { + if (!o.filename) o.filename = file; + debug('creating `fs.ReadStream` instance for file: %s', file); + file = fs.createReadStream(file); + } else if (!o.filename && file.path) { + o.filename = file.path; + } + + this._getFormData().append(field, file, o); + } + + return this; +}; + +Request.prototype._getFormData = function () { + var _this = this; + + if (!this._formData) { + this._formData = new FormData(); + + this._formData.on('error', function (err) { + debug('FormData error', err); + + if (_this.called) { + // The request has already finished and the callback was called. + // Silently ignore the error. + return; + } + + _this.callback(err); + + _this.abort(); + }); + } + + return this._formData; +}; +/** + * Gets/sets the `Agent` to use for this HTTP request. The default (if this + * function is not called) is to opt out of connection pooling (`agent: false`). + * + * @param {http.Agent} agent + * @return {http.Agent} + * @api public + */ + + +Request.prototype.agent = function (agent) { + if (arguments.length === 0) return this._agent; + this._agent = agent; + return this; +}; +/** + * Set _Content-Type_ response header passed through `mime.getType()`. + * + * Examples: + * + * request.post('/') + * .type('xml') + * .send(xmlstring) + * .end(callback); + * + * request.post('/') + * .type('json') + * .send(jsonstring) + * .end(callback); + * + * request.post('/') + * .type('application/json') + * .send(jsonstring) + * .end(callback); + * + * @param {String} type + * @return {Request} for chaining + * @api public + */ + + +Request.prototype.type = function (type) { + return this.set('Content-Type', type.includes('/') ? type : mime.getType(type)); +}; +/** + * Set _Accept_ response header passed through `mime.getType()`. + * + * Examples: + * + * superagent.types.json = 'application/json'; + * + * request.get('/agent') + * .accept('json') + * .end(callback); + * + * request.get('/agent') + * .accept('application/json') + * .end(callback); + * + * @param {String} accept + * @return {Request} for chaining + * @api public + */ + + +Request.prototype.accept = function (type) { + return this.set('Accept', type.includes('/') ? type : mime.getType(type)); +}; +/** + * Add query-string `val`. + * + * Examples: + * + * request.get('/shoes') + * .query('size=10') + * .query({ color: 'blue' }) + * + * @param {Object|String} val + * @return {Request} for chaining + * @api public + */ + + +Request.prototype.query = function (val) { + if (typeof val === 'string') { + this._query.push(val); + } else { + Object.assign(this.qs, val); + } + + return this; +}; +/** + * Write raw `data` / `encoding` to the socket. + * + * @param {Buffer|String} data + * @param {String} encoding + * @return {Boolean} + * @api public + */ + + +Request.prototype.write = function (data, encoding) { + var req = this.request(); + + if (!this._streamRequest) { + this._streamRequest = true; + } + + return req.write(data, encoding); +}; +/** + * Pipe the request body to `stream`. + * + * @param {Stream} stream + * @param {Object} options + * @return {Stream} + * @api public + */ + + +Request.prototype.pipe = function (stream, options) { + this.piped = true; // HACK... + + this.buffer(false); + this.end(); + return this._pipeContinue(stream, options); +}; + +Request.prototype._pipeContinue = function (stream, options) { + var _this2 = this; + + this.req.once('response', function (res) { + // redirect + if (isRedirect(res.statusCode) && _this2._redirects++ !== _this2._maxRedirects) { + return _this2._redirect(res) === _this2 ? _this2._pipeContinue(stream, options) : undefined; + } + + _this2.res = res; + + _this2._emitResponse(); + + if (_this2._aborted) return; + + if (_this2._shouldUnzip(res)) { + var unzipObj = zlib.createUnzip(); + unzipObj.on('error', function (err) { + if (err && err.code === 'Z_BUF_ERROR') { + // unexpected end of file is ignored by browsers and curl + stream.emit('end'); + return; + } + + stream.emit('error', err); + }); + res.pipe(unzipObj).pipe(stream, options); + } else { + res.pipe(stream, options); + } + + res.once('end', function () { + _this2.emit('end'); + }); + }); + return stream; +}; +/** + * Enable / disable buffering. + * + * @return {Boolean} [val] + * @return {Request} for chaining + * @api public + */ + + +Request.prototype.buffer = function (val) { + this._buffer = val !== false; + return this; +}; +/** + * Redirect to `url + * + * @param {IncomingMessage} res + * @return {Request} for chaining + * @api private + */ + + +Request.prototype._redirect = function (res) { + var url = res.headers.location; + + if (!url) { + return this.callback(new Error('No location header for redirect'), res); + } + + debug('redirect %s -> %s', this.url, url); // location + + url = resolve(this.url, url); // ensure the response is being consumed + // this is required for Node v0.10+ + + res.resume(); + var headers = this.req.getHeaders ? this.req.getHeaders() : this.req._headers; + var changesOrigin = parse(url).host !== parse(this.url).host; // implementation of 302 following defacto standard + + if (res.statusCode === 301 || res.statusCode === 302) { + // strip Content-* related fields + // in case of POST etc + headers = utils.cleanHeader(headers, changesOrigin); // force GET + + this.method = this.method === 'HEAD' ? 'HEAD' : 'GET'; // clear data + + this._data = null; + } // 303 is always GET + + + if (res.statusCode === 303) { + // strip Content-* related fields + // in case of POST etc + headers = utils.cleanHeader(headers, changesOrigin); // force method + + this.method = 'GET'; // clear data + + this._data = null; + } // 307 preserves method + // 308 preserves method + + + delete headers.host; + delete this.req; + delete this._formData; // remove all add header except User-Agent + + _initHeaders(this); // redirect + + + this._endCalled = false; + this.url = url; + this.qs = {}; + this._query.length = 0; + this.set(headers); + this.emit('redirect', res); + + this._redirectList.push(this.url); + + this.end(this._callback); + return this; +}; +/** + * Set Authorization field value with `user` and `pass`. + * + * Examples: + * + * .auth('tobi', 'learnboost') + * .auth('tobi:learnboost') + * .auth('tobi') + * .auth(accessToken, { type: 'bearer' }) + * + * @param {String} user + * @param {String} [pass] + * @param {Object} [options] options with authorization type 'basic' or 'bearer' ('basic' is default) + * @return {Request} for chaining + * @api public + */ + + +Request.prototype.auth = function (user, pass, options) { + if (arguments.length === 1) pass = ''; + + if (_typeof(pass) === 'object' && pass !== null) { + // pass is optional and can be replaced with options + options = pass; + pass = ''; + } + + if (!options) { + options = { + type: 'basic' + }; + } + + var encoder = function encoder(string) { + return Buffer.from(string).toString('base64'); + }; + + return this._auth(user, pass, options, encoder); +}; +/** + * Set the certificate authority option for https request. + * + * @param {Buffer | Array} cert + * @return {Request} for chaining + * @api public + */ + + +Request.prototype.ca = function (cert) { + this._ca = cert; + return this; +}; +/** + * Set the client certificate key option for https request. + * + * @param {Buffer | String} cert + * @return {Request} for chaining + * @api public + */ + + +Request.prototype.key = function (cert) { + this._key = cert; + return this; +}; +/** + * Set the key, certificate, and CA certs of the client in PFX or PKCS12 format. + * + * @param {Buffer | String} cert + * @return {Request} for chaining + * @api public + */ + + +Request.prototype.pfx = function (cert) { + if (_typeof(cert) === 'object' && !Buffer.isBuffer(cert)) { + this._pfx = cert.pfx; + this._passphrase = cert.passphrase; + } else { + this._pfx = cert; + } + + return this; +}; +/** + * Set the client certificate option for https request. + * + * @param {Buffer | String} cert + * @return {Request} for chaining + * @api public + */ + + +Request.prototype.cert = function (cert) { + this._cert = cert; + return this; +}; +/** + * Do not reject expired or invalid TLS certs. + * sets `rejectUnauthorized=true`. Be warned that this allows MITM attacks. + * + * @return {Request} for chaining + * @api public + */ + + +Request.prototype.disableTLSCerts = function () { + this._disableTLSCerts = true; + return this; +}; +/** + * Return an http[s] request. + * + * @return {OutgoingMessage} + * @api private + */ +// eslint-disable-next-line complexity + + +Request.prototype.request = function () { + var _this3 = this; + + if (this.req) return this.req; + var options = {}; + + try { + var query = qs.stringify(this.qs, { + indices: false, + strictNullHandling: true + }); + + if (query) { + this.qs = {}; + + this._query.push(query); + } + + this._finalizeQueryString(); + } catch (err) { + return this.emit('error', err); + } + + var url = this.url; + var retries = this._retries; // Capture backticks as-is from the final query string built above. + // Note: this'll only find backticks entered in req.query(String) + // calls, because qs.stringify unconditionally encodes backticks. + + var queryStringBackticks; + + if (url.includes('`')) { + var queryStartIndex = url.indexOf('?'); + + if (queryStartIndex !== -1) { + var queryString = url.slice(queryStartIndex + 1); + queryStringBackticks = queryString.match(/`|%60/g); + } + } // default to http:// + + + if (url.indexOf('http') !== 0) url = "http://".concat(url); + url = parse(url); // See https://github.com/visionmedia/superagent/issues/1367 + + if (queryStringBackticks) { + var i = 0; + url.query = url.query.replace(/%60/g, function () { + return queryStringBackticks[i++]; + }); + url.search = "?".concat(url.query); + url.path = url.pathname + url.search; + } // support unix sockets + + + if (/^https?\+unix:/.test(url.protocol) === true) { + // get the protocol + url.protocol = "".concat(url.protocol.split('+')[0], ":"); // get the socket, path + + var unixParts = url.path.match(/^([^/]+)(.+)$/); + options.socketPath = unixParts[1].replace(/%2F/g, '/'); + url.path = unixParts[2]; + } // Override IP address of a hostname + + + if (this._connectOverride) { + var _url = url, + hostname = _url.hostname; + var match = hostname in this._connectOverride ? this._connectOverride[hostname] : this._connectOverride['*']; + + if (match) { + // backup the real host + if (!this._header.host) { + this.set('host', url.host); + } + + var newHost; + var newPort; + + if (_typeof(match) === 'object') { + newHost = match.host; + newPort = match.port; + } else { + newHost = match; + newPort = url.port; + } // wrap [ipv6] + + + url.host = /:/.test(newHost) ? "[".concat(newHost, "]") : newHost; + + if (newPort) { + url.host += ":".concat(newPort); + url.port = newPort; + } + + url.hostname = newHost; + } + } // options + + + options.method = this.method; + options.port = url.port; + options.path = url.path; + options.host = url.hostname; + options.ca = this._ca; + options.key = this._key; + options.pfx = this._pfx; + options.cert = this._cert; + options.passphrase = this._passphrase; + options.agent = this._agent; + options.rejectUnauthorized = typeof this._disableTLSCerts === 'boolean' ? !this._disableTLSCerts : process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0'; // Allows request.get('https://1.2.3.4/').set('Host', 'example.com') + + if (this._header.host) { + options.servername = this._header.host.replace(/:\d+$/, ''); + } + + if (this._trustLocalhost && /^(?:localhost|127\.0\.0\.\d+|(0*:)+:0*1)$/.test(url.hostname)) { + options.rejectUnauthorized = false; + } // initiate request + + + var mod = this._enableHttp2 ? exports.protocols['http2:'].setProtocol(url.protocol) : exports.protocols[url.protocol]; // request + + this.req = mod.request(options); + var req = this.req; // set tcp no delay + + req.setNoDelay(true); + + if (options.method !== 'HEAD') { + req.setHeader('Accept-Encoding', 'gzip, deflate'); + } + + this.protocol = url.protocol; + this.host = url.host; // expose events + + req.once('drain', function () { + _this3.emit('drain'); + }); + req.on('error', function (err) { + // flag abortion here for out timeouts + // because node will emit a faux-error "socket hang up" + // when request is aborted before a connection is made + if (_this3._aborted) return; // if not the same, we are in the **old** (cancelled) request, + // so need to continue (same as for above) + + if (_this3._retries !== retries) return; // if we've received a response then we don't want to let + // an error in the request blow up the response + + if (_this3.response) return; + + _this3.callback(err); + }); // auth + + if (url.auth) { + var auth = url.auth.split(':'); + this.auth(auth[0], auth[1]); + } + + if (this.username && this.password) { + this.auth(this.username, this.password); + } + + for (var key in this.header) { + if (Object.prototype.hasOwnProperty.call(this.header, key)) req.setHeader(key, this.header[key]); + } // add cookies + + + if (this.cookies) { + if (Object.prototype.hasOwnProperty.call(this._header, 'cookie')) { + // merge + var tmpJar = new CookieJar.CookieJar(); + tmpJar.setCookies(this._header.cookie.split(';')); + tmpJar.setCookies(this.cookies.split(';')); + req.setHeader('Cookie', tmpJar.getCookies(CookieJar.CookieAccessInfo.All).toValueString()); + } else { + req.setHeader('Cookie', this.cookies); + } + } + + return req; +}; +/** + * Invoke the callback with `err` and `res` + * and handle arity check. + * + * @param {Error} err + * @param {Response} res + * @api private + */ + + +Request.prototype.callback = function (err, res) { + if (this._shouldRetry(err, res)) { + return this._retry(); + } // Avoid the error which is emitted from 'socket hang up' to cause the fn undefined error on JS runtime. + + + var fn = this._callback || noop; + this.clearTimeout(); + if (this.called) return console.warn('superagent: double callback bug'); + this.called = true; + + if (!err) { + try { + if (!this._isResponseOK(res)) { + var msg = 'Unsuccessful HTTP response'; + + if (res) { + msg = http.STATUS_CODES[res.status] || msg; + } + + err = new Error(msg); + err.status = res ? res.status : undefined; + } + } catch (err_) { + err = err_; + } + } // It's important that the callback is called outside try/catch + // to avoid double callback + + + if (!err) { + return fn(null, res); + } + + err.response = res; + if (this._maxRetries) err.retries = this._retries - 1; // only emit error event if there is a listener + // otherwise we assume the callback to `.end()` will get the error + + if (err && this.listeners('error').length > 0) { + this.emit('error', err); + } + + fn(err, res); +}; +/** + * Check if `obj` is a host object, + * + * @param {Object} obj host object + * @return {Boolean} is a host object + * @api private + */ + + +Request.prototype._isHost = function (obj) { + return Buffer.isBuffer(obj) || obj instanceof Stream || obj instanceof FormData; +}; +/** + * Initiate request, invoking callback `fn(err, res)` + * with an instanceof `Response`. + * + * @param {Function} fn + * @return {Request} for chaining + * @api public + */ + + +Request.prototype._emitResponse = function (body, files) { + var response = new Response(this); + this.response = response; + response.redirects = this._redirectList; + + if (undefined !== body) { + response.body = body; + } + + response.files = files; + + if (this._endCalled) { + response.pipe = function () { + throw new Error("end() has already been called, so it's too late to start piping"); + }; + } + + this.emit('response', response); + return response; +}; + +Request.prototype.end = function (fn) { + this.request(); + debug('%s %s', this.method, this.url); + + if (this._endCalled) { + throw new Error('.end() was called twice. This is not supported in superagent'); + } + + this._endCalled = true; // store callback + + this._callback = fn || noop; + + this._end(); +}; + +Request.prototype._end = function () { + var _this4 = this; + + if (this._aborted) return this.callback(new Error('The request has been aborted even before .end() was called')); + var data = this._data; + var req = this.req; + var method = this.method; + + this._setTimeouts(); // body + + + if (method !== 'HEAD' && !req._headerSent) { + // serialize stuff + if (typeof data !== 'string') { + var contentType = req.getHeader('Content-Type'); // Parse out just the content type from the header (ignore the charset) + + if (contentType) contentType = contentType.split(';')[0]; + var serialize = this._serializer || exports.serialize[contentType]; + + if (!serialize && isJSON(contentType)) { + serialize = exports.serialize['application/json']; + } + + if (serialize) data = serialize(data); + } // content-length + + + if (data && !req.getHeader('Content-Length')) { + req.setHeader('Content-Length', Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data)); + } + } // response + // eslint-disable-next-line complexity + + + req.once('response', function (res) { + debug('%s %s -> %s', _this4.method, _this4.url, res.statusCode); + + if (_this4._responseTimeoutTimer) { + clearTimeout(_this4._responseTimeoutTimer); + } + + if (_this4.piped) { + return; + } + + var max = _this4._maxRedirects; + var mime = utils.type(res.headers['content-type'] || '') || 'text/plain'; + var type = mime.split('/')[0]; + var multipart = type === 'multipart'; + var redirect = isRedirect(res.statusCode); + var responseType = _this4._responseType; + _this4.res = res; // redirect + + if (redirect && _this4._redirects++ !== max) { + return _this4._redirect(res); + } + + if (_this4.method === 'HEAD') { + _this4.emit('end'); + + _this4.callback(null, _this4._emitResponse()); + + return; + } // zlib support + + + if (_this4._shouldUnzip(res)) { + unzip(req, res); + } + + var buffer = _this4._buffer; + + if (buffer === undefined && mime in exports.buffer) { + buffer = Boolean(exports.buffer[mime]); + } + + var parser = _this4._parser; + + if (undefined === buffer) { + if (parser) { + console.warn("A custom superagent parser has been set, but buffering strategy for the parser hasn't been configured. Call `req.buffer(true or false)` or set `superagent.buffer[mime] = true or false`"); + buffer = true; + } + } + + if (!parser) { + if (responseType) { + parser = exports.parse.image; // It's actually a generic Buffer + + buffer = true; + } else if (multipart) { + var form = new formidable.IncomingForm(); + parser = form.parse.bind(form); + buffer = true; + } else if (isImageOrVideo(mime)) { + parser = exports.parse.image; + buffer = true; // For backwards-compatibility buffering default is ad-hoc MIME-dependent + } else if (exports.parse[mime]) { + parser = exports.parse[mime]; + } else if (type === 'text') { + parser = exports.parse.text; + buffer = buffer !== false; // everyone wants their own white-labeled json + } else if (isJSON(mime)) { + parser = exports.parse['application/json']; + buffer = buffer !== false; + } else if (buffer) { + parser = exports.parse.text; + } else if (undefined === buffer) { + parser = exports.parse.image; // It's actually a generic Buffer + + buffer = true; + } + } // by default only buffer text/*, json and messed up thing from hell + + + if (undefined === buffer && isText(mime) || isJSON(mime)) { + buffer = true; + } + + _this4._resBuffered = buffer; + var parserHandlesEnd = false; + + if (buffer) { + // Protectiona against zip bombs and other nuisance + var responseBytesLeft = _this4._maxResponseSize || 200000000; + res.on('data', function (buf) { + responseBytesLeft -= buf.byteLength || buf.length; + + if (responseBytesLeft < 0) { + // This will propagate through error event + var err = new Error('Maximum response size reached'); + err.code = 'ETOOLARGE'; // Parsers aren't required to observe error event, + // so would incorrectly report success + + parserHandlesEnd = false; // Will emit error event + + res.destroy(err); + } + }); + } + + if (parser) { + try { + // Unbuffered parsers are supposed to emit response early, + // which is weird BTW, because response.body won't be there. + parserHandlesEnd = buffer; + parser(res, function (err, obj, files) { + if (_this4.timedout) { + // Timeout has already handled all callbacks + return; + } // Intentional (non-timeout) abort is supposed to preserve partial response, + // even if it doesn't parse. + + + if (err && !_this4._aborted) { + return _this4.callback(err); + } + + if (parserHandlesEnd) { + _this4.emit('end'); + + _this4.callback(null, _this4._emitResponse(obj, files)); + } + }); + } catch (err) { + _this4.callback(err); + + return; + } + } + + _this4.res = res; // unbuffered + + if (!buffer) { + debug('unbuffered %s %s', _this4.method, _this4.url); + + _this4.callback(null, _this4._emitResponse()); + + if (multipart) return; // allow multipart to handle end event + + res.once('end', function () { + debug('end %s %s', _this4.method, _this4.url); + + _this4.emit('end'); + }); + return; + } // terminating events + + + res.once('error', function (err) { + parserHandlesEnd = false; + + _this4.callback(err, null); + }); + if (!parserHandlesEnd) res.once('end', function () { + debug('end %s %s', _this4.method, _this4.url); // TODO: unless buffering emit earlier to stream + + _this4.emit('end'); + + _this4.callback(null, _this4._emitResponse()); + }); + }); + this.emit('request', this); + + var getProgressMonitor = function getProgressMonitor() { + var lengthComputable = true; + var total = req.getHeader('Content-Length'); + var loaded = 0; + var progress = new Stream.Transform(); + + progress._transform = function (chunk, encoding, cb) { + loaded += chunk.length; + + _this4.emit('progress', { + direction: 'upload', + lengthComputable: lengthComputable, + loaded: loaded, + total: total + }); + + cb(null, chunk); + }; + + return progress; + }; + + var bufferToChunks = function bufferToChunks(buffer) { + var chunkSize = 16 * 1024; // default highWaterMark value + + var chunking = new Stream.Readable(); + var totalLength = buffer.length; + var remainder = totalLength % chunkSize; + var cutoff = totalLength - remainder; + + for (var i = 0; i < cutoff; i += chunkSize) { + var chunk = buffer.slice(i, i + chunkSize); + chunking.push(chunk); + } + + if (remainder > 0) { + var remainderBuffer = buffer.slice(-remainder); + chunking.push(remainderBuffer); + } + + chunking.push(null); // no more data + + return chunking; + }; // if a FormData instance got created, then we send that as the request body + + + var formData = this._formData; + + if (formData) { + // set headers + var headers = formData.getHeaders(); + + for (var i in headers) { + if (Object.prototype.hasOwnProperty.call(headers, i)) { + debug('setting FormData header: "%s: %s"', i, headers[i]); + req.setHeader(i, headers[i]); + } + } // attempt to get "Content-Length" header + // eslint-disable-next-line handle-callback-err + + + formData.getLength(function (err, length) { + // TODO: Add chunked encoding when no length (if err) + debug('got FormData Content-Length: %s', length); + + if (typeof length === 'number') { + req.setHeader('Content-Length', length); + } + + formData.pipe(getProgressMonitor()).pipe(req); + }); + } else if (Buffer.isBuffer(data)) { + bufferToChunks(data).pipe(getProgressMonitor()).pipe(req); + } else { + req.end(data); + } +}; // Check whether response has a non-0-sized gzip-encoded body + + +Request.prototype._shouldUnzip = function (res) { + if (res.statusCode === 204 || res.statusCode === 304) { + // These aren't supposed to have any body + return false; + } // header content is a string, and distinction between 0 and no information is crucial + + + if (res.headers['content-length'] === '0') { + // We know that the body is empty (unfortunately, this check does not cover chunked encoding) + return false; + } // console.log(res); + + + return /^\s*(?:deflate|gzip)\s*$/.test(res.headers['content-encoding']); +}; +/** + * Overrides DNS for selected hostnames. Takes object mapping hostnames to IP addresses. + * + * When making a request to a URL with a hostname exactly matching a key in the object, + * use the given IP address to connect, instead of using DNS to resolve the hostname. + * + * A special host `*` matches every hostname (keep redirects in mind!) + * + * request.connect({ + * 'test.example.com': '127.0.0.1', + * 'ipv6.example.com': '::1', + * }) + */ + + +Request.prototype.connect = function (connectOverride) { + if (typeof connectOverride === 'string') { + this._connectOverride = { + '*': connectOverride + }; + } else if (_typeof(connectOverride) === 'object') { + this._connectOverride = connectOverride; + } else { + this._connectOverride = undefined; + } + + return this; +}; + +Request.prototype.trustLocalhost = function (toggle) { + this._trustLocalhost = toggle === undefined ? true : toggle; + return this; +}; // generate HTTP verb methods + + +if (!methods.includes('del')) { + // create a copy so we don't cause conflicts with + // other packages using the methods package and + // npm 3.x + methods = methods.slice(0); + methods.push('del'); +} + +methods.forEach(function (method) { + var name = method; + method = method === 'del' ? 'delete' : method; + method = method.toUpperCase(); + + request[name] = function (url, data, fn) { + var req = request(method, url); + + if (typeof data === 'function') { + fn = data; + data = null; + } + + if (data) { + if (method === 'GET' || method === 'HEAD') { + req.query(data); + } else { + req.send(data); + } + } + + if (fn) req.end(fn); + return req; + }; +}); +/** + * Check if `mime` is text and should be buffered. + * + * @param {String} mime + * @return {Boolean} + * @api public + */ + +function isText(mime) { + var parts = mime.split('/'); + var type = parts[0]; + var subtype = parts[1]; + return type === 'text' || subtype === 'x-www-form-urlencoded'; +} + +function isImageOrVideo(mime) { + var type = mime.split('/')[0]; + return type === 'image' || type === 'video'; +} +/** + * Check if `mime` is json or has +json structured syntax suffix. + * + * @param {String} mime + * @return {Boolean} + * @api private + */ + + +function isJSON(mime) { + // should match /json or +json + // but not /json-seq + return /[/+]json($|[^-\w])/.test(mime); +} +/** + * Check if we should follow the redirect `code`. + * + * @param {Number} code + * @return {Boolean} + * @api private + */ + + +function isRedirect(code) { + return [301, 302, 303, 305, 307, 308].includes(code); +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9ub2RlL2luZGV4LmpzIl0sIm5hbWVzIjpbInJlcXVpcmUiLCJwYXJzZSIsImZvcm1hdCIsInJlc29sdmUiLCJTdHJlYW0iLCJodHRwcyIsImh0dHAiLCJmcyIsInpsaWIiLCJ1dGlsIiwicXMiLCJtaW1lIiwibWV0aG9kcyIsIkZvcm1EYXRhIiwiZm9ybWlkYWJsZSIsImRlYnVnIiwiQ29va2llSmFyIiwic2VtdmVyIiwic2FmZVN0cmluZ2lmeSIsInV0aWxzIiwiUmVxdWVzdEJhc2UiLCJ1bnppcCIsIlJlc3BvbnNlIiwiaHR0cDIiLCJndGUiLCJwcm9jZXNzIiwidmVyc2lvbiIsInJlcXVlc3QiLCJtZXRob2QiLCJ1cmwiLCJleHBvcnRzIiwiUmVxdWVzdCIsImVuZCIsImFyZ3VtZW50cyIsImxlbmd0aCIsIm1vZHVsZSIsImFnZW50Iiwibm9vcCIsImRlZmluZSIsInByb3RvY29scyIsInNlcmlhbGl6ZSIsInN0cmluZ2lmeSIsImJ1ZmZlciIsIl9pbml0SGVhZGVycyIsInJlcSIsIl9oZWFkZXIiLCJoZWFkZXIiLCJjYWxsIiwiX2VuYWJsZUh0dHAyIiwiQm9vbGVhbiIsImVudiIsIkhUVFAyX1RFU1QiLCJfYWdlbnQiLCJfZm9ybURhdGEiLCJ3cml0YWJsZSIsIl9yZWRpcmVjdHMiLCJyZWRpcmVjdHMiLCJjb29raWVzIiwiX3F1ZXJ5IiwicXNSYXciLCJfcmVkaXJlY3RMaXN0IiwiX3N0cmVhbVJlcXVlc3QiLCJvbmNlIiwiY2xlYXJUaW1lb3V0IiwiYmluZCIsImluaGVyaXRzIiwicHJvdG90eXBlIiwiYm9vbCIsInVuZGVmaW5lZCIsIkVycm9yIiwiYXR0YWNoIiwiZmllbGQiLCJmaWxlIiwib3B0aW9ucyIsIl9kYXRhIiwibyIsImZpbGVuYW1lIiwiY3JlYXRlUmVhZFN0cmVhbSIsInBhdGgiLCJfZ2V0Rm9ybURhdGEiLCJhcHBlbmQiLCJvbiIsImVyciIsImNhbGxlZCIsImNhbGxiYWNrIiwiYWJvcnQiLCJ0eXBlIiwic2V0IiwiaW5jbHVkZXMiLCJnZXRUeXBlIiwiYWNjZXB0IiwicXVlcnkiLCJ2YWwiLCJwdXNoIiwiT2JqZWN0IiwiYXNzaWduIiwid3JpdGUiLCJkYXRhIiwiZW5jb2RpbmciLCJwaXBlIiwic3RyZWFtIiwicGlwZWQiLCJfcGlwZUNvbnRpbnVlIiwicmVzIiwiaXNSZWRpcmVjdCIsInN0YXR1c0NvZGUiLCJfbWF4UmVkaXJlY3RzIiwiX3JlZGlyZWN0IiwiX2VtaXRSZXNwb25zZSIsIl9hYm9ydGVkIiwiX3Nob3VsZFVuemlwIiwidW56aXBPYmoiLCJjcmVhdGVVbnppcCIsImNvZGUiLCJlbWl0IiwiX2J1ZmZlciIsImhlYWRlcnMiLCJsb2NhdGlvbiIsInJlc3VtZSIsImdldEhlYWRlcnMiLCJfaGVhZGVycyIsImNoYW5nZXNPcmlnaW4iLCJob3N0IiwiY2xlYW5IZWFkZXIiLCJfZW5kQ2FsbGVkIiwiX2NhbGxiYWNrIiwiYXV0aCIsInVzZXIiLCJwYXNzIiwiZW5jb2RlciIsInN0cmluZyIsIkJ1ZmZlciIsImZyb20iLCJ0b1N0cmluZyIsIl9hdXRoIiwiY2EiLCJjZXJ0IiwiX2NhIiwia2V5IiwiX2tleSIsInBmeCIsImlzQnVmZmVyIiwiX3BmeCIsIl9wYXNzcGhyYXNlIiwicGFzc3BocmFzZSIsIl9jZXJ0IiwiZGlzYWJsZVRMU0NlcnRzIiwiX2Rpc2FibGVUTFNDZXJ0cyIsImluZGljZXMiLCJzdHJpY3ROdWxsSGFuZGxpbmciLCJfZmluYWxpemVRdWVyeVN0cmluZyIsInJldHJpZXMiLCJfcmV0cmllcyIsInF1ZXJ5U3RyaW5nQmFja3RpY2tzIiwicXVlcnlTdGFydEluZGV4IiwiaW5kZXhPZiIsInF1ZXJ5U3RyaW5nIiwic2xpY2UiLCJtYXRjaCIsImkiLCJyZXBsYWNlIiwic2VhcmNoIiwicGF0aG5hbWUiLCJ0ZXN0IiwicHJvdG9jb2wiLCJzcGxpdCIsInVuaXhQYXJ0cyIsInNvY2tldFBhdGgiLCJfY29ubmVjdE92ZXJyaWRlIiwiaG9zdG5hbWUiLCJuZXdIb3N0IiwibmV3UG9ydCIsInBvcnQiLCJyZWplY3RVbmF1dGhvcml6ZWQiLCJOT0RFX1RMU19SRUpFQ1RfVU5BVVRIT1JJWkVEIiwic2VydmVybmFtZSIsIl90cnVzdExvY2FsaG9zdCIsIm1vZCIsInNldFByb3RvY29sIiwic2V0Tm9EZWxheSIsInNldEhlYWRlciIsInJlc3BvbnNlIiwidXNlcm5hbWUiLCJwYXNzd29yZCIsImhhc093blByb3BlcnR5IiwidG1wSmFyIiwic2V0Q29va2llcyIsImNvb2tpZSIsImdldENvb2tpZXMiLCJDb29raWVBY2Nlc3NJbmZvIiwiQWxsIiwidG9WYWx1ZVN0cmluZyIsIl9zaG91bGRSZXRyeSIsIl9yZXRyeSIsImZuIiwiY29uc29sZSIsIndhcm4iLCJfaXNSZXNwb25zZU9LIiwibXNnIiwiU1RBVFVTX0NPREVTIiwic3RhdHVzIiwiZXJyXyIsIl9tYXhSZXRyaWVzIiwibGlzdGVuZXJzIiwiX2lzSG9zdCIsIm9iaiIsImJvZHkiLCJmaWxlcyIsIl9lbmQiLCJfc2V0VGltZW91dHMiLCJfaGVhZGVyU2VudCIsImNvbnRlbnRUeXBlIiwiZ2V0SGVhZGVyIiwiX3NlcmlhbGl6ZXIiLCJpc0pTT04iLCJieXRlTGVuZ3RoIiwiX3Jlc3BvbnNlVGltZW91dFRpbWVyIiwibWF4IiwibXVsdGlwYXJ0IiwicmVkaXJlY3QiLCJyZXNwb25zZVR5cGUiLCJfcmVzcG9uc2VUeXBlIiwicGFyc2VyIiwiX3BhcnNlciIsImltYWdlIiwiZm9ybSIsIkluY29taW5nRm9ybSIsImlzSW1hZ2VPclZpZGVvIiwidGV4dCIsImlzVGV4dCIsIl9yZXNCdWZmZXJlZCIsInBhcnNlckhhbmRsZXNFbmQiLCJyZXNwb25zZUJ5dGVzTGVmdCIsIl9tYXhSZXNwb25zZVNpemUiLCJidWYiLCJkZXN0cm95IiwidGltZWRvdXQiLCJnZXRQcm9ncmVzc01vbml0b3IiLCJsZW5ndGhDb21wdXRhYmxlIiwidG90YWwiLCJsb2FkZWQiLCJwcm9ncmVzcyIsIlRyYW5zZm9ybSIsIl90cmFuc2Zvcm0iLCJjaHVuayIsImNiIiwiZGlyZWN0aW9uIiwiYnVmZmVyVG9DaHVua3MiLCJjaHVua1NpemUiLCJjaHVua2luZyIsIlJlYWRhYmxlIiwidG90YWxMZW5ndGgiLCJyZW1haW5kZXIiLCJjdXRvZmYiLCJyZW1haW5kZXJCdWZmZXIiLCJmb3JtRGF0YSIsImdldExlbmd0aCIsImNvbm5lY3QiLCJjb25uZWN0T3ZlcnJpZGUiLCJ0cnVzdExvY2FsaG9zdCIsInRvZ2dsZSIsImZvckVhY2giLCJuYW1lIiwidG9VcHBlckNhc2UiLCJzZW5kIiwicGFydHMiLCJzdWJ0eXBlIl0sIm1hcHBpbmdzIjoiOzs7O0FBQUE7OztBQUlBO2VBQ21DQSxPQUFPLENBQUMsS0FBRCxDO0lBQWxDQyxLLFlBQUFBLEs7SUFBT0MsTSxZQUFBQSxNO0lBQVFDLE8sWUFBQUEsTzs7QUFDdkIsSUFBTUMsTUFBTSxHQUFHSixPQUFPLENBQUMsUUFBRCxDQUF0Qjs7QUFDQSxJQUFNSyxLQUFLLEdBQUdMLE9BQU8sQ0FBQyxPQUFELENBQXJCOztBQUNBLElBQU1NLElBQUksR0FBR04sT0FBTyxDQUFDLE1BQUQsQ0FBcEI7O0FBQ0EsSUFBTU8sRUFBRSxHQUFHUCxPQUFPLENBQUMsSUFBRCxDQUFsQjs7QUFDQSxJQUFNUSxJQUFJLEdBQUdSLE9BQU8sQ0FBQyxNQUFELENBQXBCOztBQUNBLElBQU1TLElBQUksR0FBR1QsT0FBTyxDQUFDLE1BQUQsQ0FBcEI7O0FBQ0EsSUFBTVUsRUFBRSxHQUFHVixPQUFPLENBQUMsSUFBRCxDQUFsQjs7QUFDQSxJQUFNVyxJQUFJLEdBQUdYLE9BQU8sQ0FBQyxNQUFELENBQXBCOztBQUNBLElBQUlZLE9BQU8sR0FBR1osT0FBTyxDQUFDLFNBQUQsQ0FBckI7O0FBQ0EsSUFBTWEsUUFBUSxHQUFHYixPQUFPLENBQUMsV0FBRCxDQUF4Qjs7QUFDQSxJQUFNYyxVQUFVLEdBQUdkLE9BQU8sQ0FBQyxZQUFELENBQTFCOztBQUNBLElBQU1lLEtBQUssR0FBR2YsT0FBTyxDQUFDLE9BQUQsQ0FBUCxDQUFpQixZQUFqQixDQUFkOztBQUNBLElBQU1nQixTQUFTLEdBQUdoQixPQUFPLENBQUMsV0FBRCxDQUF6Qjs7QUFDQSxJQUFNaUIsTUFBTSxHQUFHakIsT0FBTyxDQUFDLFFBQUQsQ0FBdEI7O0FBQ0EsSUFBTWtCLGFBQWEsR0FBR2xCLE9BQU8sQ0FBQyxxQkFBRCxDQUE3Qjs7QUFFQSxJQUFNbUIsS0FBSyxHQUFHbkIsT0FBTyxDQUFDLFVBQUQsQ0FBckI7O0FBQ0EsSUFBTW9CLFdBQVcsR0FBR3BCLE9BQU8sQ0FBQyxpQkFBRCxDQUEzQjs7Z0JBQ2tCQSxPQUFPLENBQUMsU0FBRCxDO0lBQWpCcUIsSyxhQUFBQSxLOztBQUNSLElBQU1DLFFBQVEsR0FBR3RCLE9BQU8sQ0FBQyxZQUFELENBQXhCOztBQUVBLElBQUl1QixLQUFKO0FBRUEsSUFBSU4sTUFBTSxDQUFDTyxHQUFQLENBQVdDLE9BQU8sQ0FBQ0MsT0FBbkIsRUFBNEIsVUFBNUIsQ0FBSixFQUE2Q0gsS0FBSyxHQUFHdkIsT0FBTyxDQUFDLGdCQUFELENBQWY7O0FBRTdDLFNBQVMyQixPQUFULENBQWlCQyxNQUFqQixFQUF5QkMsR0FBekIsRUFBOEI7QUFDNUI7QUFDQSxNQUFJLE9BQU9BLEdBQVAsS0FBZSxVQUFuQixFQUErQjtBQUM3QixXQUFPLElBQUlDLE9BQU8sQ0FBQ0MsT0FBWixDQUFvQixLQUFwQixFQUEyQkgsTUFBM0IsRUFBbUNJLEdBQW5DLENBQXVDSCxHQUF2QyxDQUFQO0FBQ0QsR0FKMkIsQ0FNNUI7OztBQUNBLE1BQUlJLFNBQVMsQ0FBQ0MsTUFBVixLQUFxQixDQUF6QixFQUE0QjtBQUMxQixXQUFPLElBQUlKLE9BQU8sQ0FBQ0MsT0FBWixDQUFvQixLQUFwQixFQUEyQkgsTUFBM0IsQ0FBUDtBQUNEOztBQUVELFNBQU8sSUFBSUUsT0FBTyxDQUFDQyxPQUFaLENBQW9CSCxNQUFwQixFQUE0QkMsR0FBNUIsQ0FBUDtBQUNEOztBQUVETSxNQUFNLENBQUNMLE9BQVAsR0FBaUJILE9BQWpCO0FBQ0FHLE9BQU8sR0FBR0ssTUFBTSxDQUFDTCxPQUFqQjtBQUVBOzs7O0FBSUFBLE9BQU8sQ0FBQ0MsT0FBUixHQUFrQkEsT0FBbEI7QUFFQTs7OztBQUlBRCxPQUFPLENBQUNNLEtBQVIsR0FBZ0JwQyxPQUFPLENBQUMsU0FBRCxDQUF2QjtBQUVBOzs7O0FBSUEsU0FBU3FDLElBQVQsR0FBZ0IsQ0FBRTtBQUVsQjs7Ozs7QUFJQVAsT0FBTyxDQUFDUixRQUFSLEdBQW1CQSxRQUFuQjtBQUVBOzs7O0FBSUFYLElBQUksQ0FBQzJCLE1BQUwsQ0FDRTtBQUNFLHVDQUFxQyxDQUFDLE1BQUQsRUFBUyxZQUFULEVBQXVCLFdBQXZCO0FBRHZDLENBREYsRUFJRSxJQUpGO0FBT0E7Ozs7QUFJQVIsT0FBTyxDQUFDUyxTQUFSLEdBQW9CO0FBQ2xCLFdBQVNqQyxJQURTO0FBRWxCLFlBQVVELEtBRlE7QUFHbEIsWUFBVWtCO0FBSFEsQ0FBcEI7QUFNQTs7Ozs7Ozs7O0FBU0FPLE9BQU8sQ0FBQ1UsU0FBUixHQUFvQjtBQUNsQix1Q0FBcUM5QixFQUFFLENBQUMrQixTQUR0QjtBQUVsQixzQkFBb0J2QjtBQUZGLENBQXBCO0FBS0E7Ozs7Ozs7OztBQVNBWSxPQUFPLENBQUM3QixLQUFSLEdBQWdCRCxPQUFPLENBQUMsV0FBRCxDQUF2QjtBQUVBOzs7Ozs7O0FBTUE4QixPQUFPLENBQUNZLE1BQVIsR0FBaUIsRUFBakI7QUFFQTs7Ozs7OztBQU1BLFNBQVNDLFlBQVQsQ0FBc0JDLEdBQXRCLEVBQTJCO0FBQ3pCQSxFQUFBQSxHQUFHLENBQUNDLE9BQUosR0FBYyxDQUNaO0FBRFksR0FBZDtBQUdBRCxFQUFBQSxHQUFHLENBQUNFLE1BQUosR0FBYSxDQUNYO0FBRFcsR0FBYjtBQUdEO0FBRUQ7Ozs7Ozs7OztBQVFBLFNBQVNmLE9BQVQsQ0FBaUJILE1BQWpCLEVBQXlCQyxHQUF6QixFQUE4QjtBQUM1QnpCLEVBQUFBLE1BQU0sQ0FBQzJDLElBQVAsQ0FBWSxJQUFaO0FBQ0EsTUFBSSxPQUFPbEIsR0FBUCxLQUFlLFFBQW5CLEVBQTZCQSxHQUFHLEdBQUczQixNQUFNLENBQUMyQixHQUFELENBQVo7QUFDN0IsT0FBS21CLFlBQUwsR0FBb0JDLE9BQU8sQ0FBQ3hCLE9BQU8sQ0FBQ3lCLEdBQVIsQ0FBWUMsVUFBYixDQUEzQixDQUg0QixDQUd5Qjs7QUFDckQsT0FBS0MsTUFBTCxHQUFjLEtBQWQ7QUFDQSxPQUFLQyxTQUFMLEdBQWlCLElBQWpCO0FBQ0EsT0FBS3pCLE1BQUwsR0FBY0EsTUFBZDtBQUNBLE9BQUtDLEdBQUwsR0FBV0EsR0FBWDs7QUFDQWMsRUFBQUEsWUFBWSxDQUFDLElBQUQsQ0FBWjs7QUFDQSxPQUFLVyxRQUFMLEdBQWdCLElBQWhCO0FBQ0EsT0FBS0MsVUFBTCxHQUFrQixDQUFsQjtBQUNBLE9BQUtDLFNBQUwsQ0FBZTVCLE1BQU0sS0FBSyxNQUFYLEdBQW9CLENBQXBCLEdBQXdCLENBQXZDO0FBQ0EsT0FBSzZCLE9BQUwsR0FBZSxFQUFmO0FBQ0EsT0FBSy9DLEVBQUwsR0FBVSxFQUFWO0FBQ0EsT0FBS2dELE1BQUwsR0FBYyxFQUFkO0FBQ0EsT0FBS0MsS0FBTCxHQUFhLEtBQUtELE1BQWxCLENBZjRCLENBZUY7O0FBQzFCLE9BQUtFLGFBQUwsR0FBcUIsRUFBckI7QUFDQSxPQUFLQyxjQUFMLEdBQXNCLEtBQXRCO0FBQ0EsT0FBS0MsSUFBTCxDQUFVLEtBQVYsRUFBaUIsS0FBS0MsWUFBTCxDQUFrQkMsSUFBbEIsQ0FBdUIsSUFBdkIsQ0FBakI7QUFDRDtBQUVEOzs7Ozs7QUFJQXZELElBQUksQ0FBQ3dELFFBQUwsQ0FBY2xDLE9BQWQsRUFBdUIzQixNQUF2QixFLENBQ0E7O0FBQ0FnQixXQUFXLENBQUNXLE9BQU8sQ0FBQ21DLFNBQVQsQ0FBWDtBQUVBOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztBQTZCQW5DLE9BQU8sQ0FBQ21DLFNBQVIsQ0FBa0IzQyxLQUFsQixHQUEwQixVQUFTNEMsSUFBVCxFQUFlO0FBQ3ZDLE1BQUlyQyxPQUFPLENBQUNTLFNBQVIsQ0FBa0IsUUFBbEIsTUFBZ0M2QixTQUFwQyxFQUErQztBQUM3QyxVQUFNLElBQUlDLEtBQUosQ0FDSiw0REFESSxDQUFOO0FBR0Q7O0FBRUQsT0FBS3JCLFlBQUwsR0FBb0JtQixJQUFJLEtBQUtDLFNBQVQsR0FBcUIsSUFBckIsR0FBNEJELElBQWhEO0FBQ0EsU0FBTyxJQUFQO0FBQ0QsQ0FURDtBQVdBOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztBQXlCQXBDLE9BQU8sQ0FBQ21DLFNBQVIsQ0FBa0JJLE1BQWxCLEdBQTJCLFVBQVNDLEtBQVQsRUFBZ0JDLElBQWhCLEVBQXNCQyxPQUF0QixFQUErQjtBQUN4RCxNQUFJRCxJQUFKLEVBQVU7QUFDUixRQUFJLEtBQUtFLEtBQVQsRUFBZ0I7QUFDZCxZQUFNLElBQUlMLEtBQUosQ0FBVSw0Q0FBVixDQUFOO0FBQ0Q7O0FBRUQsUUFBSU0sQ0FBQyxHQUFHRixPQUFPLElBQUksRUFBbkI7O0FBQ0EsUUFBSSxPQUFPQSxPQUFQLEtBQW1CLFFBQXZCLEVBQWlDO0FBQy9CRSxNQUFBQSxDQUFDLEdBQUc7QUFBRUMsUUFBQUEsUUFBUSxFQUFFSDtBQUFaLE9BQUo7QUFDRDs7QUFFRCxRQUFJLE9BQU9ELElBQVAsS0FBZ0IsUUFBcEIsRUFBOEI7QUFDNUIsVUFBSSxDQUFDRyxDQUFDLENBQUNDLFFBQVAsRUFBaUJELENBQUMsQ0FBQ0MsUUFBRixHQUFhSixJQUFiO0FBQ2pCekQsTUFBQUEsS0FBSyxDQUFDLGdEQUFELEVBQW1EeUQsSUFBbkQsQ0FBTDtBQUNBQSxNQUFBQSxJQUFJLEdBQUdqRSxFQUFFLENBQUNzRSxnQkFBSCxDQUFvQkwsSUFBcEIsQ0FBUDtBQUNELEtBSkQsTUFJTyxJQUFJLENBQUNHLENBQUMsQ0FBQ0MsUUFBSCxJQUFlSixJQUFJLENBQUNNLElBQXhCLEVBQThCO0FBQ25DSCxNQUFBQSxDQUFDLENBQUNDLFFBQUYsR0FBYUosSUFBSSxDQUFDTSxJQUFsQjtBQUNEOztBQUVELFNBQUtDLFlBQUwsR0FBb0JDLE1BQXBCLENBQTJCVCxLQUEzQixFQUFrQ0MsSUFBbEMsRUFBd0NHLENBQXhDO0FBQ0Q7O0FBRUQsU0FBTyxJQUFQO0FBQ0QsQ0F2QkQ7O0FBeUJBNUMsT0FBTyxDQUFDbUMsU0FBUixDQUFrQmEsWUFBbEIsR0FBaUMsWUFBVztBQUFBOztBQUMxQyxNQUFJLENBQUMsS0FBSzFCLFNBQVYsRUFBcUI7QUFDbkIsU0FBS0EsU0FBTCxHQUFpQixJQUFJeEMsUUFBSixFQUFqQjs7QUFDQSxTQUFLd0MsU0FBTCxDQUFlNEIsRUFBZixDQUFrQixPQUFsQixFQUEyQixVQUFBQyxHQUFHLEVBQUk7QUFDaENuRSxNQUFBQSxLQUFLLENBQUMsZ0JBQUQsRUFBbUJtRSxHQUFuQixDQUFMOztBQUNBLFVBQUksS0FBSSxDQUFDQyxNQUFULEVBQWlCO0FBQ2Y7QUFDQTtBQUNBO0FBQ0Q7O0FBRUQsTUFBQSxLQUFJLENBQUNDLFFBQUwsQ0FBY0YsR0FBZDs7QUFDQSxNQUFBLEtBQUksQ0FBQ0csS0FBTDtBQUNELEtBVkQ7QUFXRDs7QUFFRCxTQUFPLEtBQUtoQyxTQUFaO0FBQ0QsQ0FqQkQ7QUFtQkE7Ozs7Ozs7Ozs7QUFTQXRCLE9BQU8sQ0FBQ21DLFNBQVIsQ0FBa0I5QixLQUFsQixHQUEwQixVQUFTQSxLQUFULEVBQWdCO0FBQ3hDLE1BQUlILFNBQVMsQ0FBQ0MsTUFBVixLQUFxQixDQUF6QixFQUE0QixPQUFPLEtBQUtrQixNQUFaO0FBQzVCLE9BQUtBLE1BQUwsR0FBY2hCLEtBQWQ7QUFDQSxTQUFPLElBQVA7QUFDRCxDQUpEO0FBTUE7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0FBeUJBTCxPQUFPLENBQUNtQyxTQUFSLENBQWtCb0IsSUFBbEIsR0FBeUIsVUFBU0EsSUFBVCxFQUFlO0FBQ3RDLFNBQU8sS0FBS0MsR0FBTCxDQUNMLGNBREssRUFFTEQsSUFBSSxDQUFDRSxRQUFMLENBQWMsR0FBZCxJQUFxQkYsSUFBckIsR0FBNEIzRSxJQUFJLENBQUM4RSxPQUFMLENBQWFILElBQWIsQ0FGdkIsQ0FBUDtBQUlELENBTEQ7QUFPQTs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0FBb0JBdkQsT0FBTyxDQUFDbUMsU0FBUixDQUFrQndCLE1BQWxCLEdBQTJCLFVBQVNKLElBQVQsRUFBZTtBQUN4QyxTQUFPLEtBQUtDLEdBQUwsQ0FBUyxRQUFULEVBQW1CRCxJQUFJLENBQUNFLFFBQUwsQ0FBYyxHQUFkLElBQXFCRixJQUFyQixHQUE0QjNFLElBQUksQ0FBQzhFLE9BQUwsQ0FBYUgsSUFBYixDQUEvQyxDQUFQO0FBQ0QsQ0FGRDtBQUlBOzs7Ozs7Ozs7Ozs7Ozs7QUFjQXZELE9BQU8sQ0FBQ21DLFNBQVIsQ0FBa0J5QixLQUFsQixHQUEwQixVQUFTQyxHQUFULEVBQWM7QUFDdEMsTUFBSSxPQUFPQSxHQUFQLEtBQWUsUUFBbkIsRUFBNkI7QUFDM0IsU0FBS2xDLE1BQUwsQ0FBWW1DLElBQVosQ0FBaUJELEdBQWpCO0FBQ0QsR0FGRCxNQUVPO0FBQ0xFLElBQUFBLE1BQU0sQ0FBQ0MsTUFBUCxDQUFjLEtBQUtyRixFQUFuQixFQUF1QmtGLEdBQXZCO0FBQ0Q7O0FBRUQsU0FBTyxJQUFQO0FBQ0QsQ0FSRDtBQVVBOzs7Ozs7Ozs7O0FBU0E3RCxPQUFPLENBQUNtQyxTQUFSLENBQWtCOEIsS0FBbEIsR0FBMEIsVUFBU0MsSUFBVCxFQUFlQyxRQUFmLEVBQXlCO0FBQ2pELE1BQU10RCxHQUFHLEdBQUcsS0FBS2pCLE9BQUwsRUFBWjs7QUFDQSxNQUFJLENBQUMsS0FBS2tDLGNBQVYsRUFBMEI7QUFDeEIsU0FBS0EsY0FBTCxHQUFzQixJQUF0QjtBQUNEOztBQUVELFNBQU9qQixHQUFHLENBQUNvRCxLQUFKLENBQVVDLElBQVYsRUFBZ0JDLFFBQWhCLENBQVA7QUFDRCxDQVBEO0FBU0E7Ozs7Ozs7Ozs7QUFTQW5FLE9BQU8sQ0FBQ21DLFNBQVIsQ0FBa0JpQyxJQUFsQixHQUF5QixVQUFTQyxNQUFULEVBQWlCM0IsT0FBakIsRUFBMEI7QUFDakQsT0FBSzRCLEtBQUwsR0FBYSxJQUFiLENBRGlELENBQzlCOztBQUNuQixPQUFLM0QsTUFBTCxDQUFZLEtBQVo7QUFDQSxPQUFLVixHQUFMO0FBQ0EsU0FBTyxLQUFLc0UsYUFBTCxDQUFtQkYsTUFBbkIsRUFBMkIzQixPQUEzQixDQUFQO0FBQ0QsQ0FMRDs7QUFPQTFDLE9BQU8sQ0FBQ21DLFNBQVIsQ0FBa0JvQyxhQUFsQixHQUFrQyxVQUFTRixNQUFULEVBQWlCM0IsT0FBakIsRUFBMEI7QUFBQTs7QUFDMUQsT0FBSzdCLEdBQUwsQ0FBU2tCLElBQVQsQ0FBYyxVQUFkLEVBQTBCLFVBQUF5QyxHQUFHLEVBQUk7QUFDL0I7QUFDQSxRQUNFQyxVQUFVLENBQUNELEdBQUcsQ0FBQ0UsVUFBTCxDQUFWLElBQ0EsTUFBSSxDQUFDbEQsVUFBTCxPQUFzQixNQUFJLENBQUNtRCxhQUY3QixFQUdFO0FBQ0EsYUFBTyxNQUFJLENBQUNDLFNBQUwsQ0FBZUosR0FBZixNQUF3QixNQUF4QixHQUNILE1BQUksQ0FBQ0QsYUFBTCxDQUFtQkYsTUFBbkIsRUFBMkIzQixPQUEzQixDQURHLEdBRUhMLFNBRko7QUFHRDs7QUFFRCxJQUFBLE1BQUksQ0FBQ21DLEdBQUwsR0FBV0EsR0FBWDs7QUFDQSxJQUFBLE1BQUksQ0FBQ0ssYUFBTDs7QUFDQSxRQUFJLE1BQUksQ0FBQ0MsUUFBVCxFQUFtQjs7QUFFbkIsUUFBSSxNQUFJLENBQUNDLFlBQUwsQ0FBa0JQLEdBQWxCLENBQUosRUFBNEI7QUFDMUIsVUFBTVEsUUFBUSxHQUFHdkcsSUFBSSxDQUFDd0csV0FBTCxFQUFqQjtBQUNBRCxNQUFBQSxRQUFRLENBQUM5QixFQUFULENBQVksT0FBWixFQUFxQixVQUFBQyxHQUFHLEVBQUk7QUFDMUIsWUFBSUEsR0FBRyxJQUFJQSxHQUFHLENBQUMrQixJQUFKLEtBQWEsYUFBeEIsRUFBdUM7QUFDckM7QUFDQWIsVUFBQUEsTUFBTSxDQUFDYyxJQUFQLENBQVksS0FBWjtBQUNBO0FBQ0Q7O0FBRURkLFFBQUFBLE1BQU0sQ0FBQ2MsSUFBUCxDQUFZLE9BQVosRUFBcUJoQyxHQUFyQjtBQUNELE9BUkQ7QUFTQXFCLE1BQUFBLEdBQUcsQ0FBQ0osSUFBSixDQUFTWSxRQUFULEVBQW1CWixJQUFuQixDQUF3QkMsTUFBeEIsRUFBZ0MzQixPQUFoQztBQUNELEtBWkQsTUFZTztBQUNMOEIsTUFBQUEsR0FBRyxDQUFDSixJQUFKLENBQVNDLE1BQVQsRUFBaUIzQixPQUFqQjtBQUNEOztBQUVEOEIsSUFBQUEsR0FBRyxDQUFDekMsSUFBSixDQUFTLEtBQVQsRUFBZ0IsWUFBTTtBQUNwQixNQUFBLE1BQUksQ0FBQ29ELElBQUwsQ0FBVSxLQUFWO0FBQ0QsS0FGRDtBQUdELEdBbENEO0FBbUNBLFNBQU9kLE1BQVA7QUFDRCxDQXJDRDtBQXVDQTs7Ozs7Ozs7O0FBUUFyRSxPQUFPLENBQUNtQyxTQUFSLENBQWtCeEIsTUFBbEIsR0FBMkIsVUFBU2tELEdBQVQsRUFBYztBQUN2QyxPQUFLdUIsT0FBTCxHQUFldkIsR0FBRyxLQUFLLEtBQXZCO0FBQ0EsU0FBTyxJQUFQO0FBQ0QsQ0FIRDtBQUtBOzs7Ozs7Ozs7QUFRQTdELE9BQU8sQ0FBQ21DLFNBQVIsQ0FBa0J5QyxTQUFsQixHQUE4QixVQUFTSixHQUFULEVBQWM7QUFDMUMsTUFBSTFFLEdBQUcsR0FBRzBFLEdBQUcsQ0FBQ2EsT0FBSixDQUFZQyxRQUF0Qjs7QUFDQSxNQUFJLENBQUN4RixHQUFMLEVBQVU7QUFDUixXQUFPLEtBQUt1RCxRQUFMLENBQWMsSUFBSWYsS0FBSixDQUFVLGlDQUFWLENBQWQsRUFBNERrQyxHQUE1RCxDQUFQO0FBQ0Q7O0FBRUR4RixFQUFBQSxLQUFLLENBQUMsbUJBQUQsRUFBc0IsS0FBS2MsR0FBM0IsRUFBZ0NBLEdBQWhDLENBQUwsQ0FOMEMsQ0FRMUM7O0FBQ0FBLEVBQUFBLEdBQUcsR0FBRzFCLE9BQU8sQ0FBQyxLQUFLMEIsR0FBTixFQUFXQSxHQUFYLENBQWIsQ0FUMEMsQ0FXMUM7QUFDQTs7QUFDQTBFLEVBQUFBLEdBQUcsQ0FBQ2UsTUFBSjtBQUVBLE1BQUlGLE9BQU8sR0FBRyxLQUFLeEUsR0FBTCxDQUFTMkUsVUFBVCxHQUFzQixLQUFLM0UsR0FBTCxDQUFTMkUsVUFBVCxFQUF0QixHQUE4QyxLQUFLM0UsR0FBTCxDQUFTNEUsUUFBckU7QUFFQSxNQUFNQyxhQUFhLEdBQUd4SCxLQUFLLENBQUM0QixHQUFELENBQUwsQ0FBVzZGLElBQVgsS0FBb0J6SCxLQUFLLENBQUMsS0FBSzRCLEdBQU4sQ0FBTCxDQUFnQjZGLElBQTFELENBakIwQyxDQW1CMUM7O0FBQ0EsTUFBSW5CLEdBQUcsQ0FBQ0UsVUFBSixLQUFtQixHQUFuQixJQUEwQkYsR0FBRyxDQUFDRSxVQUFKLEtBQW1CLEdBQWpELEVBQXNEO0FBQ3BEO0FBQ0E7QUFDQVcsSUFBQUEsT0FBTyxHQUFHakcsS0FBSyxDQUFDd0csV0FBTixDQUFrQlAsT0FBbEIsRUFBMkJLLGFBQTNCLENBQVYsQ0FIb0QsQ0FLcEQ7O0FBQ0EsU0FBSzdGLE1BQUwsR0FBYyxLQUFLQSxNQUFMLEtBQWdCLE1BQWhCLEdBQXlCLE1BQXpCLEdBQWtDLEtBQWhELENBTm9ELENBUXBEOztBQUNBLFNBQUs4QyxLQUFMLEdBQWEsSUFBYjtBQUNELEdBOUJ5QyxDQWdDMUM7OztBQUNBLE1BQUk2QixHQUFHLENBQUNFLFVBQUosS0FBbUIsR0FBdkIsRUFBNEI7QUFDMUI7QUFDQTtBQUNBVyxJQUFBQSxPQUFPLEdBQUdqRyxLQUFLLENBQUN3RyxXQUFOLENBQWtCUCxPQUFsQixFQUEyQkssYUFBM0IsQ0FBVixDQUgwQixDQUsxQjs7QUFDQSxTQUFLN0YsTUFBTCxHQUFjLEtBQWQsQ0FOMEIsQ0FRMUI7O0FBQ0EsU0FBSzhDLEtBQUwsR0FBYSxJQUFiO0FBQ0QsR0EzQ3lDLENBNkMxQztBQUNBOzs7QUFDQSxTQUFPMEMsT0FBTyxDQUFDTSxJQUFmO0FBRUEsU0FBTyxLQUFLOUUsR0FBWjtBQUNBLFNBQU8sS0FBS1MsU0FBWixDQWxEMEMsQ0FvRDFDOztBQUNBVixFQUFBQSxZQUFZLENBQUMsSUFBRCxDQUFaLENBckQwQyxDQXVEMUM7OztBQUNBLE9BQUtpRixVQUFMLEdBQWtCLEtBQWxCO0FBQ0EsT0FBSy9GLEdBQUwsR0FBV0EsR0FBWDtBQUNBLE9BQUtuQixFQUFMLEdBQVUsRUFBVjtBQUNBLE9BQUtnRCxNQUFMLENBQVl4QixNQUFaLEdBQXFCLENBQXJCO0FBQ0EsT0FBS3FELEdBQUwsQ0FBUzZCLE9BQVQ7QUFDQSxPQUFLRixJQUFMLENBQVUsVUFBVixFQUFzQlgsR0FBdEI7O0FBQ0EsT0FBSzNDLGFBQUwsQ0FBbUJpQyxJQUFuQixDQUF3QixLQUFLaEUsR0FBN0I7O0FBQ0EsT0FBS0csR0FBTCxDQUFTLEtBQUs2RixTQUFkO0FBQ0EsU0FBTyxJQUFQO0FBQ0QsQ0FqRUQ7QUFtRUE7Ozs7Ozs7Ozs7Ozs7Ozs7OztBQWlCQTlGLE9BQU8sQ0FBQ21DLFNBQVIsQ0FBa0I0RCxJQUFsQixHQUF5QixVQUFTQyxJQUFULEVBQWVDLElBQWYsRUFBcUJ2RCxPQUFyQixFQUE4QjtBQUNyRCxNQUFJeEMsU0FBUyxDQUFDQyxNQUFWLEtBQXFCLENBQXpCLEVBQTRCOEYsSUFBSSxHQUFHLEVBQVA7O0FBQzVCLE1BQUksUUFBT0EsSUFBUCxNQUFnQixRQUFoQixJQUE0QkEsSUFBSSxLQUFLLElBQXpDLEVBQStDO0FBQzdDO0FBQ0F2RCxJQUFBQSxPQUFPLEdBQUd1RCxJQUFWO0FBQ0FBLElBQUFBLElBQUksR0FBRyxFQUFQO0FBQ0Q7O0FBRUQsTUFBSSxDQUFDdkQsT0FBTCxFQUFjO0FBQ1pBLElBQUFBLE9BQU8sR0FBRztBQUFFYSxNQUFBQSxJQUFJLEVBQUU7QUFBUixLQUFWO0FBQ0Q7O0FBRUQsTUFBTTJDLE9BQU8sR0FBRyxTQUFWQSxPQUFVLENBQUFDLE1BQU07QUFBQSxXQUFJQyxNQUFNLENBQUNDLElBQVAsQ0FBWUYsTUFBWixFQUFvQkcsUUFBcEIsQ0FBNkIsUUFBN0IsQ0FBSjtBQUFBLEdBQXRCOztBQUVBLFNBQU8sS0FBS0MsS0FBTCxDQUFXUCxJQUFYLEVBQWlCQyxJQUFqQixFQUF1QnZELE9BQXZCLEVBQWdDd0QsT0FBaEMsQ0FBUDtBQUNELENBZkQ7QUFpQkE7Ozs7Ozs7OztBQVFBbEcsT0FBTyxDQUFDbUMsU0FBUixDQUFrQnFFLEVBQWxCLEdBQXVCLFVBQVNDLElBQVQsRUFBZTtBQUNwQyxPQUFLQyxHQUFMLEdBQVdELElBQVg7QUFDQSxTQUFPLElBQVA7QUFDRCxDQUhEO0FBS0E7Ozs7Ozs7OztBQVFBekcsT0FBTyxDQUFDbUMsU0FBUixDQUFrQndFLEdBQWxCLEdBQXdCLFVBQVNGLElBQVQsRUFBZTtBQUNyQyxPQUFLRyxJQUFMLEdBQVlILElBQVo7QUFDQSxTQUFPLElBQVA7QUFDRCxDQUhEO0FBS0E7Ozs7Ozs7OztBQVFBekcsT0FBTyxDQUFDbUMsU0FBUixDQUFrQjBFLEdBQWxCLEdBQXdCLFVBQVNKLElBQVQsRUFBZTtBQUNyQyxNQUFJLFFBQU9BLElBQVAsTUFBZ0IsUUFBaEIsSUFBNEIsQ0FBQ0wsTUFBTSxDQUFDVSxRQUFQLENBQWdCTCxJQUFoQixDQUFqQyxFQUF3RDtBQUN0RCxTQUFLTSxJQUFMLEdBQVlOLElBQUksQ0FBQ0ksR0FBakI7QUFDQSxTQUFLRyxXQUFMLEdBQW1CUCxJQUFJLENBQUNRLFVBQXhCO0FBQ0QsR0FIRCxNQUdPO0FBQ0wsU0FBS0YsSUFBTCxHQUFZTixJQUFaO0FBQ0Q7O0FBRUQsU0FBTyxJQUFQO0FBQ0QsQ0FURDtBQVdBOzs7Ozs7Ozs7QUFRQXpHLE9BQU8sQ0FBQ21DLFNBQVIsQ0FBa0JzRSxJQUFsQixHQUF5QixVQUFTQSxJQUFULEVBQWU7QUFDdEMsT0FBS1MsS0FBTCxHQUFhVCxJQUFiO0FBQ0EsU0FBTyxJQUFQO0FBQ0QsQ0FIRDtBQUtBOzs7Ozs7Ozs7QUFRQXpHLE9BQU8sQ0FBQ21DLFNBQVIsQ0FBa0JnRixlQUFsQixHQUFvQyxZQUFXO0FBQzdDLE9BQUtDLGdCQUFMLEdBQXdCLElBQXhCO0FBQ0EsU0FBTyxJQUFQO0FBQ0QsQ0FIRDtBQUtBOzs7Ozs7QUFPQTs7O0FBQ0FwSCxPQUFPLENBQUNtQyxTQUFSLENBQWtCdkMsT0FBbEIsR0FBNEIsWUFBVztBQUFBOztBQUNyQyxNQUFJLEtBQUtpQixHQUFULEVBQWMsT0FBTyxLQUFLQSxHQUFaO0FBRWQsTUFBTTZCLE9BQU8sR0FBRyxFQUFoQjs7QUFFQSxNQUFJO0FBQ0YsUUFBTWtCLEtBQUssR0FBR2pGLEVBQUUsQ0FBQytCLFNBQUgsQ0FBYSxLQUFLL0IsRUFBbEIsRUFBc0I7QUFDbEMwSSxNQUFBQSxPQUFPLEVBQUUsS0FEeUI7QUFFbENDLE1BQUFBLGtCQUFrQixFQUFFO0FBRmMsS0FBdEIsQ0FBZDs7QUFJQSxRQUFJMUQsS0FBSixFQUFXO0FBQ1QsV0FBS2pGLEVBQUwsR0FBVSxFQUFWOztBQUNBLFdBQUtnRCxNQUFMLENBQVltQyxJQUFaLENBQWlCRixLQUFqQjtBQUNEOztBQUVELFNBQUsyRCxvQkFBTDtBQUNELEdBWEQsQ0FXRSxPQUFPcEUsR0FBUCxFQUFZO0FBQ1osV0FBTyxLQUFLZ0MsSUFBTCxDQUFVLE9BQVYsRUFBbUJoQyxHQUFuQixDQUFQO0FBQ0Q7O0FBbEJvQyxNQW9CL0JyRCxHQXBCK0IsR0FvQnZCLElBcEJ1QixDQW9CL0JBLEdBcEIrQjtBQXFCckMsTUFBTTBILE9BQU8sR0FBRyxLQUFLQyxRQUFyQixDQXJCcUMsQ0F1QnJDO0FBQ0E7QUFDQTs7QUFDQSxNQUFJQyxvQkFBSjs7QUFDQSxNQUFJNUgsR0FBRyxDQUFDMkQsUUFBSixDQUFhLEdBQWIsQ0FBSixFQUF1QjtBQUNyQixRQUFNa0UsZUFBZSxHQUFHN0gsR0FBRyxDQUFDOEgsT0FBSixDQUFZLEdBQVosQ0FBeEI7O0FBRUEsUUFBSUQsZUFBZSxLQUFLLENBQUMsQ0FBekIsRUFBNEI7QUFDMUIsVUFBTUUsV0FBVyxHQUFHL0gsR0FBRyxDQUFDZ0ksS0FBSixDQUFVSCxlQUFlLEdBQUcsQ0FBNUIsQ0FBcEI7QUFDQUQsTUFBQUEsb0JBQW9CLEdBQUdHLFdBQVcsQ0FBQ0UsS0FBWixDQUFrQixRQUFsQixDQUF2QjtBQUNEO0FBQ0YsR0FsQ29DLENBb0NyQzs7O0FBQ0EsTUFBSWpJLEdBQUcsQ0FBQzhILE9BQUosQ0FBWSxNQUFaLE1BQXdCLENBQTVCLEVBQStCOUgsR0FBRyxvQkFBYUEsR0FBYixDQUFIO0FBQy9CQSxFQUFBQSxHQUFHLEdBQUc1QixLQUFLLENBQUM0QixHQUFELENBQVgsQ0F0Q3FDLENBd0NyQzs7QUFDQSxNQUFJNEgsb0JBQUosRUFBMEI7QUFDeEIsUUFBSU0sQ0FBQyxHQUFHLENBQVI7QUFDQWxJLElBQUFBLEdBQUcsQ0FBQzhELEtBQUosR0FBWTlELEdBQUcsQ0FBQzhELEtBQUosQ0FBVXFFLE9BQVYsQ0FBa0IsTUFBbEIsRUFBMEI7QUFBQSxhQUFNUCxvQkFBb0IsQ0FBQ00sQ0FBQyxFQUFGLENBQTFCO0FBQUEsS0FBMUIsQ0FBWjtBQUNBbEksSUFBQUEsR0FBRyxDQUFDb0ksTUFBSixjQUFpQnBJLEdBQUcsQ0FBQzhELEtBQXJCO0FBQ0E5RCxJQUFBQSxHQUFHLENBQUNpRCxJQUFKLEdBQVdqRCxHQUFHLENBQUNxSSxRQUFKLEdBQWVySSxHQUFHLENBQUNvSSxNQUE5QjtBQUNELEdBOUNvQyxDQWdEckM7OztBQUNBLE1BQUksaUJBQWlCRSxJQUFqQixDQUFzQnRJLEdBQUcsQ0FBQ3VJLFFBQTFCLE1BQXdDLElBQTVDLEVBQWtEO0FBQ2hEO0FBQ0F2SSxJQUFBQSxHQUFHLENBQUN1SSxRQUFKLGFBQWtCdkksR0FBRyxDQUFDdUksUUFBSixDQUFhQyxLQUFiLENBQW1CLEdBQW5CLEVBQXdCLENBQXhCLENBQWxCLE9BRmdELENBSWhEOztBQUNBLFFBQU1DLFNBQVMsR0FBR3pJLEdBQUcsQ0FBQ2lELElBQUosQ0FBU2dGLEtBQVQsQ0FBZSxlQUFmLENBQWxCO0FBQ0FyRixJQUFBQSxPQUFPLENBQUM4RixVQUFSLEdBQXFCRCxTQUFTLENBQUMsQ0FBRCxDQUFULENBQWFOLE9BQWIsQ0FBcUIsTUFBckIsRUFBNkIsR0FBN0IsQ0FBckI7QUFDQW5JLElBQUFBLEdBQUcsQ0FBQ2lELElBQUosR0FBV3dGLFNBQVMsQ0FBQyxDQUFELENBQXBCO0FBQ0QsR0F6RG9DLENBMkRyQzs7O0FBQ0EsTUFBSSxLQUFLRSxnQkFBVCxFQUEyQjtBQUFBLGVBQ0ozSSxHQURJO0FBQUEsUUFDakI0SSxRQURpQixRQUNqQkEsUUFEaUI7QUFFekIsUUFBTVgsS0FBSyxHQUNUVyxRQUFRLElBQUksS0FBS0QsZ0JBQWpCLEdBQ0ksS0FBS0EsZ0JBQUwsQ0FBc0JDLFFBQXRCLENBREosR0FFSSxLQUFLRCxnQkFBTCxDQUFzQixHQUF0QixDQUhOOztBQUlBLFFBQUlWLEtBQUosRUFBVztBQUNUO0FBQ0EsVUFBSSxDQUFDLEtBQUtqSCxPQUFMLENBQWE2RSxJQUFsQixFQUF3QjtBQUN0QixhQUFLbkMsR0FBTCxDQUFTLE1BQVQsRUFBaUIxRCxHQUFHLENBQUM2RixJQUFyQjtBQUNEOztBQUVELFVBQUlnRCxPQUFKO0FBQ0EsVUFBSUMsT0FBSjs7QUFFQSxVQUFJLFFBQU9iLEtBQVAsTUFBaUIsUUFBckIsRUFBK0I7QUFDN0JZLFFBQUFBLE9BQU8sR0FBR1osS0FBSyxDQUFDcEMsSUFBaEI7QUFDQWlELFFBQUFBLE9BQU8sR0FBR2IsS0FBSyxDQUFDYyxJQUFoQjtBQUNELE9BSEQsTUFHTztBQUNMRixRQUFBQSxPQUFPLEdBQUdaLEtBQVY7QUFDQWEsUUFBQUEsT0FBTyxHQUFHOUksR0FBRyxDQUFDK0ksSUFBZDtBQUNELE9BZlEsQ0FpQlQ7OztBQUNBL0ksTUFBQUEsR0FBRyxDQUFDNkYsSUFBSixHQUFXLElBQUl5QyxJQUFKLENBQVNPLE9BQVQsZUFBd0JBLE9BQXhCLFNBQXFDQSxPQUFoRDs7QUFDQSxVQUFJQyxPQUFKLEVBQWE7QUFDWDlJLFFBQUFBLEdBQUcsQ0FBQzZGLElBQUosZUFBZ0JpRCxPQUFoQjtBQUNBOUksUUFBQUEsR0FBRyxDQUFDK0ksSUFBSixHQUFXRCxPQUFYO0FBQ0Q7O0FBRUQ5SSxNQUFBQSxHQUFHLENBQUM0SSxRQUFKLEdBQWVDLE9BQWY7QUFDRDtBQUNGLEdBNUZvQyxDQThGckM7OztBQUNBakcsRUFBQUEsT0FBTyxDQUFDN0MsTUFBUixHQUFpQixLQUFLQSxNQUF0QjtBQUNBNkMsRUFBQUEsT0FBTyxDQUFDbUcsSUFBUixHQUFlL0ksR0FBRyxDQUFDK0ksSUFBbkI7QUFDQW5HLEVBQUFBLE9BQU8sQ0FBQ0ssSUFBUixHQUFlakQsR0FBRyxDQUFDaUQsSUFBbkI7QUFDQUwsRUFBQUEsT0FBTyxDQUFDaUQsSUFBUixHQUFlN0YsR0FBRyxDQUFDNEksUUFBbkI7QUFDQWhHLEVBQUFBLE9BQU8sQ0FBQzhELEVBQVIsR0FBYSxLQUFLRSxHQUFsQjtBQUNBaEUsRUFBQUEsT0FBTyxDQUFDaUUsR0FBUixHQUFjLEtBQUtDLElBQW5CO0FBQ0FsRSxFQUFBQSxPQUFPLENBQUNtRSxHQUFSLEdBQWMsS0FBS0UsSUFBbkI7QUFDQXJFLEVBQUFBLE9BQU8sQ0FBQytELElBQVIsR0FBZSxLQUFLUyxLQUFwQjtBQUNBeEUsRUFBQUEsT0FBTyxDQUFDdUUsVUFBUixHQUFxQixLQUFLRCxXQUExQjtBQUNBdEUsRUFBQUEsT0FBTyxDQUFDckMsS0FBUixHQUFnQixLQUFLZ0IsTUFBckI7QUFDQXFCLEVBQUFBLE9BQU8sQ0FBQ29HLGtCQUFSLEdBQ0UsT0FBTyxLQUFLMUIsZ0JBQVosS0FBaUMsU0FBakMsR0FDSSxDQUFDLEtBQUtBLGdCQURWLEdBRUkxSCxPQUFPLENBQUN5QixHQUFSLENBQVk0SCw0QkFBWixLQUE2QyxHQUhuRCxDQXpHcUMsQ0E4R3JDOztBQUNBLE1BQUksS0FBS2pJLE9BQUwsQ0FBYTZFLElBQWpCLEVBQXVCO0FBQ3JCakQsSUFBQUEsT0FBTyxDQUFDc0csVUFBUixHQUFxQixLQUFLbEksT0FBTCxDQUFhNkUsSUFBYixDQUFrQnNDLE9BQWxCLENBQTBCLE9BQTFCLEVBQW1DLEVBQW5DLENBQXJCO0FBQ0Q7O0FBRUQsTUFDRSxLQUFLZ0IsZUFBTCxJQUNBLDRDQUE0Q2IsSUFBNUMsQ0FBaUR0SSxHQUFHLENBQUM0SSxRQUFyRCxDQUZGLEVBR0U7QUFDQWhHLElBQUFBLE9BQU8sQ0FBQ29HLGtCQUFSLEdBQTZCLEtBQTdCO0FBQ0QsR0F4SG9DLENBMEhyQzs7O0FBQ0EsTUFBTUksR0FBRyxHQUFHLEtBQUtqSSxZQUFMLEdBQ1JsQixPQUFPLENBQUNTLFNBQVIsQ0FBa0IsUUFBbEIsRUFBNEIySSxXQUE1QixDQUF3Q3JKLEdBQUcsQ0FBQ3VJLFFBQTVDLENBRFEsR0FFUnRJLE9BQU8sQ0FBQ1MsU0FBUixDQUFrQlYsR0FBRyxDQUFDdUksUUFBdEIsQ0FGSixDQTNIcUMsQ0ErSHJDOztBQUNBLE9BQUt4SCxHQUFMLEdBQVdxSSxHQUFHLENBQUN0SixPQUFKLENBQVk4QyxPQUFaLENBQVg7QUFoSXFDLE1BaUk3QjdCLEdBakk2QixHQWlJckIsSUFqSXFCLENBaUk3QkEsR0FqSTZCLEVBbUlyQzs7QUFDQUEsRUFBQUEsR0FBRyxDQUFDdUksVUFBSixDQUFlLElBQWY7O0FBRUEsTUFBSTFHLE9BQU8sQ0FBQzdDLE1BQVIsS0FBbUIsTUFBdkIsRUFBK0I7QUFDN0JnQixJQUFBQSxHQUFHLENBQUN3SSxTQUFKLENBQWMsaUJBQWQsRUFBaUMsZUFBakM7QUFDRDs7QUFFRCxPQUFLaEIsUUFBTCxHQUFnQnZJLEdBQUcsQ0FBQ3VJLFFBQXBCO0FBQ0EsT0FBSzFDLElBQUwsR0FBWTdGLEdBQUcsQ0FBQzZGLElBQWhCLENBM0lxQyxDQTZJckM7O0FBQ0E5RSxFQUFBQSxHQUFHLENBQUNrQixJQUFKLENBQVMsT0FBVCxFQUFrQixZQUFNO0FBQ3RCLElBQUEsTUFBSSxDQUFDb0QsSUFBTCxDQUFVLE9BQVY7QUFDRCxHQUZEO0FBSUF0RSxFQUFBQSxHQUFHLENBQUNxQyxFQUFKLENBQU8sT0FBUCxFQUFnQixVQUFBQyxHQUFHLEVBQUk7QUFDckI7QUFDQTtBQUNBO0FBQ0EsUUFBSSxNQUFJLENBQUMyQixRQUFULEVBQW1CLE9BSkUsQ0FLckI7QUFDQTs7QUFDQSxRQUFJLE1BQUksQ0FBQzJDLFFBQUwsS0FBa0JELE9BQXRCLEVBQStCLE9BUFYsQ0FRckI7QUFDQTs7QUFDQSxRQUFJLE1BQUksQ0FBQzhCLFFBQVQsRUFBbUI7O0FBQ25CLElBQUEsTUFBSSxDQUFDakcsUUFBTCxDQUFjRixHQUFkO0FBQ0QsR0FaRCxFQWxKcUMsQ0FnS3JDOztBQUNBLE1BQUlyRCxHQUFHLENBQUNpRyxJQUFSLEVBQWM7QUFDWixRQUFNQSxJQUFJLEdBQUdqRyxHQUFHLENBQUNpRyxJQUFKLENBQVN1QyxLQUFULENBQWUsR0FBZixDQUFiO0FBQ0EsU0FBS3ZDLElBQUwsQ0FBVUEsSUFBSSxDQUFDLENBQUQsQ0FBZCxFQUFtQkEsSUFBSSxDQUFDLENBQUQsQ0FBdkI7QUFDRDs7QUFFRCxNQUFJLEtBQUt3RCxRQUFMLElBQWlCLEtBQUtDLFFBQTFCLEVBQW9DO0FBQ2xDLFNBQUt6RCxJQUFMLENBQVUsS0FBS3dELFFBQWYsRUFBeUIsS0FBS0MsUUFBOUI7QUFDRDs7QUFFRCxPQUFLLElBQU03QyxHQUFYLElBQWtCLEtBQUs1RixNQUF2QixFQUErQjtBQUM3QixRQUFJZ0QsTUFBTSxDQUFDNUIsU0FBUCxDQUFpQnNILGNBQWpCLENBQWdDekksSUFBaEMsQ0FBcUMsS0FBS0QsTUFBMUMsRUFBa0Q0RixHQUFsRCxDQUFKLEVBQ0U5RixHQUFHLENBQUN3SSxTQUFKLENBQWMxQyxHQUFkLEVBQW1CLEtBQUs1RixNQUFMLENBQVk0RixHQUFaLENBQW5CO0FBQ0gsR0E3S29DLENBK0tyQzs7O0FBQ0EsTUFBSSxLQUFLakYsT0FBVCxFQUFrQjtBQUNoQixRQUFJcUMsTUFBTSxDQUFDNUIsU0FBUCxDQUFpQnNILGNBQWpCLENBQWdDekksSUFBaEMsQ0FBcUMsS0FBS0YsT0FBMUMsRUFBbUQsUUFBbkQsQ0FBSixFQUFrRTtBQUNoRTtBQUNBLFVBQU00SSxNQUFNLEdBQUcsSUFBSXpLLFNBQVMsQ0FBQ0EsU0FBZCxFQUFmO0FBQ0F5SyxNQUFBQSxNQUFNLENBQUNDLFVBQVAsQ0FBa0IsS0FBSzdJLE9BQUwsQ0FBYThJLE1BQWIsQ0FBb0J0QixLQUFwQixDQUEwQixHQUExQixDQUFsQjtBQUNBb0IsTUFBQUEsTUFBTSxDQUFDQyxVQUFQLENBQWtCLEtBQUtqSSxPQUFMLENBQWE0RyxLQUFiLENBQW1CLEdBQW5CLENBQWxCO0FBQ0F6SCxNQUFBQSxHQUFHLENBQUN3SSxTQUFKLENBQ0UsUUFERixFQUVFSyxNQUFNLENBQUNHLFVBQVAsQ0FBa0I1SyxTQUFTLENBQUM2SyxnQkFBVixDQUEyQkMsR0FBN0MsRUFBa0RDLGFBQWxELEVBRkY7QUFJRCxLQVRELE1BU087QUFDTG5KLE1BQUFBLEdBQUcsQ0FBQ3dJLFNBQUosQ0FBYyxRQUFkLEVBQXdCLEtBQUszSCxPQUE3QjtBQUNEO0FBQ0Y7O0FBRUQsU0FBT2IsR0FBUDtBQUNELENBaE1EO0FBa01BOzs7Ozs7Ozs7O0FBU0FiLE9BQU8sQ0FBQ21DLFNBQVIsQ0FBa0JrQixRQUFsQixHQUE2QixVQUFTRixHQUFULEVBQWNxQixHQUFkLEVBQW1CO0FBQzlDLE1BQUksS0FBS3lGLFlBQUwsQ0FBa0I5RyxHQUFsQixFQUF1QnFCLEdBQXZCLENBQUosRUFBaUM7QUFDL0IsV0FBTyxLQUFLMEYsTUFBTCxFQUFQO0FBQ0QsR0FINkMsQ0FLOUM7OztBQUNBLE1BQU1DLEVBQUUsR0FBRyxLQUFLckUsU0FBTCxJQUFrQnhGLElBQTdCO0FBQ0EsT0FBSzBCLFlBQUw7QUFDQSxNQUFJLEtBQUtvQixNQUFULEVBQWlCLE9BQU9nSCxPQUFPLENBQUNDLElBQVIsQ0FBYSxpQ0FBYixDQUFQO0FBQ2pCLE9BQUtqSCxNQUFMLEdBQWMsSUFBZDs7QUFFQSxNQUFJLENBQUNELEdBQUwsRUFBVTtBQUNSLFFBQUk7QUFDRixVQUFJLENBQUMsS0FBS21ILGFBQUwsQ0FBbUI5RixHQUFuQixDQUFMLEVBQThCO0FBQzVCLFlBQUkrRixHQUFHLEdBQUcsNEJBQVY7O0FBQ0EsWUFBSS9GLEdBQUosRUFBUztBQUNQK0YsVUFBQUEsR0FBRyxHQUFHaE0sSUFBSSxDQUFDaU0sWUFBTCxDQUFrQmhHLEdBQUcsQ0FBQ2lHLE1BQXRCLEtBQWlDRixHQUF2QztBQUNEOztBQUVEcEgsUUFBQUEsR0FBRyxHQUFHLElBQUliLEtBQUosQ0FBVWlJLEdBQVYsQ0FBTjtBQUNBcEgsUUFBQUEsR0FBRyxDQUFDc0gsTUFBSixHQUFhakcsR0FBRyxHQUFHQSxHQUFHLENBQUNpRyxNQUFQLEdBQWdCcEksU0FBaEM7QUFDRDtBQUNGLEtBVkQsQ0FVRSxPQUFPcUksSUFBUCxFQUFhO0FBQ2J2SCxNQUFBQSxHQUFHLEdBQUd1SCxJQUFOO0FBQ0Q7QUFDRixHQXpCNkMsQ0EyQjlDO0FBQ0E7OztBQUNBLE1BQUksQ0FBQ3ZILEdBQUwsRUFBVTtBQUNSLFdBQU9nSCxFQUFFLENBQUMsSUFBRCxFQUFPM0YsR0FBUCxDQUFUO0FBQ0Q7O0FBRURyQixFQUFBQSxHQUFHLENBQUNtRyxRQUFKLEdBQWU5RSxHQUFmO0FBQ0EsTUFBSSxLQUFLbUcsV0FBVCxFQUFzQnhILEdBQUcsQ0FBQ3FFLE9BQUosR0FBYyxLQUFLQyxRQUFMLEdBQWdCLENBQTlCLENBbEN3QixDQW9DOUM7QUFDQTs7QUFDQSxNQUFJdEUsR0FBRyxJQUFJLEtBQUt5SCxTQUFMLENBQWUsT0FBZixFQUF3QnpLLE1BQXhCLEdBQWlDLENBQTVDLEVBQStDO0FBQzdDLFNBQUtnRixJQUFMLENBQVUsT0FBVixFQUFtQmhDLEdBQW5CO0FBQ0Q7O0FBRURnSCxFQUFBQSxFQUFFLENBQUNoSCxHQUFELEVBQU1xQixHQUFOLENBQUY7QUFDRCxDQTNDRDtBQTZDQTs7Ozs7Ozs7O0FBT0F4RSxPQUFPLENBQUNtQyxTQUFSLENBQWtCMEksT0FBbEIsR0FBNEIsVUFBU0MsR0FBVCxFQUFjO0FBQ3hDLFNBQ0UxRSxNQUFNLENBQUNVLFFBQVAsQ0FBZ0JnRSxHQUFoQixLQUF3QkEsR0FBRyxZQUFZek0sTUFBdkMsSUFBaUR5TSxHQUFHLFlBQVloTSxRQURsRTtBQUdELENBSkQ7QUFNQTs7Ozs7Ozs7OztBQVNBa0IsT0FBTyxDQUFDbUMsU0FBUixDQUFrQjBDLGFBQWxCLEdBQWtDLFVBQVNrRyxJQUFULEVBQWVDLEtBQWYsRUFBc0I7QUFDdEQsTUFBTTFCLFFBQVEsR0FBRyxJQUFJL0osUUFBSixDQUFhLElBQWIsQ0FBakI7QUFDQSxPQUFLK0osUUFBTCxHQUFnQkEsUUFBaEI7QUFDQUEsRUFBQUEsUUFBUSxDQUFDN0gsU0FBVCxHQUFxQixLQUFLSSxhQUExQjs7QUFDQSxNQUFJUSxTQUFTLEtBQUswSSxJQUFsQixFQUF3QjtBQUN0QnpCLElBQUFBLFFBQVEsQ0FBQ3lCLElBQVQsR0FBZ0JBLElBQWhCO0FBQ0Q7O0FBRUR6QixFQUFBQSxRQUFRLENBQUMwQixLQUFULEdBQWlCQSxLQUFqQjs7QUFDQSxNQUFJLEtBQUtuRixVQUFULEVBQXFCO0FBQ25CeUQsSUFBQUEsUUFBUSxDQUFDbEYsSUFBVCxHQUFnQixZQUFXO0FBQ3pCLFlBQU0sSUFBSTlCLEtBQUosQ0FDSixpRUFESSxDQUFOO0FBR0QsS0FKRDtBQUtEOztBQUVELE9BQUs2QyxJQUFMLENBQVUsVUFBVixFQUFzQm1FLFFBQXRCO0FBQ0EsU0FBT0EsUUFBUDtBQUNELENBbkJEOztBQXFCQXRKLE9BQU8sQ0FBQ21DLFNBQVIsQ0FBa0JsQyxHQUFsQixHQUF3QixVQUFTa0ssRUFBVCxFQUFhO0FBQ25DLE9BQUt2SyxPQUFMO0FBQ0FaLEVBQUFBLEtBQUssQ0FBQyxPQUFELEVBQVUsS0FBS2EsTUFBZixFQUF1QixLQUFLQyxHQUE1QixDQUFMOztBQUVBLE1BQUksS0FBSytGLFVBQVQsRUFBcUI7QUFDbkIsVUFBTSxJQUFJdkQsS0FBSixDQUNKLDhEQURJLENBQU47QUFHRDs7QUFFRCxPQUFLdUQsVUFBTCxHQUFrQixJQUFsQixDQVZtQyxDQVluQzs7QUFDQSxPQUFLQyxTQUFMLEdBQWlCcUUsRUFBRSxJQUFJN0osSUFBdkI7O0FBRUEsT0FBSzJLLElBQUw7QUFDRCxDQWhCRDs7QUFrQkFqTCxPQUFPLENBQUNtQyxTQUFSLENBQWtCOEksSUFBbEIsR0FBeUIsWUFBVztBQUFBOztBQUNsQyxNQUFJLEtBQUtuRyxRQUFULEVBQ0UsT0FBTyxLQUFLekIsUUFBTCxDQUNMLElBQUlmLEtBQUosQ0FBVSw0REFBVixDQURLLENBQVA7QUFJRixNQUFJNEIsSUFBSSxHQUFHLEtBQUt2QixLQUFoQjtBQU5rQyxNQU8xQjlCLEdBUDBCLEdBT2xCLElBUGtCLENBTzFCQSxHQVAwQjtBQUFBLE1BUTFCaEIsTUFSMEIsR0FRZixJQVJlLENBUTFCQSxNQVIwQjs7QUFVbEMsT0FBS3FMLFlBQUwsR0FWa0MsQ0FZbEM7OztBQUNBLE1BQUlyTCxNQUFNLEtBQUssTUFBWCxJQUFxQixDQUFDZ0IsR0FBRyxDQUFDc0ssV0FBOUIsRUFBMkM7QUFDekM7QUFDQSxRQUFJLE9BQU9qSCxJQUFQLEtBQWdCLFFBQXBCLEVBQThCO0FBQzVCLFVBQUlrSCxXQUFXLEdBQUd2SyxHQUFHLENBQUN3SyxTQUFKLENBQWMsY0FBZCxDQUFsQixDQUQ0QixDQUU1Qjs7QUFDQSxVQUFJRCxXQUFKLEVBQWlCQSxXQUFXLEdBQUdBLFdBQVcsQ0FBQzlDLEtBQVosQ0FBa0IsR0FBbEIsRUFBdUIsQ0FBdkIsQ0FBZDtBQUNqQixVQUFJN0gsU0FBUyxHQUFHLEtBQUs2SyxXQUFMLElBQW9CdkwsT0FBTyxDQUFDVSxTQUFSLENBQWtCMkssV0FBbEIsQ0FBcEM7O0FBQ0EsVUFBSSxDQUFDM0ssU0FBRCxJQUFjOEssTUFBTSxDQUFDSCxXQUFELENBQXhCLEVBQXVDO0FBQ3JDM0ssUUFBQUEsU0FBUyxHQUFHVixPQUFPLENBQUNVLFNBQVIsQ0FBa0Isa0JBQWxCLENBQVo7QUFDRDs7QUFFRCxVQUFJQSxTQUFKLEVBQWV5RCxJQUFJLEdBQUd6RCxTQUFTLENBQUN5RCxJQUFELENBQWhCO0FBQ2hCLEtBWndDLENBY3pDOzs7QUFDQSxRQUFJQSxJQUFJLElBQUksQ0FBQ3JELEdBQUcsQ0FBQ3dLLFNBQUosQ0FBYyxnQkFBZCxDQUFiLEVBQThDO0FBQzVDeEssTUFBQUEsR0FBRyxDQUFDd0ksU0FBSixDQUNFLGdCQURGLEVBRUVqRCxNQUFNLENBQUNVLFFBQVAsQ0FBZ0I1QyxJQUFoQixJQUF3QkEsSUFBSSxDQUFDL0QsTUFBN0IsR0FBc0NpRyxNQUFNLENBQUNvRixVQUFQLENBQWtCdEgsSUFBbEIsQ0FGeEM7QUFJRDtBQUNGLEdBbENpQyxDQW9DbEM7QUFDQTs7O0FBQ0FyRCxFQUFBQSxHQUFHLENBQUNrQixJQUFKLENBQVMsVUFBVCxFQUFxQixVQUFBeUMsR0FBRyxFQUFJO0FBQzFCeEYsSUFBQUEsS0FBSyxDQUFDLGFBQUQsRUFBZ0IsTUFBSSxDQUFDYSxNQUFyQixFQUE2QixNQUFJLENBQUNDLEdBQWxDLEVBQXVDMEUsR0FBRyxDQUFDRSxVQUEzQyxDQUFMOztBQUVBLFFBQUksTUFBSSxDQUFDK0cscUJBQVQsRUFBZ0M7QUFDOUJ6SixNQUFBQSxZQUFZLENBQUMsTUFBSSxDQUFDeUoscUJBQU4sQ0FBWjtBQUNEOztBQUVELFFBQUksTUFBSSxDQUFDbkgsS0FBVCxFQUFnQjtBQUNkO0FBQ0Q7O0FBRUQsUUFBTW9ILEdBQUcsR0FBRyxNQUFJLENBQUMvRyxhQUFqQjtBQUNBLFFBQU0vRixJQUFJLEdBQUdRLEtBQUssQ0FBQ21FLElBQU4sQ0FBV2lCLEdBQUcsQ0FBQ2EsT0FBSixDQUFZLGNBQVosS0FBK0IsRUFBMUMsS0FBaUQsWUFBOUQ7QUFDQSxRQUFNOUIsSUFBSSxHQUFHM0UsSUFBSSxDQUFDMEosS0FBTCxDQUFXLEdBQVgsRUFBZ0IsQ0FBaEIsQ0FBYjtBQUNBLFFBQU1xRCxTQUFTLEdBQUdwSSxJQUFJLEtBQUssV0FBM0I7QUFDQSxRQUFNcUksUUFBUSxHQUFHbkgsVUFBVSxDQUFDRCxHQUFHLENBQUNFLFVBQUwsQ0FBM0I7QUFDQSxRQUFNbUgsWUFBWSxHQUFHLE1BQUksQ0FBQ0MsYUFBMUI7QUFFQSxJQUFBLE1BQUksQ0FBQ3RILEdBQUwsR0FBV0EsR0FBWCxDQWxCMEIsQ0FvQjFCOztBQUNBLFFBQUlvSCxRQUFRLElBQUksTUFBSSxDQUFDcEssVUFBTCxPQUFzQmtLLEdBQXRDLEVBQTJDO0FBQ3pDLGFBQU8sTUFBSSxDQUFDOUcsU0FBTCxDQUFlSixHQUFmLENBQVA7QUFDRDs7QUFFRCxRQUFJLE1BQUksQ0FBQzNFLE1BQUwsS0FBZ0IsTUFBcEIsRUFBNEI7QUFDMUIsTUFBQSxNQUFJLENBQUNzRixJQUFMLENBQVUsS0FBVjs7QUFDQSxNQUFBLE1BQUksQ0FBQzlCLFFBQUwsQ0FBYyxJQUFkLEVBQW9CLE1BQUksQ0FBQ3dCLGFBQUwsRUFBcEI7O0FBQ0E7QUFDRCxLQTdCeUIsQ0ErQjFCOzs7QUFDQSxRQUFJLE1BQUksQ0FBQ0UsWUFBTCxDQUFrQlAsR0FBbEIsQ0FBSixFQUE0QjtBQUMxQmxGLE1BQUFBLEtBQUssQ0FBQ3VCLEdBQUQsRUFBTTJELEdBQU4sQ0FBTDtBQUNEOztBQUVELFFBQUk3RCxNQUFNLEdBQUcsTUFBSSxDQUFDeUUsT0FBbEI7O0FBQ0EsUUFBSXpFLE1BQU0sS0FBSzBCLFNBQVgsSUFBd0J6RCxJQUFJLElBQUltQixPQUFPLENBQUNZLE1BQTVDLEVBQW9EO0FBQ2xEQSxNQUFBQSxNQUFNLEdBQUdPLE9BQU8sQ0FBQ25CLE9BQU8sQ0FBQ1ksTUFBUixDQUFlL0IsSUFBZixDQUFELENBQWhCO0FBQ0Q7O0FBRUQsUUFBSW1OLE1BQU0sR0FBRyxNQUFJLENBQUNDLE9BQWxCOztBQUNBLFFBQUkzSixTQUFTLEtBQUsxQixNQUFsQixFQUEwQjtBQUN4QixVQUFJb0wsTUFBSixFQUFZO0FBQ1YzQixRQUFBQSxPQUFPLENBQUNDLElBQVIsQ0FDRSwwTEFERjtBQUdBMUosUUFBQUEsTUFBTSxHQUFHLElBQVQ7QUFDRDtBQUNGOztBQUVELFFBQUksQ0FBQ29MLE1BQUwsRUFBYTtBQUNYLFVBQUlGLFlBQUosRUFBa0I7QUFDaEJFLFFBQUFBLE1BQU0sR0FBR2hNLE9BQU8sQ0FBQzdCLEtBQVIsQ0FBYytOLEtBQXZCLENBRGdCLENBQ2M7O0FBQzlCdEwsUUFBQUEsTUFBTSxHQUFHLElBQVQ7QUFDRCxPQUhELE1BR08sSUFBSWdMLFNBQUosRUFBZTtBQUNwQixZQUFNTyxJQUFJLEdBQUcsSUFBSW5OLFVBQVUsQ0FBQ29OLFlBQWYsRUFBYjtBQUNBSixRQUFBQSxNQUFNLEdBQUdHLElBQUksQ0FBQ2hPLEtBQUwsQ0FBVytELElBQVgsQ0FBZ0JpSyxJQUFoQixDQUFUO0FBQ0F2TCxRQUFBQSxNQUFNLEdBQUcsSUFBVDtBQUNELE9BSk0sTUFJQSxJQUFJeUwsY0FBYyxDQUFDeE4sSUFBRCxDQUFsQixFQUEwQjtBQUMvQm1OLFFBQUFBLE1BQU0sR0FBR2hNLE9BQU8sQ0FBQzdCLEtBQVIsQ0FBYytOLEtBQXZCO0FBQ0F0TCxRQUFBQSxNQUFNLEdBQUcsSUFBVCxDQUYrQixDQUVoQjtBQUNoQixPQUhNLE1BR0EsSUFBSVosT0FBTyxDQUFDN0IsS0FBUixDQUFjVSxJQUFkLENBQUosRUFBeUI7QUFDOUJtTixRQUFBQSxNQUFNLEdBQUdoTSxPQUFPLENBQUM3QixLQUFSLENBQWNVLElBQWQsQ0FBVDtBQUNELE9BRk0sTUFFQSxJQUFJMkUsSUFBSSxLQUFLLE1BQWIsRUFBcUI7QUFDMUJ3SSxRQUFBQSxNQUFNLEdBQUdoTSxPQUFPLENBQUM3QixLQUFSLENBQWNtTyxJQUF2QjtBQUNBMUwsUUFBQUEsTUFBTSxHQUFHQSxNQUFNLEtBQUssS0FBcEIsQ0FGMEIsQ0FJMUI7QUFDRCxPQUxNLE1BS0EsSUFBSTRLLE1BQU0sQ0FBQzNNLElBQUQsQ0FBVixFQUFrQjtBQUN2Qm1OLFFBQUFBLE1BQU0sR0FBR2hNLE9BQU8sQ0FBQzdCLEtBQVIsQ0FBYyxrQkFBZCxDQUFUO0FBQ0F5QyxRQUFBQSxNQUFNLEdBQUdBLE1BQU0sS0FBSyxLQUFwQjtBQUNELE9BSE0sTUFHQSxJQUFJQSxNQUFKLEVBQVk7QUFDakJvTCxRQUFBQSxNQUFNLEdBQUdoTSxPQUFPLENBQUM3QixLQUFSLENBQWNtTyxJQUF2QjtBQUNELE9BRk0sTUFFQSxJQUFJaEssU0FBUyxLQUFLMUIsTUFBbEIsRUFBMEI7QUFDL0JvTCxRQUFBQSxNQUFNLEdBQUdoTSxPQUFPLENBQUM3QixLQUFSLENBQWMrTixLQUF2QixDQUQrQixDQUNEOztBQUM5QnRMLFFBQUFBLE1BQU0sR0FBRyxJQUFUO0FBQ0Q7QUFDRixLQTlFeUIsQ0FnRjFCOzs7QUFDQSxRQUFLMEIsU0FBUyxLQUFLMUIsTUFBZCxJQUF3QjJMLE1BQU0sQ0FBQzFOLElBQUQsQ0FBL0IsSUFBMEMyTSxNQUFNLENBQUMzTSxJQUFELENBQXBELEVBQTREO0FBQzFEK0IsTUFBQUEsTUFBTSxHQUFHLElBQVQ7QUFDRDs7QUFFRCxJQUFBLE1BQUksQ0FBQzRMLFlBQUwsR0FBb0I1TCxNQUFwQjtBQUNBLFFBQUk2TCxnQkFBZ0IsR0FBRyxLQUF2Qjs7QUFDQSxRQUFJN0wsTUFBSixFQUFZO0FBQ1Y7QUFDQSxVQUFJOEwsaUJBQWlCLEdBQUcsTUFBSSxDQUFDQyxnQkFBTCxJQUF5QixTQUFqRDtBQUNBbEksTUFBQUEsR0FBRyxDQUFDdEIsRUFBSixDQUFPLE1BQVAsRUFBZSxVQUFBeUosR0FBRyxFQUFJO0FBQ3BCRixRQUFBQSxpQkFBaUIsSUFBSUUsR0FBRyxDQUFDbkIsVUFBSixJQUFrQm1CLEdBQUcsQ0FBQ3hNLE1BQTNDOztBQUNBLFlBQUlzTSxpQkFBaUIsR0FBRyxDQUF4QixFQUEyQjtBQUN6QjtBQUNBLGNBQU10SixHQUFHLEdBQUcsSUFBSWIsS0FBSixDQUFVLCtCQUFWLENBQVo7QUFDQWEsVUFBQUEsR0FBRyxDQUFDK0IsSUFBSixHQUFXLFdBQVgsQ0FIeUIsQ0FJekI7QUFDQTs7QUFDQXNILFVBQUFBLGdCQUFnQixHQUFHLEtBQW5CLENBTnlCLENBT3pCOztBQUNBaEksVUFBQUEsR0FBRyxDQUFDb0ksT0FBSixDQUFZekosR0FBWjtBQUNEO0FBQ0YsT0FaRDtBQWFEOztBQUVELFFBQUk0SSxNQUFKLEVBQVk7QUFDVixVQUFJO0FBQ0Y7QUFDQTtBQUNBUyxRQUFBQSxnQkFBZ0IsR0FBRzdMLE1BQW5CO0FBRUFvTCxRQUFBQSxNQUFNLENBQUN2SCxHQUFELEVBQU0sVUFBQ3JCLEdBQUQsRUFBTTJILEdBQU4sRUFBV0UsS0FBWCxFQUFxQjtBQUMvQixjQUFJLE1BQUksQ0FBQzZCLFFBQVQsRUFBbUI7QUFDakI7QUFDQTtBQUNELFdBSjhCLENBTS9CO0FBQ0E7OztBQUNBLGNBQUkxSixHQUFHLElBQUksQ0FBQyxNQUFJLENBQUMyQixRQUFqQixFQUEyQjtBQUN6QixtQkFBTyxNQUFJLENBQUN6QixRQUFMLENBQWNGLEdBQWQsQ0FBUDtBQUNEOztBQUVELGNBQUlxSixnQkFBSixFQUFzQjtBQUNwQixZQUFBLE1BQUksQ0FBQ3JILElBQUwsQ0FBVSxLQUFWOztBQUNBLFlBQUEsTUFBSSxDQUFDOUIsUUFBTCxDQUFjLElBQWQsRUFBb0IsTUFBSSxDQUFDd0IsYUFBTCxDQUFtQmlHLEdBQW5CLEVBQXdCRSxLQUF4QixDQUFwQjtBQUNEO0FBQ0YsU0FoQkssQ0FBTjtBQWlCRCxPQXRCRCxDQXNCRSxPQUFPN0gsR0FBUCxFQUFZO0FBQ1osUUFBQSxNQUFJLENBQUNFLFFBQUwsQ0FBY0YsR0FBZDs7QUFDQTtBQUNEO0FBQ0Y7O0FBRUQsSUFBQSxNQUFJLENBQUNxQixHQUFMLEdBQVdBLEdBQVgsQ0F0STBCLENBd0kxQjs7QUFDQSxRQUFJLENBQUM3RCxNQUFMLEVBQWE7QUFDWDNCLE1BQUFBLEtBQUssQ0FBQyxrQkFBRCxFQUFxQixNQUFJLENBQUNhLE1BQTFCLEVBQWtDLE1BQUksQ0FBQ0MsR0FBdkMsQ0FBTDs7QUFDQSxNQUFBLE1BQUksQ0FBQ3VELFFBQUwsQ0FBYyxJQUFkLEVBQW9CLE1BQUksQ0FBQ3dCLGFBQUwsRUFBcEI7O0FBQ0EsVUFBSThHLFNBQUosRUFBZSxPQUhKLENBR1k7O0FBQ3ZCbkgsTUFBQUEsR0FBRyxDQUFDekMsSUFBSixDQUFTLEtBQVQsRUFBZ0IsWUFBTTtBQUNwQi9DLFFBQUFBLEtBQUssQ0FBQyxXQUFELEVBQWMsTUFBSSxDQUFDYSxNQUFuQixFQUEyQixNQUFJLENBQUNDLEdBQWhDLENBQUw7O0FBQ0EsUUFBQSxNQUFJLENBQUNxRixJQUFMLENBQVUsS0FBVjtBQUNELE9BSEQ7QUFJQTtBQUNELEtBbEp5QixDQW9KMUI7OztBQUNBWCxJQUFBQSxHQUFHLENBQUN6QyxJQUFKLENBQVMsT0FBVCxFQUFrQixVQUFBb0IsR0FBRyxFQUFJO0FBQ3ZCcUosTUFBQUEsZ0JBQWdCLEdBQUcsS0FBbkI7O0FBQ0EsTUFBQSxNQUFJLENBQUNuSixRQUFMLENBQWNGLEdBQWQsRUFBbUIsSUFBbkI7QUFDRCxLQUhEO0FBSUEsUUFBSSxDQUFDcUosZ0JBQUwsRUFDRWhJLEdBQUcsQ0FBQ3pDLElBQUosQ0FBUyxLQUFULEVBQWdCLFlBQU07QUFDcEIvQyxNQUFBQSxLQUFLLENBQUMsV0FBRCxFQUFjLE1BQUksQ0FBQ2EsTUFBbkIsRUFBMkIsTUFBSSxDQUFDQyxHQUFoQyxDQUFMLENBRG9CLENBRXBCOztBQUNBLE1BQUEsTUFBSSxDQUFDcUYsSUFBTCxDQUFVLEtBQVY7O0FBQ0EsTUFBQSxNQUFJLENBQUM5QixRQUFMLENBQWMsSUFBZCxFQUFvQixNQUFJLENBQUN3QixhQUFMLEVBQXBCO0FBQ0QsS0FMRDtBQU1ILEdBaEtEO0FBa0tBLE9BQUtNLElBQUwsQ0FBVSxTQUFWLEVBQXFCLElBQXJCOztBQUVBLE1BQU0ySCxrQkFBa0IsR0FBRyxTQUFyQkEsa0JBQXFCLEdBQU07QUFDL0IsUUFBTUMsZ0JBQWdCLEdBQUcsSUFBekI7QUFDQSxRQUFNQyxLQUFLLEdBQUduTSxHQUFHLENBQUN3SyxTQUFKLENBQWMsZ0JBQWQsQ0FBZDtBQUNBLFFBQUk0QixNQUFNLEdBQUcsQ0FBYjtBQUVBLFFBQU1DLFFBQVEsR0FBRyxJQUFJN08sTUFBTSxDQUFDOE8sU0FBWCxFQUFqQjs7QUFDQUQsSUFBQUEsUUFBUSxDQUFDRSxVQUFULEdBQXNCLFVBQUNDLEtBQUQsRUFBUWxKLFFBQVIsRUFBa0JtSixFQUFsQixFQUF5QjtBQUM3Q0wsTUFBQUEsTUFBTSxJQUFJSSxLQUFLLENBQUNsTixNQUFoQjs7QUFDQSxNQUFBLE1BQUksQ0FBQ2dGLElBQUwsQ0FBVSxVQUFWLEVBQXNCO0FBQ3BCb0ksUUFBQUEsU0FBUyxFQUFFLFFBRFM7QUFFcEJSLFFBQUFBLGdCQUFnQixFQUFoQkEsZ0JBRm9CO0FBR3BCRSxRQUFBQSxNQUFNLEVBQU5BLE1BSG9CO0FBSXBCRCxRQUFBQSxLQUFLLEVBQUxBO0FBSm9CLE9BQXRCOztBQU1BTSxNQUFBQSxFQUFFLENBQUMsSUFBRCxFQUFPRCxLQUFQLENBQUY7QUFDRCxLQVREOztBQVdBLFdBQU9ILFFBQVA7QUFDRCxHQWxCRDs7QUFvQkEsTUFBTU0sY0FBYyxHQUFHLFNBQWpCQSxjQUFpQixDQUFBN00sTUFBTSxFQUFJO0FBQy9CLFFBQU04TSxTQUFTLEdBQUcsS0FBSyxJQUF2QixDQUQrQixDQUNGOztBQUM3QixRQUFNQyxRQUFRLEdBQUcsSUFBSXJQLE1BQU0sQ0FBQ3NQLFFBQVgsRUFBakI7QUFDQSxRQUFNQyxXQUFXLEdBQUdqTixNQUFNLENBQUNSLE1BQTNCO0FBQ0EsUUFBTTBOLFNBQVMsR0FBR0QsV0FBVyxHQUFHSCxTQUFoQztBQUNBLFFBQU1LLE1BQU0sR0FBR0YsV0FBVyxHQUFHQyxTQUE3Qjs7QUFFQSxTQUFLLElBQUk3RixDQUFDLEdBQUcsQ0FBYixFQUFnQkEsQ0FBQyxHQUFHOEYsTUFBcEIsRUFBNEI5RixDQUFDLElBQUl5RixTQUFqQyxFQUE0QztBQUMxQyxVQUFNSixLQUFLLEdBQUcxTSxNQUFNLENBQUNtSCxLQUFQLENBQWFFLENBQWIsRUFBZ0JBLENBQUMsR0FBR3lGLFNBQXBCLENBQWQ7QUFDQUMsTUFBQUEsUUFBUSxDQUFDNUosSUFBVCxDQUFjdUosS0FBZDtBQUNEOztBQUVELFFBQUlRLFNBQVMsR0FBRyxDQUFoQixFQUFtQjtBQUNqQixVQUFNRSxlQUFlLEdBQUdwTixNQUFNLENBQUNtSCxLQUFQLENBQWEsQ0FBQytGLFNBQWQsQ0FBeEI7QUFDQUgsTUFBQUEsUUFBUSxDQUFDNUosSUFBVCxDQUFjaUssZUFBZDtBQUNEOztBQUVETCxJQUFBQSxRQUFRLENBQUM1SixJQUFULENBQWMsSUFBZCxFQWpCK0IsQ0FpQlY7O0FBRXJCLFdBQU80SixRQUFQO0FBQ0QsR0FwQkQsQ0E5TmtDLENBb1BsQzs7O0FBQ0EsTUFBTU0sUUFBUSxHQUFHLEtBQUsxTSxTQUF0Qjs7QUFDQSxNQUFJME0sUUFBSixFQUFjO0FBQ1o7QUFDQSxRQUFNM0ksT0FBTyxHQUFHMkksUUFBUSxDQUFDeEksVUFBVCxFQUFoQjs7QUFDQSxTQUFLLElBQU13QyxDQUFYLElBQWdCM0MsT0FBaEIsRUFBeUI7QUFDdkIsVUFBSXRCLE1BQU0sQ0FBQzVCLFNBQVAsQ0FBaUJzSCxjQUFqQixDQUFnQ3pJLElBQWhDLENBQXFDcUUsT0FBckMsRUFBOEMyQyxDQUE5QyxDQUFKLEVBQXNEO0FBQ3BEaEosUUFBQUEsS0FBSyxDQUFDLG1DQUFELEVBQXNDZ0osQ0FBdEMsRUFBeUMzQyxPQUFPLENBQUMyQyxDQUFELENBQWhELENBQUw7QUFDQW5ILFFBQUFBLEdBQUcsQ0FBQ3dJLFNBQUosQ0FBY3JCLENBQWQsRUFBaUIzQyxPQUFPLENBQUMyQyxDQUFELENBQXhCO0FBQ0Q7QUFDRixLQVJXLENBVVo7QUFDQTs7O0FBQ0FnRyxJQUFBQSxRQUFRLENBQUNDLFNBQVQsQ0FBbUIsVUFBQzlLLEdBQUQsRUFBTWhELE1BQU4sRUFBaUI7QUFDbEM7QUFFQW5CLE1BQUFBLEtBQUssQ0FBQyxpQ0FBRCxFQUFvQ21CLE1BQXBDLENBQUw7O0FBQ0EsVUFBSSxPQUFPQSxNQUFQLEtBQWtCLFFBQXRCLEVBQWdDO0FBQzlCVSxRQUFBQSxHQUFHLENBQUN3SSxTQUFKLENBQWMsZ0JBQWQsRUFBZ0NsSixNQUFoQztBQUNEOztBQUVENk4sTUFBQUEsUUFBUSxDQUFDNUosSUFBVCxDQUFjMEksa0JBQWtCLEVBQWhDLEVBQW9DMUksSUFBcEMsQ0FBeUN2RCxHQUF6QztBQUNELEtBVEQ7QUFVRCxHQXRCRCxNQXNCTyxJQUFJdUYsTUFBTSxDQUFDVSxRQUFQLENBQWdCNUMsSUFBaEIsQ0FBSixFQUEyQjtBQUNoQ3NKLElBQUFBLGNBQWMsQ0FBQ3RKLElBQUQsQ0FBZCxDQUNHRSxJQURILENBQ1EwSSxrQkFBa0IsRUFEMUIsRUFFRzFJLElBRkgsQ0FFUXZELEdBRlI7QUFHRCxHQUpNLE1BSUE7QUFDTEEsSUFBQUEsR0FBRyxDQUFDWixHQUFKLENBQVFpRSxJQUFSO0FBQ0Q7QUFDRixDQW5SRCxDLENBcVJBOzs7QUFDQWxFLE9BQU8sQ0FBQ21DLFNBQVIsQ0FBa0I0QyxZQUFsQixHQUFpQyxVQUFBUCxHQUFHLEVBQUk7QUFDdEMsTUFBSUEsR0FBRyxDQUFDRSxVQUFKLEtBQW1CLEdBQW5CLElBQTBCRixHQUFHLENBQUNFLFVBQUosS0FBbUIsR0FBakQsRUFBc0Q7QUFDcEQ7QUFDQSxXQUFPLEtBQVA7QUFDRCxHQUpxQyxDQU10Qzs7O0FBQ0EsTUFBSUYsR0FBRyxDQUFDYSxPQUFKLENBQVksZ0JBQVosTUFBa0MsR0FBdEMsRUFBMkM7QUFDekM7QUFDQSxXQUFPLEtBQVA7QUFDRCxHQVZxQyxDQVl0Qzs7O0FBQ0EsU0FBTywyQkFBMkIrQyxJQUEzQixDQUFnQzVELEdBQUcsQ0FBQ2EsT0FBSixDQUFZLGtCQUFaLENBQWhDLENBQVA7QUFDRCxDQWREO0FBZ0JBOzs7Ozs7Ozs7Ozs7Ozs7QUFhQXJGLE9BQU8sQ0FBQ21DLFNBQVIsQ0FBa0IrTCxPQUFsQixHQUE0QixVQUFTQyxlQUFULEVBQTBCO0FBQ3BELE1BQUksT0FBT0EsZUFBUCxLQUEyQixRQUEvQixFQUF5QztBQUN2QyxTQUFLMUYsZ0JBQUwsR0FBd0I7QUFBRSxXQUFLMEY7QUFBUCxLQUF4QjtBQUNELEdBRkQsTUFFTyxJQUFJLFFBQU9BLGVBQVAsTUFBMkIsUUFBL0IsRUFBeUM7QUFDOUMsU0FBSzFGLGdCQUFMLEdBQXdCMEYsZUFBeEI7QUFDRCxHQUZNLE1BRUE7QUFDTCxTQUFLMUYsZ0JBQUwsR0FBd0JwRyxTQUF4QjtBQUNEOztBQUVELFNBQU8sSUFBUDtBQUNELENBVkQ7O0FBWUFyQyxPQUFPLENBQUNtQyxTQUFSLENBQWtCaU0sY0FBbEIsR0FBbUMsVUFBU0MsTUFBVCxFQUFpQjtBQUNsRCxPQUFLcEYsZUFBTCxHQUF1Qm9GLE1BQU0sS0FBS2hNLFNBQVgsR0FBdUIsSUFBdkIsR0FBOEJnTSxNQUFyRDtBQUNBLFNBQU8sSUFBUDtBQUNELENBSEQsQyxDQUtBOzs7QUFDQSxJQUFJLENBQUN4UCxPQUFPLENBQUM0RSxRQUFSLENBQWlCLEtBQWpCLENBQUwsRUFBOEI7QUFDNUI7QUFDQTtBQUNBO0FBQ0E1RSxFQUFBQSxPQUFPLEdBQUdBLE9BQU8sQ0FBQ2lKLEtBQVIsQ0FBYyxDQUFkLENBQVY7QUFDQWpKLEVBQUFBLE9BQU8sQ0FBQ2lGLElBQVIsQ0FBYSxLQUFiO0FBQ0Q7O0FBRURqRixPQUFPLENBQUN5UCxPQUFSLENBQWdCLFVBQUF6TyxNQUFNLEVBQUk7QUFDeEIsTUFBTTBPLElBQUksR0FBRzFPLE1BQWI7QUFDQUEsRUFBQUEsTUFBTSxHQUFHQSxNQUFNLEtBQUssS0FBWCxHQUFtQixRQUFuQixHQUE4QkEsTUFBdkM7QUFFQUEsRUFBQUEsTUFBTSxHQUFHQSxNQUFNLENBQUMyTyxXQUFQLEVBQVQ7O0FBQ0E1TyxFQUFBQSxPQUFPLENBQUMyTyxJQUFELENBQVAsR0FBZ0IsVUFBQ3pPLEdBQUQsRUFBTW9FLElBQU4sRUFBWWlHLEVBQVosRUFBbUI7QUFDakMsUUFBTXRKLEdBQUcsR0FBR2pCLE9BQU8sQ0FBQ0MsTUFBRCxFQUFTQyxHQUFULENBQW5COztBQUNBLFFBQUksT0FBT29FLElBQVAsS0FBZ0IsVUFBcEIsRUFBZ0M7QUFDOUJpRyxNQUFBQSxFQUFFLEdBQUdqRyxJQUFMO0FBQ0FBLE1BQUFBLElBQUksR0FBRyxJQUFQO0FBQ0Q7O0FBRUQsUUFBSUEsSUFBSixFQUFVO0FBQ1IsVUFBSXJFLE1BQU0sS0FBSyxLQUFYLElBQW9CQSxNQUFNLEtBQUssTUFBbkMsRUFBMkM7QUFDekNnQixRQUFBQSxHQUFHLENBQUMrQyxLQUFKLENBQVVNLElBQVY7QUFDRCxPQUZELE1BRU87QUFDTHJELFFBQUFBLEdBQUcsQ0FBQzROLElBQUosQ0FBU3ZLLElBQVQ7QUFDRDtBQUNGOztBQUVELFFBQUlpRyxFQUFKLEVBQVF0SixHQUFHLENBQUNaLEdBQUosQ0FBUWtLLEVBQVI7QUFDUixXQUFPdEosR0FBUDtBQUNELEdBakJEO0FBa0JELENBdkJEO0FBeUJBOzs7Ozs7OztBQVFBLFNBQVN5TCxNQUFULENBQWdCMU4sSUFBaEIsRUFBc0I7QUFDcEIsTUFBTThQLEtBQUssR0FBRzlQLElBQUksQ0FBQzBKLEtBQUwsQ0FBVyxHQUFYLENBQWQ7QUFDQSxNQUFNL0UsSUFBSSxHQUFHbUwsS0FBSyxDQUFDLENBQUQsQ0FBbEI7QUFDQSxNQUFNQyxPQUFPLEdBQUdELEtBQUssQ0FBQyxDQUFELENBQXJCO0FBRUEsU0FBT25MLElBQUksS0FBSyxNQUFULElBQW1Cb0wsT0FBTyxLQUFLLHVCQUF0QztBQUNEOztBQUVELFNBQVN2QyxjQUFULENBQXdCeE4sSUFBeEIsRUFBOEI7QUFDNUIsTUFBTTJFLElBQUksR0FBRzNFLElBQUksQ0FBQzBKLEtBQUwsQ0FBVyxHQUFYLEVBQWdCLENBQWhCLENBQWI7QUFFQSxTQUFPL0UsSUFBSSxLQUFLLE9BQVQsSUFBb0JBLElBQUksS0FBSyxPQUFwQztBQUNEO0FBRUQ7Ozs7Ozs7OztBQVFBLFNBQVNnSSxNQUFULENBQWdCM00sSUFBaEIsRUFBc0I7QUFDcEI7QUFDQTtBQUNBLFNBQU8scUJBQXFCd0osSUFBckIsQ0FBMEJ4SixJQUExQixDQUFQO0FBQ0Q7QUFFRDs7Ozs7Ozs7O0FBUUEsU0FBUzZGLFVBQVQsQ0FBb0JTLElBQXBCLEVBQTBCO0FBQ3hCLFNBQU8sQ0FBQyxHQUFELEVBQU0sR0FBTixFQUFXLEdBQVgsRUFBZ0IsR0FBaEIsRUFBcUIsR0FBckIsRUFBMEIsR0FBMUIsRUFBK0J6QixRQUEvQixDQUF3Q3lCLElBQXhDLENBQVA7QUFDRCIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogTW9kdWxlIGRlcGVuZGVuY2llcy5cbiAqL1xuXG4vLyBlc2xpbnQtZGlzYWJsZS1uZXh0LWxpbmUgbm9kZS9uby1kZXByZWNhdGVkLWFwaVxuY29uc3QgeyBwYXJzZSwgZm9ybWF0LCByZXNvbHZlIH0gPSByZXF1aXJlKCd1cmwnKTtcbmNvbnN0IFN0cmVhbSA9IHJlcXVpcmUoJ3N0cmVhbScpO1xuY29uc3QgaHR0cHMgPSByZXF1aXJlKCdodHRwcycpO1xuY29uc3QgaHR0cCA9IHJlcXVpcmUoJ2h0dHAnKTtcbmNvbnN0IGZzID0gcmVxdWlyZSgnZnMnKTtcbmNvbnN0IHpsaWIgPSByZXF1aXJlKCd6bGliJyk7XG5jb25zdCB1dGlsID0gcmVxdWlyZSgndXRpbCcpO1xuY29uc3QgcXMgPSByZXF1aXJlKCdxcycpO1xuY29uc3QgbWltZSA9IHJlcXVpcmUoJ21pbWUnKTtcbmxldCBtZXRob2RzID0gcmVxdWlyZSgnbWV0aG9kcycpO1xuY29uc3QgRm9ybURhdGEgPSByZXF1aXJlKCdmb3JtLWRhdGEnKTtcbmNvbnN0IGZvcm1pZGFibGUgPSByZXF1aXJlKCdmb3JtaWRhYmxlJyk7XG5jb25zdCBkZWJ1ZyA9IHJlcXVpcmUoJ2RlYnVnJykoJ3N1cGVyYWdlbnQnKTtcbmNvbnN0IENvb2tpZUphciA9IHJlcXVpcmUoJ2Nvb2tpZWphcicpO1xuY29uc3Qgc2VtdmVyID0gcmVxdWlyZSgnc2VtdmVyJyk7XG5jb25zdCBzYWZlU3RyaW5naWZ5ID0gcmVxdWlyZSgnZmFzdC1zYWZlLXN0cmluZ2lmeScpO1xuXG5jb25zdCB1dGlscyA9IHJlcXVpcmUoJy4uL3V0aWxzJyk7XG5jb25zdCBSZXF1ZXN0QmFzZSA9IHJlcXVpcmUoJy4uL3JlcXVlc3QtYmFzZScpO1xuY29uc3QgeyB1bnppcCB9ID0gcmVxdWlyZSgnLi91bnppcCcpO1xuY29uc3QgUmVzcG9uc2UgPSByZXF1aXJlKCcuL3Jlc3BvbnNlJyk7XG5cbmxldCBodHRwMjtcblxuaWYgKHNlbXZlci5ndGUocHJvY2Vzcy52ZXJzaW9uLCAndjEwLjEwLjAnKSkgaHR0cDIgPSByZXF1aXJlKCcuL2h0dHAyd3JhcHBlcicpO1xuXG5mdW5jdGlvbiByZXF1ZXN0KG1ldGhvZCwgdXJsKSB7XG4gIC8vIGNhbGxiYWNrXG4gIGlmICh0eXBlb2YgdXJsID09PSAnZnVuY3Rpb24nKSB7XG4gICAgcmV0dXJuIG5ldyBleHBvcnRzLlJlcXVlc3QoJ0dFVCcsIG1ldGhvZCkuZW5kKHVybCk7XG4gIH1cblxuICAvLyB1cmwgZmlyc3RcbiAgaWYgKGFyZ3VtZW50cy5sZW5ndGggPT09IDEpIHtcbiAgICByZXR1cm4gbmV3IGV4cG9ydHMuUmVxdWVzdCgnR0VUJywgbWV0aG9kKTtcbiAgfVxuXG4gIHJldHVybiBuZXcgZXhwb3J0cy5SZXF1ZXN0KG1ldGhvZCwgdXJsKTtcbn1cblxubW9kdWxlLmV4cG9ydHMgPSByZXF1ZXN0O1xuZXhwb3J0cyA9IG1vZHVsZS5leHBvcnRzO1xuXG4vKipcbiAqIEV4cG9zZSBgUmVxdWVzdGAuXG4gKi9cblxuZXhwb3J0cy5SZXF1ZXN0ID0gUmVxdWVzdDtcblxuLyoqXG4gKiBFeHBvc2UgdGhlIGFnZW50IGZ1bmN0aW9uXG4gKi9cblxuZXhwb3J0cy5hZ2VudCA9IHJlcXVpcmUoJy4vYWdlbnQnKTtcblxuLyoqXG4gKiBOb29wLlxuICovXG5cbmZ1bmN0aW9uIG5vb3AoKSB7fVxuXG4vKipcbiAqIEV4cG9zZSBgUmVzcG9uc2VgLlxuICovXG5cbmV4cG9ydHMuUmVzcG9uc2UgPSBSZXNwb25zZTtcblxuLyoqXG4gKiBEZWZpbmUgXCJmb3JtXCIgbWltZSB0eXBlLlxuICovXG5cbm1pbWUuZGVmaW5lKFxuICB7XG4gICAgJ2FwcGxpY2F0aW9uL3gtd3d3LWZvcm0tdXJsZW5jb2RlZCc6IFsnZm9ybScsICd1cmxlbmNvZGVkJywgJ2Zvcm0tZGF0YSddXG4gIH0sXG4gIHRydWVcbik7XG5cbi8qKlxuICogUHJvdG9jb2wgbWFwLlxuICovXG5cbmV4cG9ydHMucHJvdG9jb2xzID0ge1xuICAnaHR0cDonOiBodHRwLFxuICAnaHR0cHM6JzogaHR0cHMsXG4gICdodHRwMjonOiBodHRwMlxufTtcblxuLyoqXG4gKiBEZWZhdWx0IHNlcmlhbGl6YXRpb24gbWFwLlxuICpcbiAqICAgICBzdXBlcmFnZW50LnNlcmlhbGl6ZVsnYXBwbGljYXRpb24veG1sJ10gPSBmdW5jdGlvbihvYmope1xuICogICAgICAgcmV0dXJuICdnZW5lcmF0ZWQgeG1sIGhlcmUnO1xuICogICAgIH07XG4gKlxuICovXG5cbmV4cG9ydHMuc2VyaWFsaXplID0ge1xuICAnYXBwbGljYXRpb24veC13d3ctZm9ybS11cmxlbmNvZGVkJzogcXMuc3RyaW5naWZ5LFxuICAnYXBwbGljYXRpb24vanNvbic6IHNhZmVTdHJpbmdpZnlcbn07XG5cbi8qKlxuICogRGVmYXVsdCBwYXJzZXJzLlxuICpcbiAqICAgICBzdXBlcmFnZW50LnBhcnNlWydhcHBsaWNhdGlvbi94bWwnXSA9IGZ1bmN0aW9uKHJlcywgZm4pe1xuICogICAgICAgZm4obnVsbCwgcmVzKTtcbiAqICAgICB9O1xuICpcbiAqL1xuXG5leHBvcnRzLnBhcnNlID0gcmVxdWlyZSgnLi9wYXJzZXJzJyk7XG5cbi8qKlxuICogRGVmYXVsdCBidWZmZXJpbmcgbWFwLiBDYW4gYmUgdXNlZCB0byBzZXQgY2VydGFpblxuICogcmVzcG9uc2UgdHlwZXMgdG8gYnVmZmVyL25vdCBidWZmZXIuXG4gKlxuICogICAgIHN1cGVyYWdlbnQuYnVmZmVyWydhcHBsaWNhdGlvbi94bWwnXSA9IHRydWU7XG4gKi9cbmV4cG9ydHMuYnVmZmVyID0ge307XG5cbi8qKlxuICogSW5pdGlhbGl6ZSBpbnRlcm5hbCBoZWFkZXIgdHJhY2tpbmcgcHJvcGVydGllcyBvbiBhIHJlcXVlc3QgaW5zdGFuY2UuXG4gKlxuICogQHBhcmFtIHtPYmplY3R9IHJlcSB0aGUgaW5zdGFuY2VcbiAqIEBhcGkgcHJpdmF0ZVxuICovXG5mdW5jdGlvbiBfaW5pdEhlYWRlcnMocmVxKSB7XG4gIHJlcS5faGVhZGVyID0ge1xuICAgIC8vIGNvZXJjZXMgaGVhZGVyIG5hbWVzIHRvIGxvd2VyY2FzZVxuICB9O1xuICByZXEuaGVhZGVyID0ge1xuICAgIC8vIHByZXNlcnZlcyBoZWFkZXIgbmFtZSBjYXNlXG4gIH07XG59XG5cbi8qKlxuICogSW5pdGlhbGl6ZSBhIG5ldyBgUmVxdWVzdGAgd2l0aCB0aGUgZ2l2ZW4gYG1ldGhvZGAgYW5kIGB1cmxgLlxuICpcbiAqIEBwYXJhbSB7U3RyaW5nfSBtZXRob2RcbiAqIEBwYXJhbSB7U3RyaW5nfE9iamVjdH0gdXJsXG4gKiBAYXBpIHB1YmxpY1xuICovXG5cbmZ1bmN0aW9uIFJlcXVlc3QobWV0aG9kLCB1cmwpIHtcbiAgU3RyZWFtLmNhbGwodGhpcyk7XG4gIGlmICh0eXBlb2YgdXJsICE9PSAnc3RyaW5nJykgdXJsID0gZm9ybWF0KHVybCk7XG4gIHRoaXMuX2VuYWJsZUh0dHAyID0gQm9vbGVhbihwcm9jZXNzLmVudi5IVFRQMl9URVNUKTsgLy8gaW50ZXJuYWwgb25seVxuICB0aGlzLl9hZ2VudCA9IGZhbHNlO1xuICB0aGlzLl9mb3JtRGF0YSA9IG51bGw7XG4gIHRoaXMubWV0aG9kID0gbWV0aG9kO1xuICB0aGlzLnVybCA9IHVybDtcbiAgX2luaXRIZWFkZXJzKHRoaXMpO1xuICB0aGlzLndyaXRhYmxlID0gdHJ1ZTtcbiAgdGhpcy5fcmVkaXJlY3RzID0gMDtcbiAgdGhpcy5yZWRpcmVjdHMobWV0aG9kID09PSAnSEVBRCcgPyAwIDogNSk7XG4gIHRoaXMuY29va2llcyA9ICcnO1xuICB0aGlzLnFzID0ge307XG4gIHRoaXMuX3F1ZXJ5ID0gW107XG4gIHRoaXMucXNSYXcgPSB0aGlzLl9xdWVyeTsgLy8gVW51c2VkLCBmb3IgYmFja3dhcmRzIGNvbXBhdGliaWxpdHkgb25seVxuICB0aGlzLl9yZWRpcmVjdExpc3QgPSBbXTtcbiAgdGhpcy5fc3RyZWFtUmVxdWVzdCA9IGZhbHNlO1xuICB0aGlzLm9uY2UoJ2VuZCcsIHRoaXMuY2xlYXJUaW1lb3V0LmJpbmQodGhpcykpO1xufVxuXG4vKipcbiAqIEluaGVyaXQgZnJvbSBgU3RyZWFtYCAod2hpY2ggaW5oZXJpdHMgZnJvbSBgRXZlbnRFbWl0dGVyYCkuXG4gKiBNaXhpbiBgUmVxdWVzdEJhc2VgLlxuICovXG51dGlsLmluaGVyaXRzKFJlcXVlc3QsIFN0cmVhbSk7XG4vLyBlc2xpbnQtZGlzYWJsZS1uZXh0LWxpbmUgbmV3LWNhcFxuUmVxdWVzdEJhc2UoUmVxdWVzdC5wcm90b3R5cGUpO1xuXG4vKipcbiAqIEVuYWJsZSBvciBEaXNhYmxlIGh0dHAyLlxuICpcbiAqIEVuYWJsZSBodHRwMi5cbiAqXG4gKiBgYGAganNcbiAqIHJlcXVlc3QuZ2V0KCdodHRwOi8vbG9jYWxob3N0LycpXG4gKiAgIC5odHRwMigpXG4gKiAgIC5lbmQoY2FsbGJhY2spO1xuICpcbiAqIHJlcXVlc3QuZ2V0KCdodHRwOi8vbG9jYWxob3N0LycpXG4gKiAgIC5odHRwMih0cnVlKVxuICogICAuZW5kKGNhbGxiYWNrKTtcbiAqIGBgYFxuICpcbiAqIERpc2FibGUgaHR0cDIuXG4gKlxuICogYGBgIGpzXG4gKiByZXF1ZXN0ID0gcmVxdWVzdC5odHRwMigpO1xuICogcmVxdWVzdC5nZXQoJ2h0dHA6Ly9sb2NhbGhvc3QvJylcbiAqICAgLmh0dHAyKGZhbHNlKVxuICogICAuZW5kKGNhbGxiYWNrKTtcbiAqIGBgYFxuICpcbiAqIEBwYXJhbSB7Qm9vbGVhbn0gZW5hYmxlXG4gKiBAcmV0dXJuIHtSZXF1ZXN0fSBmb3IgY2hhaW5pbmdcbiAqIEBhcGkgcHVibGljXG4gKi9cblxuUmVxdWVzdC5wcm90b3R5cGUuaHR0cDIgPSBmdW5jdGlvbihib29sKSB7XG4gIGlmIChleHBvcnRzLnByb3RvY29sc1snaHR0cDI6J10gPT09IHVuZGVmaW5lZCkge1xuICAgIHRocm93IG5ldyBFcnJvcihcbiAgICAgICdzdXBlcmFnZW50OiB0aGlzIHZlcnNpb24gb2YgTm9kZS5qcyBkb2VzIG5vdCBzdXBwb3J0IGh0dHAyJ1xuICAgICk7XG4gIH1cblxuICB0aGlzLl9lbmFibGVIdHRwMiA9IGJvb2wgPT09IHVuZGVmaW5lZCA/IHRydWUgOiBib29sO1xuICByZXR1cm4gdGhpcztcbn07XG5cbi8qKlxuICogUXVldWUgdGhlIGdpdmVuIGBmaWxlYCBhcyBhbiBhdHRhY2htZW50IHRvIHRoZSBzcGVjaWZpZWQgYGZpZWxkYCxcbiAqIHdpdGggb3B0aW9uYWwgYG9wdGlvbnNgIChvciBmaWxlbmFtZSkuXG4gKlxuICogYGBgIGpzXG4gKiByZXF1ZXN0LnBvc3QoJ2h0dHA6Ly9sb2NhbGhvc3QvdXBsb2FkJylcbiAqICAgLmF0dGFjaCgnZmllbGQnLCBCdWZmZXIuZnJvbSgnPGI+SGVsbG8gd29ybGQ8L2I+JyksICdoZWxsby5odG1sJylcbiAqICAgLmVuZChjYWxsYmFjayk7XG4gKiBgYGBcbiAqXG4gKiBBIGZpbGVuYW1lIG1heSBhbHNvIGJlIHVzZWQ6XG4gKlxuICogYGBgIGpzXG4gKiByZXF1ZXN0LnBvc3QoJ2h0dHA6Ly9sb2NhbGhvc3QvdXBsb2FkJylcbiAqICAgLmF0dGFjaCgnZmlsZXMnLCAnaW1hZ2UuanBnJylcbiAqICAgLmVuZChjYWxsYmFjayk7XG4gKiBgYGBcbiAqXG4gKiBAcGFyYW0ge1N0cmluZ30gZmllbGRcbiAqIEBwYXJhbSB7U3RyaW5nfGZzLlJlYWRTdHJlYW18QnVmZmVyfSBmaWxlXG4gKiBAcGFyYW0ge1N0cmluZ3xPYmplY3R9IG9wdGlvbnNcbiAqIEByZXR1cm4ge1JlcXVlc3R9IGZvciBjaGFpbmluZ1xuICogQGFwaSBwdWJsaWNcbiAqL1xuXG5SZXF1ZXN0LnByb3RvdHlwZS5hdHRhY2ggPSBmdW5jdGlvbihmaWVsZCwgZmlsZSwgb3B0aW9ucykge1xuICBpZiAoZmlsZSkge1xuICAgIGlmICh0aGlzLl9kYXRhKSB7XG4gICAgICB0aHJvdyBuZXcgRXJyb3IoXCJzdXBlcmFnZW50IGNhbid0IG1peCAuc2VuZCgpIGFuZCAuYXR0YWNoKClcIik7XG4gICAgfVxuXG4gICAgbGV0IG8gPSBvcHRpb25zIHx8IHt9O1xuICAgIGlmICh0eXBlb2Ygb3B0aW9ucyA9PT0gJ3N0cmluZycpIHtcbiAgICAgIG8gPSB7IGZpbGVuYW1lOiBvcHRpb25zIH07XG4gICAgfVxuXG4gICAgaWYgKHR5cGVvZiBmaWxlID09PSAnc3RyaW5nJykge1xuICAgICAgaWYgKCFvLmZpbGVuYW1lKSBvLmZpbGVuYW1lID0gZmlsZTtcbiAgICAgIGRlYnVnKCdjcmVhdGluZyBgZnMuUmVhZFN0cmVhbWAgaW5zdGFuY2UgZm9yIGZpbGU6ICVzJywgZmlsZSk7XG4gICAgICBmaWxlID0gZnMuY3JlYXRlUmVhZFN0cmVhbShmaWxlKTtcbiAgICB9IGVsc2UgaWYgKCFvLmZpbGVuYW1lICYmIGZpbGUucGF0aCkge1xuICAgICAgby5maWxlbmFtZSA9IGZpbGUucGF0aDtcbiAgICB9XG5cbiAgICB0aGlzLl9nZXRGb3JtRGF0YSgpLmFwcGVuZChmaWVsZCwgZmlsZSwgbyk7XG4gIH1cblxuICByZXR1cm4gdGhpcztcbn07XG5cblJlcXVlc3QucHJvdG90eXBlLl9nZXRGb3JtRGF0YSA9IGZ1bmN0aW9uKCkge1xuICBpZiAoIXRoaXMuX2Zvcm1EYXRhKSB7XG4gICAgdGhpcy5fZm9ybURhdGEgPSBuZXcgRm9ybURhdGEoKTtcbiAgICB0aGlzLl9mb3JtRGF0YS5vbignZXJyb3InLCBlcnIgPT4ge1xuICAgICAgZGVidWcoJ0Zvcm1EYXRhIGVycm9yJywgZXJyKTtcbiAgICAgIGlmICh0aGlzLmNhbGxlZCkge1xuICAgICAgICAvLyBUaGUgcmVxdWVzdCBoYXMgYWxyZWFkeSBmaW5pc2hlZCBhbmQgdGhlIGNhbGxiYWNrIHdhcyBjYWxsZWQuXG4gICAgICAgIC8vIFNpbGVudGx5IGlnbm9yZSB0aGUgZXJyb3IuXG4gICAgICAgIHJldHVybjtcbiAgICAgIH1cblxuICAgICAgdGhpcy5jYWxsYmFjayhlcnIpO1xuICAgICAgdGhpcy5hYm9ydCgpO1xuICAgIH0pO1xuICB9XG5cbiAgcmV0dXJuIHRoaXMuX2Zvcm1EYXRhO1xufTtcblxuLyoqXG4gKiBHZXRzL3NldHMgdGhlIGBBZ2VudGAgdG8gdXNlIGZvciB0aGlzIEhUVFAgcmVxdWVzdC4gVGhlIGRlZmF1bHQgKGlmIHRoaXNcbiAqIGZ1bmN0aW9uIGlzIG5vdCBjYWxsZWQpIGlzIHRvIG9wdCBvdXQgb2YgY29ubmVjdGlvbiBwb29saW5nIChgYWdlbnQ6IGZhbHNlYCkuXG4gKlxuICogQHBhcmFtIHtodHRwLkFnZW50fSBhZ2VudFxuICogQHJldHVybiB7aHR0cC5BZ2VudH1cbiAqIEBhcGkgcHVibGljXG4gKi9cblxuUmVxdWVzdC5wcm90b3R5cGUuYWdlbnQgPSBmdW5jdGlvbihhZ2VudCkge1xuICBpZiAoYXJndW1lbnRzLmxlbmd0aCA9PT0gMCkgcmV0dXJuIHRoaXMuX2FnZW50O1xuICB0aGlzLl9hZ2VudCA9IGFnZW50O1xuICByZXR1cm4gdGhpcztcbn07XG5cbi8qKlxuICogU2V0IF9Db250ZW50LVR5cGVfIHJlc3BvbnNlIGhlYWRlciBwYXNzZWQgdGhyb3VnaCBgbWltZS5nZXRUeXBlKClgLlxuICpcbiAqIEV4YW1wbGVzOlxuICpcbiAqICAgICAgcmVxdWVzdC5wb3N0KCcvJylcbiAqICAgICAgICAudHlwZSgneG1sJylcbiAqICAgICAgICAuc2VuZCh4bWxzdHJpbmcpXG4gKiAgICAgICAgLmVuZChjYWxsYmFjayk7XG4gKlxuICogICAgICByZXF1ZXN0LnBvc3QoJy8nKVxuICogICAgICAgIC50eXBlKCdqc29uJylcbiAqICAgICAgICAuc2VuZChqc29uc3RyaW5nKVxuICogICAgICAgIC5lbmQoY2FsbGJhY2spO1xuICpcbiAqICAgICAgcmVxdWVzdC5wb3N0KCcvJylcbiAqICAgICAgICAudHlwZSgnYXBwbGljYXRpb24vanNvbicpXG4gKiAgICAgICAgLnNlbmQoanNvbnN0cmluZylcbiAqICAgICAgICAuZW5kKGNhbGxiYWNrKTtcbiAqXG4gKiBAcGFyYW0ge1N0cmluZ30gdHlwZVxuICogQHJldHVybiB7UmVxdWVzdH0gZm9yIGNoYWluaW5nXG4gKiBAYXBpIHB1YmxpY1xuICovXG5cblJlcXVlc3QucHJvdG90eXBlLnR5cGUgPSBmdW5jdGlvbih0eXBlKSB7XG4gIHJldHVybiB0aGlzLnNldChcbiAgICAnQ29udGVudC1UeXBlJyxcbiAgICB0eXBlLmluY2x1ZGVzKCcvJykgPyB0eXBlIDogbWltZS5nZXRUeXBlKHR5cGUpXG4gICk7XG59O1xuXG4vKipcbiAqIFNldCBfQWNjZXB0XyByZXNwb25zZSBoZWFkZXIgcGFzc2VkIHRocm91Z2ggYG1pbWUuZ2V0VHlwZSgpYC5cbiAqXG4gKiBFeGFtcGxlczpcbiAqXG4gKiAgICAgIHN1cGVyYWdlbnQudHlwZXMuanNvbiA9ICdhcHBsaWNhdGlvbi9qc29uJztcbiAqXG4gKiAgICAgIHJlcXVlc3QuZ2V0KCcvYWdlbnQnKVxuICogICAgICAgIC5hY2NlcHQoJ2pzb24nKVxuICogICAgICAgIC5lbmQoY2FsbGJhY2spO1xuICpcbiAqICAgICAgcmVxdWVzdC5nZXQoJy9hZ2VudCcpXG4gKiAgICAgICAgLmFjY2VwdCgnYXBwbGljYXRpb24vanNvbicpXG4gKiAgICAgICAgLmVuZChjYWxsYmFjayk7XG4gKlxuICogQHBhcmFtIHtTdHJpbmd9IGFjY2VwdFxuICogQHJldHVybiB7UmVxdWVzdH0gZm9yIGNoYWluaW5nXG4gKiBAYXBpIHB1YmxpY1xuICovXG5cblJlcXVlc3QucHJvdG90eXBlLmFjY2VwdCA9IGZ1bmN0aW9uKHR5cGUpIHtcbiAgcmV0dXJuIHRoaXMuc2V0KCdBY2NlcHQnLCB0eXBlLmluY2x1ZGVzKCcvJykgPyB0eXBlIDogbWltZS5nZXRUeXBlKHR5cGUpKTtcbn07XG5cbi8qKlxuICogQWRkIHF1ZXJ5LXN0cmluZyBgdmFsYC5cbiAqXG4gKiBFeGFtcGxlczpcbiAqXG4gKiAgIHJlcXVlc3QuZ2V0KCcvc2hvZXMnKVxuICogICAgIC5xdWVyeSgnc2l6ZT0xMCcpXG4gKiAgICAgLnF1ZXJ5KHsgY29sb3I6ICdibHVlJyB9KVxuICpcbiAqIEBwYXJhbSB7T2JqZWN0fFN0cmluZ30gdmFsXG4gKiBAcmV0dXJuIHtSZXF1ZXN0fSBmb3IgY2hhaW5pbmdcbiAqIEBhcGkgcHVibGljXG4gKi9cblxuUmVxdWVzdC5wcm90b3R5cGUucXVlcnkgPSBmdW5jdGlvbih2YWwpIHtcbiAgaWYgKHR5cGVvZiB2YWwgPT09ICdzdHJpbmcnKSB7XG4gICAgdGhpcy5fcXVlcnkucHVzaCh2YWwpO1xuICB9IGVsc2Uge1xuICAgIE9iamVjdC5hc3NpZ24odGhpcy5xcywgdmFsKTtcbiAgfVxuXG4gIHJldHVybiB0aGlzO1xufTtcblxuLyoqXG4gKiBXcml0ZSByYXcgYGRhdGFgIC8gYGVuY29kaW5nYCB0byB0aGUgc29ja2V0LlxuICpcbiAqIEBwYXJhbSB7QnVmZmVyfFN0cmluZ30gZGF0YVxuICogQHBhcmFtIHtTdHJpbmd9IGVuY29kaW5nXG4gKiBAcmV0dXJuIHtCb29sZWFufVxuICogQGFwaSBwdWJsaWNcbiAqL1xuXG5SZXF1ZXN0LnByb3RvdHlwZS53cml0ZSA9IGZ1bmN0aW9uKGRhdGEsIGVuY29kaW5nKSB7XG4gIGNvbnN0IHJlcSA9IHRoaXMucmVxdWVzdCgpO1xuICBpZiAoIXRoaXMuX3N0cmVhbVJlcXVlc3QpIHtcbiAgICB0aGlzLl9zdHJlYW1SZXF1ZXN0ID0gdHJ1ZTtcbiAgfVxuXG4gIHJldHVybiByZXEud3JpdGUoZGF0YSwgZW5jb2RpbmcpO1xufTtcblxuLyoqXG4gKiBQaXBlIHRoZSByZXF1ZXN0IGJvZHkgdG8gYHN0cmVhbWAuXG4gKlxuICogQHBhcmFtIHtTdHJlYW19IHN0cmVhbVxuICogQHBhcmFtIHtPYmplY3R9IG9wdGlvbnNcbiAqIEByZXR1cm4ge1N0cmVhbX1cbiAqIEBhcGkgcHVibGljXG4gKi9cblxuUmVxdWVzdC5wcm90b3R5cGUucGlwZSA9IGZ1bmN0aW9uKHN0cmVhbSwgb3B0aW9ucykge1xuICB0aGlzLnBpcGVkID0gdHJ1ZTsgLy8gSEFDSy4uLlxuICB0aGlzLmJ1ZmZlcihmYWxzZSk7XG4gIHRoaXMuZW5kKCk7XG4gIHJldHVybiB0aGlzLl9waXBlQ29udGludWUoc3RyZWFtLCBvcHRpb25zKTtcbn07XG5cblJlcXVlc3QucHJvdG90eXBlLl9waXBlQ29udGludWUgPSBmdW5jdGlvbihzdHJlYW0sIG9wdGlvbnMpIHtcbiAgdGhpcy5yZXEub25jZSgncmVzcG9uc2UnLCByZXMgPT4ge1xuICAgIC8vIHJlZGlyZWN0XG4gICAgaWYgKFxuICAgICAgaXNSZWRpcmVjdChyZXMuc3RhdHVzQ29kZSkgJiZcbiAgICAgIHRoaXMuX3JlZGlyZWN0cysrICE9PSB0aGlzLl9tYXhSZWRpcmVjdHNcbiAgICApIHtcbiAgICAgIHJldHVybiB0aGlzLl9yZWRpcmVjdChyZXMpID09PSB0aGlzXG4gICAgICAgID8gdGhpcy5fcGlwZUNvbnRpbnVlKHN0cmVhbSwgb3B0aW9ucylcbiAgICAgICAgOiB1bmRlZmluZWQ7XG4gICAgfVxuXG4gICAgdGhpcy5yZXMgPSByZXM7XG4gICAgdGhpcy5fZW1pdFJlc3BvbnNlKCk7XG4gICAgaWYgKHRoaXMuX2Fib3J0ZWQpIHJldHVybjtcblxuICAgIGlmICh0aGlzLl9zaG91bGRVbnppcChyZXMpKSB7XG4gICAgICBjb25zdCB1bnppcE9iaiA9IHpsaWIuY3JlYXRlVW56aXAoKTtcbiAgICAgIHVuemlwT2JqLm9uKCdlcnJvcicsIGVyciA9PiB7XG4gICAgICAgIGlmIChlcnIgJiYgZXJyLmNvZGUgPT09ICdaX0JVRl9FUlJPUicpIHtcbiAgICAgICAgICAvLyB1bmV4cGVjdGVkIGVuZCBvZiBmaWxlIGlzIGlnbm9yZWQgYnkgYnJvd3NlcnMgYW5kIGN1cmxcbiAgICAgICAgICBzdHJlYW0uZW1pdCgnZW5kJyk7XG4gICAgICAgICAgcmV0dXJuO1xuICAgICAgICB9XG5cbiAgICAgICAgc3RyZWFtLmVtaXQoJ2Vycm9yJywgZXJyKTtcbiAgICAgIH0pO1xuICAgICAgcmVzLnBpcGUodW56aXBPYmopLnBpcGUoc3RyZWFtLCBvcHRpb25zKTtcbiAgICB9IGVsc2Uge1xuICAgICAgcmVzLnBpcGUoc3RyZWFtLCBvcHRpb25zKTtcbiAgICB9XG5cbiAgICByZXMub25jZSgnZW5kJywgKCkgPT4ge1xuICAgICAgdGhpcy5lbWl0KCdlbmQnKTtcbiAgICB9KTtcbiAgfSk7XG4gIHJldHVybiBzdHJlYW07XG59O1xuXG4vKipcbiAqIEVuYWJsZSAvIGRpc2FibGUgYnVmZmVyaW5nLlxuICpcbiAqIEByZXR1cm4ge0Jvb2xlYW59IFt2YWxdXG4gKiBAcmV0dXJuIHtSZXF1ZXN0fSBmb3IgY2hhaW5pbmdcbiAqIEBhcGkgcHVibGljXG4gKi9cblxuUmVxdWVzdC5wcm90b3R5cGUuYnVmZmVyID0gZnVuY3Rpb24odmFsKSB7XG4gIHRoaXMuX2J1ZmZlciA9IHZhbCAhPT0gZmFsc2U7XG4gIHJldHVybiB0aGlzO1xufTtcblxuLyoqXG4gKiBSZWRpcmVjdCB0byBgdXJsXG4gKlxuICogQHBhcmFtIHtJbmNvbWluZ01lc3NhZ2V9IHJlc1xuICogQHJldHVybiB7UmVxdWVzdH0gZm9yIGNoYWluaW5nXG4gKiBAYXBpIHByaXZhdGVcbiAqL1xuXG5SZXF1ZXN0LnByb3RvdHlwZS5fcmVkaXJlY3QgPSBmdW5jdGlvbihyZXMpIHtcbiAgbGV0IHVybCA9IHJlcy5oZWFkZXJzLmxvY2F0aW9uO1xuICBpZiAoIXVybCkge1xuICAgIHJldHVybiB0aGlzLmNhbGxiYWNrKG5ldyBFcnJvcignTm8gbG9jYXRpb24gaGVhZGVyIGZvciByZWRpcmVjdCcpLCByZXMpO1xuICB9XG5cbiAgZGVidWcoJ3JlZGlyZWN0ICVzIC0+ICVzJywgdGhpcy51cmwsIHVybCk7XG5cbiAgLy8gbG9jYXRpb25cbiAgdXJsID0gcmVzb2x2ZSh0aGlzLnVybCwgdXJsKTtcblxuICAvLyBlbnN1cmUgdGhlIHJlc3BvbnNlIGlzIGJlaW5nIGNvbnN1bWVkXG4gIC8vIHRoaXMgaXMgcmVxdWlyZWQgZm9yIE5vZGUgdjAuMTArXG4gIHJlcy5yZXN1bWUoKTtcblxuICBsZXQgaGVhZGVycyA9IHRoaXMucmVxLmdldEhlYWRlcnMgPyB0aGlzLnJlcS5nZXRIZWFkZXJzKCkgOiB0aGlzLnJlcS5faGVhZGVycztcblxuICBjb25zdCBjaGFuZ2VzT3JpZ2luID0gcGFyc2UodXJsKS5ob3N0ICE9PSBwYXJzZSh0aGlzLnVybCkuaG9zdDtcblxuICAvLyBpbXBsZW1lbnRhdGlvbiBvZiAzMDIgZm9sbG93aW5nIGRlZmFjdG8gc3RhbmRhcmRcbiAgaWYgKHJlcy5zdGF0dXNDb2RlID09PSAzMDEgfHwgcmVzLnN0YXR1c0NvZGUgPT09IDMwMikge1xuICAgIC8vIHN0cmlwIENvbnRlbnQtKiByZWxhdGVkIGZpZWxkc1xuICAgIC8vIGluIGNhc2Ugb2YgUE9TVCBldGNcbiAgICBoZWFkZXJzID0gdXRpbHMuY2xlYW5IZWFkZXIoaGVhZGVycywgY2hhbmdlc09yaWdpbik7XG5cbiAgICAvLyBmb3JjZSBHRVRcbiAgICB0aGlzLm1ldGhvZCA9IHRoaXMubWV0aG9kID09PSAnSEVBRCcgPyAnSEVBRCcgOiAnR0VUJztcblxuICAgIC8vIGNsZWFyIGRhdGFcbiAgICB0aGlzLl9kYXRhID0gbnVsbDtcbiAgfVxuXG4gIC8vIDMwMyBpcyBhbHdheXMgR0VUXG4gIGlmIChyZXMuc3RhdHVzQ29kZSA9PT0gMzAzKSB7XG4gICAgLy8gc3RyaXAgQ29udGVudC0qIHJlbGF0ZWQgZmllbGRzXG4gICAgLy8gaW4gY2FzZSBvZiBQT1NUIGV0Y1xuICAgIGhlYWRlcnMgPSB1dGlscy5jbGVhbkhlYWRlcihoZWFkZXJzLCBjaGFuZ2VzT3JpZ2luKTtcblxuICAgIC8vIGZvcmNlIG1ldGhvZFxuICAgIHRoaXMubWV0aG9kID0gJ0dFVCc7XG5cbiAgICAvLyBjbGVhciBkYXRhXG4gICAgdGhpcy5fZGF0YSA9IG51bGw7XG4gIH1cblxuICAvLyAzMDcgcHJlc2VydmVzIG1ldGhvZFxuICAvLyAzMDggcHJlc2VydmVzIG1ldGhvZFxuICBkZWxldGUgaGVhZGVycy5ob3N0O1xuXG4gIGRlbGV0ZSB0aGlzLnJlcTtcbiAgZGVsZXRlIHRoaXMuX2Zvcm1EYXRhO1xuXG4gIC8vIHJlbW92ZSBhbGwgYWRkIGhlYWRlciBleGNlcHQgVXNlci1BZ2VudFxuICBfaW5pdEhlYWRlcnModGhpcyk7XG5cbiAgLy8gcmVkaXJlY3RcbiAgdGhpcy5fZW5kQ2FsbGVkID0gZmFsc2U7XG4gIHRoaXMudXJsID0gdXJsO1xuICB0aGlzLnFzID0ge307XG4gIHRoaXMuX3F1ZXJ5Lmxlbmd0aCA9IDA7XG4gIHRoaXMuc2V0KGhlYWRlcnMpO1xuICB0aGlzLmVtaXQoJ3JlZGlyZWN0JywgcmVzKTtcbiAgdGhpcy5fcmVkaXJlY3RMaXN0LnB1c2godGhpcy51cmwpO1xuICB0aGlzLmVuZCh0aGlzLl9jYWxsYmFjayk7XG4gIHJldHVybiB0aGlzO1xufTtcblxuLyoqXG4gKiBTZXQgQXV0aG9yaXphdGlvbiBmaWVsZCB2YWx1ZSB3aXRoIGB1c2VyYCBhbmQgYHBhc3NgLlxuICpcbiAqIEV4YW1wbGVzOlxuICpcbiAqICAgLmF1dGgoJ3RvYmknLCAnbGVhcm5ib29zdCcpXG4gKiAgIC5hdXRoKCd0b2JpOmxlYXJuYm9vc3QnKVxuICogICAuYXV0aCgndG9iaScpXG4gKiAgIC5hdXRoKGFjY2Vzc1Rva2VuLCB7IHR5cGU6ICdiZWFyZXInIH0pXG4gKlxuICogQHBhcmFtIHtTdHJpbmd9IHVzZXJcbiAqIEBwYXJhbSB7U3RyaW5nfSBbcGFzc11cbiAqIEBwYXJhbSB7T2JqZWN0fSBbb3B0aW9uc10gb3B0aW9ucyB3aXRoIGF1dGhvcml6YXRpb24gdHlwZSAnYmFzaWMnIG9yICdiZWFyZXInICgnYmFzaWMnIGlzIGRlZmF1bHQpXG4gKiBAcmV0dXJuIHtSZXF1ZXN0fSBmb3IgY2hhaW5pbmdcbiAqIEBhcGkgcHVibGljXG4gKi9cblxuUmVxdWVzdC5wcm90b3R5cGUuYXV0aCA9IGZ1bmN0aW9uKHVzZXIsIHBhc3MsIG9wdGlvbnMpIHtcbiAgaWYgKGFyZ3VtZW50cy5sZW5ndGggPT09IDEpIHBhc3MgPSAnJztcbiAgaWYgKHR5cGVvZiBwYXNzID09PSAnb2JqZWN0JyAmJiBwYXNzICE9PSBudWxsKSB7XG4gICAgLy8gcGFzcyBpcyBvcHRpb25hbCBhbmQgY2FuIGJlIHJlcGxhY2VkIHdpdGggb3B0aW9uc1xuICAgIG9wdGlvbnMgPSBwYXNzO1xuICAgIHBhc3MgPSAnJztcbiAgfVxuXG4gIGlmICghb3B0aW9ucykge1xuICAgIG9wdGlvbnMgPSB7IHR5cGU6ICdiYXNpYycgfTtcbiAgfVxuXG4gIGNvbnN0IGVuY29kZXIgPSBzdHJpbmcgPT4gQnVmZmVyLmZyb20oc3RyaW5nKS50b1N0cmluZygnYmFzZTY0Jyk7XG5cbiAgcmV0dXJuIHRoaXMuX2F1dGgodXNlciwgcGFzcywgb3B0aW9ucywgZW5jb2Rlcik7XG59O1xuXG4vKipcbiAqIFNldCB0aGUgY2VydGlmaWNhdGUgYXV0aG9yaXR5IG9wdGlvbiBmb3IgaHR0cHMgcmVxdWVzdC5cbiAqXG4gKiBAcGFyYW0ge0J1ZmZlciB8IEFycmF5fSBjZXJ0XG4gKiBAcmV0dXJuIHtSZXF1ZXN0fSBmb3IgY2hhaW5pbmdcbiAqIEBhcGkgcHVibGljXG4gKi9cblxuUmVxdWVzdC5wcm90b3R5cGUuY2EgPSBmdW5jdGlvbihjZXJ0KSB7XG4gIHRoaXMuX2NhID0gY2VydDtcbiAgcmV0dXJuIHRoaXM7XG59O1xuXG4vKipcbiAqIFNldCB0aGUgY2xpZW50IGNlcnRpZmljYXRlIGtleSBvcHRpb24gZm9yIGh0dHBzIHJlcXVlc3QuXG4gKlxuICogQHBhcmFtIHtCdWZmZXIgfCBTdHJpbmd9IGNlcnRcbiAqIEByZXR1cm4ge1JlcXVlc3R9IGZvciBjaGFpbmluZ1xuICogQGFwaSBwdWJsaWNcbiAqL1xuXG5SZXF1ZXN0LnByb3RvdHlwZS5rZXkgPSBmdW5jdGlvbihjZXJ0KSB7XG4gIHRoaXMuX2tleSA9IGNlcnQ7XG4gIHJldHVybiB0aGlzO1xufTtcblxuLyoqXG4gKiBTZXQgdGhlIGtleSwgY2VydGlmaWNhdGUsIGFuZCBDQSBjZXJ0cyBvZiB0aGUgY2xpZW50IGluIFBGWCBvciBQS0NTMTIgZm9ybWF0LlxuICpcbiAqIEBwYXJhbSB7QnVmZmVyIHwgU3RyaW5nfSBjZXJ0XG4gKiBAcmV0dXJuIHtSZXF1ZXN0fSBmb3IgY2hhaW5pbmdcbiAqIEBhcGkgcHVibGljXG4gKi9cblxuUmVxdWVzdC5wcm90b3R5cGUucGZ4ID0gZnVuY3Rpb24oY2VydCkge1xuICBpZiAodHlwZW9mIGNlcnQgPT09ICdvYmplY3QnICYmICFCdWZmZXIuaXNCdWZmZXIoY2VydCkpIHtcbiAgICB0aGlzLl9wZnggPSBjZXJ0LnBmeDtcbiAgICB0aGlzLl9wYXNzcGhyYXNlID0gY2VydC5wYXNzcGhyYXNlO1xuICB9IGVsc2Uge1xuICAgIHRoaXMuX3BmeCA9IGNlcnQ7XG4gIH1cblxuICByZXR1cm4gdGhpcztcbn07XG5cbi8qKlxuICogU2V0IHRoZSBjbGllbnQgY2VydGlmaWNhdGUgb3B0aW9uIGZvciBodHRwcyByZXF1ZXN0LlxuICpcbiAqIEBwYXJhbSB7QnVmZmVyIHwgU3RyaW5nfSBjZXJ0XG4gKiBAcmV0dXJuIHtSZXF1ZXN0fSBmb3IgY2hhaW5pbmdcbiAqIEBhcGkgcHVibGljXG4gKi9cblxuUmVxdWVzdC5wcm90b3R5cGUuY2VydCA9IGZ1bmN0aW9uKGNlcnQpIHtcbiAgdGhpcy5fY2VydCA9IGNlcnQ7XG4gIHJldHVybiB0aGlzO1xufTtcblxuLyoqXG4gKiBEbyBub3QgcmVqZWN0IGV4cGlyZWQgb3IgaW52YWxpZCBUTFMgY2VydHMuXG4gKiBzZXRzIGByZWplY3RVbmF1dGhvcml6ZWQ9dHJ1ZWAuIEJlIHdhcm5lZCB0aGF0IHRoaXMgYWxsb3dzIE1JVE0gYXR0YWNrcy5cbiAqXG4gKiBAcmV0dXJuIHtSZXF1ZXN0fSBmb3IgY2hhaW5pbmdcbiAqIEBhcGkgcHVibGljXG4gKi9cblxuUmVxdWVzdC5wcm90b3R5cGUuZGlzYWJsZVRMU0NlcnRzID0gZnVuY3Rpb24oKSB7XG4gIHRoaXMuX2Rpc2FibGVUTFNDZXJ0cyA9IHRydWU7XG4gIHJldHVybiB0aGlzO1xufTtcblxuLyoqXG4gKiBSZXR1cm4gYW4gaHR0cFtzXSByZXF1ZXN0LlxuICpcbiAqIEByZXR1cm4ge091dGdvaW5nTWVzc2FnZX1cbiAqIEBhcGkgcHJpdmF0ZVxuICovXG5cbi8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBjb21wbGV4aXR5XG5SZXF1ZXN0LnByb3RvdHlwZS5yZXF1ZXN0ID0gZnVuY3Rpb24oKSB7XG4gIGlmICh0aGlzLnJlcSkgcmV0dXJuIHRoaXMucmVxO1xuXG4gIGNvbnN0IG9wdGlvbnMgPSB7fTtcblxuICB0cnkge1xuICAgIGNvbnN0IHF1ZXJ5ID0gcXMuc3RyaW5naWZ5KHRoaXMucXMsIHtcbiAgICAgIGluZGljZXM6IGZhbHNlLFxuICAgICAgc3RyaWN0TnVsbEhhbmRsaW5nOiB0cnVlXG4gICAgfSk7XG4gICAgaWYgKHF1ZXJ5KSB7XG4gICAgICB0aGlzLnFzID0ge307XG4gICAgICB0aGlzLl9xdWVyeS5wdXNoKHF1ZXJ5KTtcbiAgICB9XG5cbiAgICB0aGlzLl9maW5hbGl6ZVF1ZXJ5U3RyaW5nKCk7XG4gIH0gY2F0Y2ggKGVycikge1xuICAgIHJldHVybiB0aGlzLmVtaXQoJ2Vycm9yJywgZXJyKTtcbiAgfVxuXG4gIGxldCB7IHVybCB9ID0gdGhpcztcbiAgY29uc3QgcmV0cmllcyA9IHRoaXMuX3JldHJpZXM7XG5cbiAgLy8gQ2FwdHVyZSBiYWNrdGlja3MgYXMtaXMgZnJvbSB0aGUgZmluYWwgcXVlcnkgc3RyaW5nIGJ1aWx0IGFib3ZlLlxuICAvLyBOb3RlOiB0aGlzJ2xsIG9ubHkgZmluZCBiYWNrdGlja3MgZW50ZXJlZCBpbiByZXEucXVlcnkoU3RyaW5nKVxuICAvLyBjYWxscywgYmVjYXVzZSBxcy5zdHJpbmdpZnkgdW5jb25kaXRpb25hbGx5IGVuY29kZXMgYmFja3RpY2tzLlxuICBsZXQgcXVlcnlTdHJpbmdCYWNrdGlja3M7XG4gIGlmICh1cmwuaW5jbHVkZXMoJ2AnKSkge1xuICAgIGNvbnN0IHF1ZXJ5U3RhcnRJbmRleCA9IHVybC5pbmRleE9mKCc/Jyk7XG5cbiAgICBpZiAocXVlcnlTdGFydEluZGV4ICE9PSAtMSkge1xuICAgICAgY29uc3QgcXVlcnlTdHJpbmcgPSB1cmwuc2xpY2UocXVlcnlTdGFydEluZGV4ICsgMSk7XG4gICAgICBxdWVyeVN0cmluZ0JhY2t0aWNrcyA9IHF1ZXJ5U3RyaW5nLm1hdGNoKC9gfCU2MC9nKTtcbiAgICB9XG4gIH1cblxuICAvLyBkZWZhdWx0IHRvIGh0dHA6Ly9cbiAgaWYgKHVybC5pbmRleE9mKCdodHRwJykgIT09IDApIHVybCA9IGBodHRwOi8vJHt1cmx9YDtcbiAgdXJsID0gcGFyc2UodXJsKTtcblxuICAvLyBTZWUgaHR0cHM6Ly9naXRodWIuY29tL3Zpc2lvbm1lZGlhL3N1cGVyYWdlbnQvaXNzdWVzLzEzNjdcbiAgaWYgKHF1ZXJ5U3RyaW5nQmFja3RpY2tzKSB7XG4gICAgbGV0IGkgPSAwO1xuICAgIHVybC5xdWVyeSA9IHVybC5xdWVyeS5yZXBsYWNlKC8lNjAvZywgKCkgPT4gcXVlcnlTdHJpbmdCYWNrdGlja3NbaSsrXSk7XG4gICAgdXJsLnNlYXJjaCA9IGA/JHt1cmwucXVlcnl9YDtcbiAgICB1cmwucGF0aCA9IHVybC5wYXRobmFtZSArIHVybC5zZWFyY2g7XG4gIH1cblxuICAvLyBzdXBwb3J0IHVuaXggc29ja2V0c1xuICBpZiAoL15odHRwcz9cXCt1bml4Oi8udGVzdCh1cmwucHJvdG9jb2wpID09PSB0cnVlKSB7XG4gICAgLy8gZ2V0IHRoZSBwcm90b2NvbFxuICAgIHVybC5wcm90b2NvbCA9IGAke3VybC5wcm90b2NvbC5zcGxpdCgnKycpWzBdfTpgO1xuXG4gICAgLy8gZ2V0IHRoZSBzb2NrZXQsIHBhdGhcbiAgICBjb25zdCB1bml4UGFydHMgPSB1cmwucGF0aC5tYXRjaCgvXihbXi9dKykoLispJC8pO1xuICAgIG9wdGlvbnMuc29ja2V0UGF0aCA9IHVuaXhQYXJ0c1sxXS5yZXBsYWNlKC8lMkYvZywgJy8nKTtcbiAgICB1cmwucGF0aCA9IHVuaXhQYXJ0c1syXTtcbiAgfVxuXG4gIC8vIE92ZXJyaWRlIElQIGFkZHJlc3Mgb2YgYSBob3N0bmFtZVxuICBpZiAodGhpcy5fY29ubmVjdE92ZXJyaWRlKSB7XG4gICAgY29uc3QgeyBob3N0bmFtZSB9ID0gdXJsO1xuICAgIGNvbnN0IG1hdGNoID1cbiAgICAgIGhvc3RuYW1lIGluIHRoaXMuX2Nvbm5lY3RPdmVycmlkZVxuICAgICAgICA/IHRoaXMuX2Nvbm5lY3RPdmVycmlkZVtob3N0bmFtZV1cbiAgICAgICAgOiB0aGlzLl9jb25uZWN0T3ZlcnJpZGVbJyonXTtcbiAgICBpZiAobWF0Y2gpIHtcbiAgICAgIC8vIGJhY2t1cCB0aGUgcmVhbCBob3N0XG4gICAgICBpZiAoIXRoaXMuX2hlYWRlci5ob3N0KSB7XG4gICAgICAgIHRoaXMuc2V0KCdob3N0JywgdXJsLmhvc3QpO1xuICAgICAgfVxuXG4gICAgICBsZXQgbmV3SG9zdDtcbiAgICAgIGxldCBuZXdQb3J0O1xuXG4gICAgICBpZiAodHlwZW9mIG1hdGNoID09PSAnb2JqZWN0Jykge1xuICAgICAgICBuZXdIb3N0ID0gbWF0Y2guaG9zdDtcbiAgICAgICAgbmV3UG9ydCA9IG1hdGNoLnBvcnQ7XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBuZXdIb3N0ID0gbWF0Y2g7XG4gICAgICAgIG5ld1BvcnQgPSB1cmwucG9ydDtcbiAgICAgIH1cblxuICAgICAgLy8gd3JhcCBbaXB2Nl1cbiAgICAgIHVybC5ob3N0ID0gLzovLnRlc3QobmV3SG9zdCkgPyBgWyR7bmV3SG9zdH1dYCA6IG5ld0hvc3Q7XG4gICAgICBpZiAobmV3UG9ydCkge1xuICAgICAgICB1cmwuaG9zdCArPSBgOiR7bmV3UG9ydH1gO1xuICAgICAgICB1cmwucG9ydCA9IG5ld1BvcnQ7XG4gICAgICB9XG5cbiAgICAgIHVybC5ob3N0bmFtZSA9IG5ld0hvc3Q7XG4gICAgfVxuICB9XG5cbiAgLy8gb3B0aW9uc1xuICBvcHRpb25zLm1ldGhvZCA9IHRoaXMubWV0aG9kO1xuICBvcHRpb25zLnBvcnQgPSB1cmwucG9ydDtcbiAgb3B0aW9ucy5wYXRoID0gdXJsLnBhdGg7XG4gIG9wdGlvbnMuaG9zdCA9IHVybC5ob3N0bmFtZTtcbiAgb3B0aW9ucy5jYSA9IHRoaXMuX2NhO1xuICBvcHRpb25zLmtleSA9IHRoaXMuX2tleTtcbiAgb3B0aW9ucy5wZnggPSB0aGlzLl9wZng7XG4gIG9wdGlvbnMuY2VydCA9IHRoaXMuX2NlcnQ7XG4gIG9wdGlvbnMucGFzc3BocmFzZSA9IHRoaXMuX3Bhc3NwaHJhc2U7XG4gIG9wdGlvbnMuYWdlbnQgPSB0aGlzLl9hZ2VudDtcbiAgb3B0aW9ucy5yZWplY3RVbmF1dGhvcml6ZWQgPVxuICAgIHR5cGVvZiB0aGlzLl9kaXNhYmxlVExTQ2VydHMgPT09ICdib29sZWFuJ1xuICAgICAgPyAhdGhpcy5fZGlzYWJsZVRMU0NlcnRzXG4gICAgICA6IHByb2Nlc3MuZW52Lk5PREVfVExTX1JFSkVDVF9VTkFVVEhPUklaRUQgIT09ICcwJztcblxuICAvLyBBbGxvd3MgcmVxdWVzdC5nZXQoJ2h0dHBzOi8vMS4yLjMuNC8nKS5zZXQoJ0hvc3QnLCAnZXhhbXBsZS5jb20nKVxuICBpZiAodGhpcy5faGVhZGVyLmhvc3QpIHtcbiAgICBvcHRpb25zLnNlcnZlcm5hbWUgPSB0aGlzLl9oZWFkZXIuaG9zdC5yZXBsYWNlKC86XFxkKyQvLCAnJyk7XG4gIH1cblxuICBpZiAoXG4gICAgdGhpcy5fdHJ1c3RMb2NhbGhvc3QgJiZcbiAgICAvXig/OmxvY2FsaG9zdHwxMjdcXC4wXFwuMFxcLlxcZCt8KDAqOikrOjAqMSkkLy50ZXN0KHVybC5ob3N0bmFtZSlcbiAgKSB7XG4gICAgb3B0aW9ucy5yZWplY3RVbmF1dGhvcml6ZWQgPSBmYWxzZTtcbiAgfVxuXG4gIC8vIGluaXRpYXRlIHJlcXVlc3RcbiAgY29uc3QgbW9kID0gdGhpcy5fZW5hYmxlSHR0cDJcbiAgICA/IGV4cG9ydHMucHJvdG9jb2xzWydodHRwMjonXS5zZXRQcm90b2NvbCh1cmwucHJvdG9jb2wpXG4gICAgOiBleHBvcnRzLnByb3RvY29sc1t1cmwucHJvdG9jb2xdO1xuXG4gIC8vIHJlcXVlc3RcbiAgdGhpcy5yZXEgPSBtb2QucmVxdWVzdChvcHRpb25zKTtcbiAgY29uc3QgeyByZXEgfSA9IHRoaXM7XG5cbiAgLy8gc2V0IHRjcCBubyBkZWxheVxuICByZXEuc2V0Tm9EZWxheSh0cnVlKTtcblxuICBpZiAob3B0aW9ucy5tZXRob2QgIT09ICdIRUFEJykge1xuICAgIHJlcS5zZXRIZWFkZXIoJ0FjY2VwdC1FbmNvZGluZycsICdnemlwLCBkZWZsYXRlJyk7XG4gIH1cblxuICB0aGlzLnByb3RvY29sID0gdXJsLnByb3RvY29sO1xuICB0aGlzLmhvc3QgPSB1cmwuaG9zdDtcblxuICAvLyBleHBvc2UgZXZlbnRzXG4gIHJlcS5vbmNlKCdkcmFpbicsICgpID0+IHtcbiAgICB0aGlzLmVtaXQoJ2RyYWluJyk7XG4gIH0pO1xuXG4gIHJlcS5vbignZXJyb3InLCBlcnIgPT4ge1xuICAgIC8vIGZsYWcgYWJvcnRpb24gaGVyZSBmb3Igb3V0IHRpbWVvdXRzXG4gICAgLy8gYmVjYXVzZSBub2RlIHdpbGwgZW1pdCBhIGZhdXgtZXJyb3IgXCJzb2NrZXQgaGFuZyB1cFwiXG4gICAgLy8gd2hlbiByZXF1ZXN0IGlzIGFib3J0ZWQgYmVmb3JlIGEgY29ubmVjdGlvbiBpcyBtYWRlXG4gICAgaWYgKHRoaXMuX2Fib3J0ZWQpIHJldHVybjtcbiAgICAvLyBpZiBub3QgdGhlIHNhbWUsIHdlIGFyZSBpbiB0aGUgKipvbGQqKiAoY2FuY2VsbGVkKSByZXF1ZXN0LFxuICAgIC8vIHNvIG5lZWQgdG8gY29udGludWUgKHNhbWUgYXMgZm9yIGFib3ZlKVxuICAgIGlmICh0aGlzLl9yZXRyaWVzICE9PSByZXRyaWVzKSByZXR1cm47XG4gICAgLy8gaWYgd2UndmUgcmVjZWl2ZWQgYSByZXNwb25zZSB0aGVuIHdlIGRvbid0IHdhbnQgdG8gbGV0XG4gICAgLy8gYW4gZXJyb3IgaW4gdGhlIHJlcXVlc3QgYmxvdyB1cCB0aGUgcmVzcG9uc2VcbiAgICBpZiAodGhpcy5yZXNwb25zZSkgcmV0dXJuO1xuICAgIHRoaXMuY2FsbGJhY2soZXJyKTtcbiAgfSk7XG5cbiAgLy8gYXV0aFxuICBpZiAodXJsLmF1dGgpIHtcbiAgICBjb25zdCBhdXRoID0gdXJsLmF1dGguc3BsaXQoJzonKTtcbiAgICB0aGlzLmF1dGgoYXV0aFswXSwgYXV0aFsxXSk7XG4gIH1cblxuICBpZiAodGhpcy51c2VybmFtZSAmJiB0aGlzLnBhc3N3b3JkKSB7XG4gICAgdGhpcy5hdXRoKHRoaXMudXNlcm5hbWUsIHRoaXMucGFzc3dvcmQpO1xuICB9XG5cbiAgZm9yIChjb25zdCBrZXkgaW4gdGhpcy5oZWFkZXIpIHtcbiAgICBpZiAoT2JqZWN0LnByb3RvdHlwZS5oYXNPd25Qcm9wZXJ0eS5jYWxsKHRoaXMuaGVhZGVyLCBrZXkpKVxuICAgICAgcmVxLnNldEhlYWRlcihrZXksIHRoaXMuaGVhZGVyW2tleV0pO1xuICB9XG5cbiAgLy8gYWRkIGNvb2tpZXNcbiAgaWYgKHRoaXMuY29va2llcykge1xuICAgIGlmIChPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwodGhpcy5faGVhZGVyLCAnY29va2llJykpIHtcbiAgICAgIC8vIG1lcmdlXG4gICAgICBjb25zdCB0bXBKYXIgPSBuZXcgQ29va2llSmFyLkNvb2tpZUphcigpO1xuICAgICAgdG1wSmFyLnNldENvb2tpZXModGhpcy5faGVhZGVyLmNvb2tpZS5zcGxpdCgnOycpKTtcbiAgICAgIHRtcEphci5zZXRDb29raWVzKHRoaXMuY29va2llcy5zcGxpdCgnOycpKTtcbiAgICAgIHJlcS5zZXRIZWFkZXIoXG4gICAgICAgICdDb29raWUnLFxuICAgICAgICB0bXBKYXIuZ2V0Q29va2llcyhDb29raWVKYXIuQ29va2llQWNjZXNzSW5mby5BbGwpLnRvVmFsdWVTdHJpbmcoKVxuICAgICAgKTtcbiAgICB9IGVsc2Uge1xuICAgICAgcmVxLnNldEhlYWRlcignQ29va2llJywgdGhpcy5jb29raWVzKTtcbiAgICB9XG4gIH1cblxuICByZXR1cm4gcmVxO1xufTtcblxuLyoqXG4gKiBJbnZva2UgdGhlIGNhbGxiYWNrIHdpdGggYGVycmAgYW5kIGByZXNgXG4gKiBhbmQgaGFuZGxlIGFyaXR5IGNoZWNrLlxuICpcbiAqIEBwYXJhbSB7RXJyb3J9IGVyclxuICogQHBhcmFtIHtSZXNwb25zZX0gcmVzXG4gKiBAYXBpIHByaXZhdGVcbiAqL1xuXG5SZXF1ZXN0LnByb3RvdHlwZS5jYWxsYmFjayA9IGZ1bmN0aW9uKGVyciwgcmVzKSB7XG4gIGlmICh0aGlzLl9zaG91bGRSZXRyeShlcnIsIHJlcykpIHtcbiAgICByZXR1cm4gdGhpcy5fcmV0cnkoKTtcbiAgfVxuXG4gIC8vIEF2b2lkIHRoZSBlcnJvciB3aGljaCBpcyBlbWl0dGVkIGZyb20gJ3NvY2tldCBoYW5nIHVwJyB0byBjYXVzZSB0aGUgZm4gdW5kZWZpbmVkIGVycm9yIG9uIEpTIHJ1bnRpbWUuXG4gIGNvbnN0IGZuID0gdGhpcy5fY2FsbGJhY2sgfHwgbm9vcDtcbiAgdGhpcy5jbGVhclRpbWVvdXQoKTtcbiAgaWYgKHRoaXMuY2FsbGVkKSByZXR1cm4gY29uc29sZS53YXJuKCdzdXBlcmFnZW50OiBkb3VibGUgY2FsbGJhY2sgYnVnJyk7XG4gIHRoaXMuY2FsbGVkID0gdHJ1ZTtcblxuICBpZiAoIWVycikge1xuICAgIHRyeSB7XG4gICAgICBpZiAoIXRoaXMuX2lzUmVzcG9uc2VPSyhyZXMpKSB7XG4gICAgICAgIGxldCBtc2cgPSAnVW5zdWNjZXNzZnVsIEhUVFAgcmVzcG9uc2UnO1xuICAgICAgICBpZiAocmVzKSB7XG4gICAgICAgICAgbXNnID0gaHR0cC5TVEFUVVNfQ09ERVNbcmVzLnN0YXR1c10gfHwgbXNnO1xuICAgICAgICB9XG5cbiAgICAgICAgZXJyID0gbmV3IEVycm9yKG1zZyk7XG4gICAgICAgIGVyci5zdGF0dXMgPSByZXMgPyByZXMuc3RhdHVzIDogdW5kZWZpbmVkO1xuICAgICAgfVxuICAgIH0gY2F0Y2ggKGVycl8pIHtcbiAgICAgIGVyciA9IGVycl87XG4gICAgfVxuICB9XG5cbiAgLy8gSXQncyBpbXBvcnRhbnQgdGhhdCB0aGUgY2FsbGJhY2sgaXMgY2FsbGVkIG91dHNpZGUgdHJ5L2NhdGNoXG4gIC8vIHRvIGF2b2lkIGRvdWJsZSBjYWxsYmFja1xuICBpZiAoIWVycikge1xuICAgIHJldHVybiBmbihudWxsLCByZXMpO1xuICB9XG5cbiAgZXJyLnJlc3BvbnNlID0gcmVzO1xuICBpZiAodGhpcy5fbWF4UmV0cmllcykgZXJyLnJldHJpZXMgPSB0aGlzLl9yZXRyaWVzIC0gMTtcblxuICAvLyBvbmx5IGVtaXQgZXJyb3IgZXZlbnQgaWYgdGhlcmUgaXMgYSBsaXN0ZW5lclxuICAvLyBvdGhlcndpc2Ugd2UgYXNzdW1lIHRoZSBjYWxsYmFjayB0byBgLmVuZCgpYCB3aWxsIGdldCB0aGUgZXJyb3JcbiAgaWYgKGVyciAmJiB0aGlzLmxpc3RlbmVycygnZXJyb3InKS5sZW5ndGggPiAwKSB7XG4gICAgdGhpcy5lbWl0KCdlcnJvcicsIGVycik7XG4gIH1cblxuICBmbihlcnIsIHJlcyk7XG59O1xuXG4vKipcbiAqIENoZWNrIGlmIGBvYmpgIGlzIGEgaG9zdCBvYmplY3QsXG4gKlxuICogQHBhcmFtIHtPYmplY3R9IG9iaiBob3N0IG9iamVjdFxuICogQHJldHVybiB7Qm9vbGVhbn0gaXMgYSBob3N0IG9iamVjdFxuICogQGFwaSBwcml2YXRlXG4gKi9cblJlcXVlc3QucHJvdG90eXBlLl9pc0hvc3QgPSBmdW5jdGlvbihvYmopIHtcbiAgcmV0dXJuIChcbiAgICBCdWZmZXIuaXNCdWZmZXIob2JqKSB8fCBvYmogaW5zdGFuY2VvZiBTdHJlYW0gfHwgb2JqIGluc3RhbmNlb2YgRm9ybURhdGFcbiAgKTtcbn07XG5cbi8qKlxuICogSW5pdGlhdGUgcmVxdWVzdCwgaW52b2tpbmcgY2FsbGJhY2sgYGZuKGVyciwgcmVzKWBcbiAqIHdpdGggYW4gaW5zdGFuY2VvZiBgUmVzcG9uc2VgLlxuICpcbiAqIEBwYXJhbSB7RnVuY3Rpb259IGZuXG4gKiBAcmV0dXJuIHtSZXF1ZXN0fSBmb3IgY2hhaW5pbmdcbiAqIEBhcGkgcHVibGljXG4gKi9cblxuUmVxdWVzdC5wcm90b3R5cGUuX2VtaXRSZXNwb25zZSA9IGZ1bmN0aW9uKGJvZHksIGZpbGVzKSB7XG4gIGNvbnN0IHJlc3BvbnNlID0gbmV3IFJlc3BvbnNlKHRoaXMpO1xuICB0aGlzLnJlc3BvbnNlID0gcmVzcG9uc2U7XG4gIHJlc3BvbnNlLnJlZGlyZWN0cyA9IHRoaXMuX3JlZGlyZWN0TGlzdDtcbiAgaWYgKHVuZGVmaW5lZCAhPT0gYm9keSkge1xuICAgIHJlc3BvbnNlLmJvZHkgPSBib2R5O1xuICB9XG5cbiAgcmVzcG9uc2UuZmlsZXMgPSBmaWxlcztcbiAgaWYgKHRoaXMuX2VuZENhbGxlZCkge1xuICAgIHJlc3BvbnNlLnBpcGUgPSBmdW5jdGlvbigpIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcihcbiAgICAgICAgXCJlbmQoKSBoYXMgYWxyZWFkeSBiZWVuIGNhbGxlZCwgc28gaXQncyB0b28gbGF0ZSB0byBzdGFydCBwaXBpbmdcIlxuICAgICAgKTtcbiAgICB9O1xuICB9XG5cbiAgdGhpcy5lbWl0KCdyZXNwb25zZScsIHJlc3BvbnNlKTtcbiAgcmV0dXJuIHJlc3BvbnNlO1xufTtcblxuUmVxdWVzdC5wcm90b3R5cGUuZW5kID0gZnVuY3Rpb24oZm4pIHtcbiAgdGhpcy5yZXF1ZXN0KCk7XG4gIGRlYnVnKCclcyAlcycsIHRoaXMubWV0aG9kLCB0aGlzLnVybCk7XG5cbiAgaWYgKHRoaXMuX2VuZENhbGxlZCkge1xuICAgIHRocm93IG5ldyBFcnJvcihcbiAgICAgICcuZW5kKCkgd2FzIGNhbGxlZCB0d2ljZS4gVGhpcyBpcyBub3Qgc3VwcG9ydGVkIGluIHN1cGVyYWdlbnQnXG4gICAgKTtcbiAgfVxuXG4gIHRoaXMuX2VuZENhbGxlZCA9IHRydWU7XG5cbiAgLy8gc3RvcmUgY2FsbGJhY2tcbiAgdGhpcy5fY2FsbGJhY2sgPSBmbiB8fCBub29wO1xuXG4gIHRoaXMuX2VuZCgpO1xufTtcblxuUmVxdWVzdC5wcm90b3R5cGUuX2VuZCA9IGZ1bmN0aW9uKCkge1xuICBpZiAodGhpcy5fYWJvcnRlZClcbiAgICByZXR1cm4gdGhpcy5jYWxsYmFjayhcbiAgICAgIG5ldyBFcnJvcignVGhlIHJlcXVlc3QgaGFzIGJlZW4gYWJvcnRlZCBldmVuIGJlZm9yZSAuZW5kKCkgd2FzIGNhbGxlZCcpXG4gICAgKTtcblxuICBsZXQgZGF0YSA9IHRoaXMuX2RhdGE7XG4gIGNvbnN0IHsgcmVxIH0gPSB0aGlzO1xuICBjb25zdCB7IG1ldGhvZCB9ID0gdGhpcztcblxuICB0aGlzLl9zZXRUaW1lb3V0cygpO1xuXG4gIC8vIGJvZHlcbiAgaWYgKG1ldGhvZCAhPT0gJ0hFQUQnICYmICFyZXEuX2hlYWRlclNlbnQpIHtcbiAgICAvLyBzZXJpYWxpemUgc3R1ZmZcbiAgICBpZiAodHlwZW9mIGRhdGEgIT09ICdzdHJpbmcnKSB7XG4gICAgICBsZXQgY29udGVudFR5cGUgPSByZXEuZ2V0SGVhZGVyKCdDb250ZW50LVR5cGUnKTtcbiAgICAgIC8vIFBhcnNlIG91dCBqdXN0IHRoZSBjb250ZW50IHR5cGUgZnJvbSB0aGUgaGVhZGVyIChpZ25vcmUgdGhlIGNoYXJzZXQpXG4gICAgICBpZiAoY29udGVudFR5cGUpIGNvbnRlbnRUeXBlID0gY29udGVudFR5cGUuc3BsaXQoJzsnKVswXTtcbiAgICAgIGxldCBzZXJpYWxpemUgPSB0aGlzLl9zZXJpYWxpemVyIHx8IGV4cG9ydHMuc2VyaWFsaXplW2NvbnRlbnRUeXBlXTtcbiAgICAgIGlmICghc2VyaWFsaXplICYmIGlzSlNPTihjb250ZW50VHlwZSkpIHtcbiAgICAgICAgc2VyaWFsaXplID0gZXhwb3J0cy5zZXJpYWxpemVbJ2FwcGxpY2F0aW9uL2pzb24nXTtcbiAgICAgIH1cblxuICAgICAgaWYgKHNlcmlhbGl6ZSkgZGF0YSA9IHNlcmlhbGl6ZShkYXRhKTtcbiAgICB9XG5cbiAgICAvLyBjb250ZW50LWxlbmd0aFxuICAgIGlmIChkYXRhICYmICFyZXEuZ2V0SGVhZGVyKCdDb250ZW50LUxlbmd0aCcpKSB7XG4gICAgICByZXEuc2V0SGVhZGVyKFxuICAgICAgICAnQ29udGVudC1MZW5ndGgnLFxuICAgICAgICBCdWZmZXIuaXNCdWZmZXIoZGF0YSkgPyBkYXRhLmxlbmd0aCA6IEJ1ZmZlci5ieXRlTGVuZ3RoKGRhdGEpXG4gICAgICApO1xuICAgIH1cbiAgfVxuXG4gIC8vIHJlc3BvbnNlXG4gIC8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBjb21wbGV4aXR5XG4gIHJlcS5vbmNlKCdyZXNwb25zZScsIHJlcyA9PiB7XG4gICAgZGVidWcoJyVzICVzIC0+ICVzJywgdGhpcy5tZXRob2QsIHRoaXMudXJsLCByZXMuc3RhdHVzQ29kZSk7XG5cbiAgICBpZiAodGhpcy5fcmVzcG9uc2VUaW1lb3V0VGltZXIpIHtcbiAgICAgIGNsZWFyVGltZW91dCh0aGlzLl9yZXNwb25zZVRpbWVvdXRUaW1lcik7XG4gICAgfVxuXG4gICAgaWYgKHRoaXMucGlwZWQpIHtcbiAgICAgIHJldHVybjtcbiAgICB9XG5cbiAgICBjb25zdCBtYXggPSB0aGlzLl9tYXhSZWRpcmVjdHM7XG4gICAgY29uc3QgbWltZSA9IHV0aWxzLnR5cGUocmVzLmhlYWRlcnNbJ2NvbnRlbnQtdHlwZSddIHx8ICcnKSB8fCAndGV4dC9wbGFpbic7XG4gICAgY29uc3QgdHlwZSA9IG1pbWUuc3BsaXQoJy8nKVswXTtcbiAgICBjb25zdCBtdWx0aXBhcnQgPSB0eXBlID09PSAnbXVsdGlwYXJ0JztcbiAgICBjb25zdCByZWRpcmVjdCA9IGlzUmVkaXJlY3QocmVzLnN0YXR1c0NvZGUpO1xuICAgIGNvbnN0IHJlc3BvbnNlVHlwZSA9IHRoaXMuX3Jlc3BvbnNlVHlwZTtcblxuICAgIHRoaXMucmVzID0gcmVzO1xuXG4gICAgLy8gcmVkaXJlY3RcbiAgICBpZiAocmVkaXJlY3QgJiYgdGhpcy5fcmVkaXJlY3RzKysgIT09IG1heCkge1xuICAgICAgcmV0dXJuIHRoaXMuX3JlZGlyZWN0KHJlcyk7XG4gICAgfVxuXG4gICAgaWYgKHRoaXMubWV0aG9kID09PSAnSEVBRCcpIHtcbiAgICAgIHRoaXMuZW1pdCgnZW5kJyk7XG4gICAgICB0aGlzLmNhbGxiYWNrKG51bGwsIHRoaXMuX2VtaXRSZXNwb25zZSgpKTtcbiAgICAgIHJldHVybjtcbiAgICB9XG5cbiAgICAvLyB6bGliIHN1cHBvcnRcbiAgICBpZiAodGhpcy5fc2hvdWxkVW56aXAocmVzKSkge1xuICAgICAgdW56aXAocmVxLCByZXMpO1xuICAgIH1cblxuICAgIGxldCBidWZmZXIgPSB0aGlzLl9idWZmZXI7XG4gICAgaWYgKGJ1ZmZlciA9PT0gdW5kZWZpbmVkICYmIG1pbWUgaW4gZXhwb3J0cy5idWZmZXIpIHtcbiAgICAgIGJ1ZmZlciA9IEJvb2xlYW4oZXhwb3J0cy5idWZmZXJbbWltZV0pO1xuICAgIH1cblxuICAgIGxldCBwYXJzZXIgPSB0aGlzLl9wYXJzZXI7XG4gICAgaWYgKHVuZGVmaW5lZCA9PT0gYnVmZmVyKSB7XG4gICAgICBpZiAocGFyc2VyKSB7XG4gICAgICAgIGNvbnNvbGUud2FybihcbiAgICAgICAgICBcIkEgY3VzdG9tIHN1cGVyYWdlbnQgcGFyc2VyIGhhcyBiZWVuIHNldCwgYnV0IGJ1ZmZlcmluZyBzdHJhdGVneSBmb3IgdGhlIHBhcnNlciBoYXNuJ3QgYmVlbiBjb25maWd1cmVkLiBDYWxsIGByZXEuYnVmZmVyKHRydWUgb3IgZmFsc2UpYCBvciBzZXQgYHN1cGVyYWdlbnQuYnVmZmVyW21pbWVdID0gdHJ1ZSBvciBmYWxzZWBcIlxuICAgICAgICApO1xuICAgICAgICBidWZmZXIgPSB0cnVlO1xuICAgICAgfVxuICAgIH1cblxuICAgIGlmICghcGFyc2VyKSB7XG4gICAgICBpZiAocmVzcG9uc2VUeXBlKSB7XG4gICAgICAgIHBhcnNlciA9IGV4cG9ydHMucGFyc2UuaW1hZ2U7IC8vIEl0J3MgYWN0dWFsbHkgYSBnZW5lcmljIEJ1ZmZlclxuICAgICAgICBidWZmZXIgPSB0cnVlO1xuICAgICAgfSBlbHNlIGlmIChtdWx0aXBhcnQpIHtcbiAgICAgICAgY29uc3QgZm9ybSA9IG5ldyBmb3JtaWRhYmxlLkluY29taW5nRm9ybSgpO1xuICAgICAgICBwYXJzZXIgPSBmb3JtLnBhcnNlLmJpbmQoZm9ybSk7XG4gICAgICAgIGJ1ZmZlciA9IHRydWU7XG4gICAgICB9IGVsc2UgaWYgKGlzSW1hZ2VPclZpZGVvKG1pbWUpKSB7XG4gICAgICAgIHBhcnNlciA9IGV4cG9ydHMucGFyc2UuaW1hZ2U7XG4gICAgICAgIGJ1ZmZlciA9IHRydWU7IC8vIEZvciBiYWNrd2FyZHMtY29tcGF0aWJpbGl0eSBidWZmZXJpbmcgZGVmYXVsdCBpcyBhZC1ob2MgTUlNRS1kZXBlbmRlbnRcbiAgICAgIH0gZWxzZSBpZiAoZXhwb3J0cy5wYXJzZVttaW1lXSkge1xuICAgICAgICBwYXJzZXIgPSBleHBvcnRzLnBhcnNlW21pbWVdO1xuICAgICAgfSBlbHNlIGlmICh0eXBlID09PSAndGV4dCcpIHtcbiAgICAgICAgcGFyc2VyID0gZXhwb3J0cy5wYXJzZS50ZXh0O1xuICAgICAgICBidWZmZXIgPSBidWZmZXIgIT09IGZhbHNlO1xuXG4gICAgICAgIC8vIGV2ZXJ5b25lIHdhbnRzIHRoZWlyIG93biB3aGl0ZS1sYWJlbGVkIGpzb25cbiAgICAgIH0gZWxzZSBpZiAoaXNKU09OKG1pbWUpKSB7XG4gICAgICAgIHBhcnNlciA9IGV4cG9ydHMucGFyc2VbJ2FwcGxpY2F0aW9uL2pzb24nXTtcbiAgICAgICAgYnVmZmVyID0gYnVmZmVyICE9PSBmYWxzZTtcbiAgICAgIH0gZWxzZSBpZiAoYnVmZmVyKSB7XG4gICAgICAgIHBhcnNlciA9IGV4cG9ydHMucGFyc2UudGV4dDtcbiAgICAgIH0gZWxzZSBpZiAodW5kZWZpbmVkID09PSBidWZmZXIpIHtcbiAgICAgICAgcGFyc2VyID0gZXhwb3J0cy5wYXJzZS5pbWFnZTsgLy8gSXQncyBhY3R1YWxseSBhIGdlbmVyaWMgQnVmZmVyXG4gICAgICAgIGJ1ZmZlciA9IHRydWU7XG4gICAgICB9XG4gICAgfVxuXG4gICAgLy8gYnkgZGVmYXVsdCBvbmx5IGJ1ZmZlciB0ZXh0LyosIGpzb24gYW5kIG1lc3NlZCB1cCB0aGluZyBmcm9tIGhlbGxcbiAgICBpZiAoKHVuZGVmaW5lZCA9PT0gYnVmZmVyICYmIGlzVGV4dChtaW1lKSkgfHwgaXNKU09OKG1pbWUpKSB7XG4gICAgICBidWZmZXIgPSB0cnVlO1xuICAgIH1cblxuICAgIHRoaXMuX3Jlc0J1ZmZlcmVkID0gYnVmZmVyO1xuICAgIGxldCBwYXJzZXJIYW5kbGVzRW5kID0gZmFsc2U7XG4gICAgaWYgKGJ1ZmZlcikge1xuICAgICAgLy8gUHJvdGVjdGlvbmEgYWdhaW5zdCB6aXAgYm9tYnMgYW5kIG90aGVyIG51aXNhbmNlXG4gICAgICBsZXQgcmVzcG9uc2VCeXRlc0xlZnQgPSB0aGlzLl9tYXhSZXNwb25zZVNpemUgfHwgMjAwMDAwMDAwO1xuICAgICAgcmVzLm9uKCdkYXRhJywgYnVmID0+IHtcbiAgICAgICAgcmVzcG9uc2VCeXRlc0xlZnQgLT0gYnVmLmJ5dGVMZW5ndGggfHwgYnVmLmxlbmd0aDtcbiAgICAgICAgaWYgKHJlc3BvbnNlQnl0ZXNMZWZ0IDwgMCkge1xuICAgICAgICAgIC8vIFRoaXMgd2lsbCBwcm9wYWdhdGUgdGhyb3VnaCBlcnJvciBldmVudFxuICAgICAgICAgIGNvbnN0IGVyciA9IG5ldyBFcnJvcignTWF4aW11bSByZXNwb25zZSBzaXplIHJlYWNoZWQnKTtcbiAgICAgICAgICBlcnIuY29kZSA9ICdFVE9PTEFSR0UnO1xuICAgICAgICAgIC8vIFBhcnNlcnMgYXJlbid0IHJlcXVpcmVkIHRvIG9ic2VydmUgZXJyb3IgZXZlbnQsXG4gICAgICAgICAgLy8gc28gd291bGQgaW5jb3JyZWN0bHkgcmVwb3J0IHN1Y2Nlc3NcbiAgICAgICAgICBwYXJzZXJIYW5kbGVzRW5kID0gZmFsc2U7XG4gICAgICAgICAgLy8gV2lsbCBlbWl0IGVycm9yIGV2ZW50XG4gICAgICAgICAgcmVzLmRlc3Ryb3koZXJyKTtcbiAgICAgICAgfVxuICAgICAgfSk7XG4gICAgfVxuXG4gICAgaWYgKHBhcnNlcikge1xuICAgICAgdHJ5IHtcbiAgICAgICAgLy8gVW5idWZmZXJlZCBwYXJzZXJzIGFyZSBzdXBwb3NlZCB0byBlbWl0IHJlc3BvbnNlIGVhcmx5LFxuICAgICAgICAvLyB3aGljaCBpcyB3ZWlyZCBCVFcsIGJlY2F1c2UgcmVzcG9uc2UuYm9keSB3b24ndCBiZSB0aGVyZS5cbiAgICAgICAgcGFyc2VySGFuZGxlc0VuZCA9IGJ1ZmZlcjtcblxuICAgICAgICBwYXJzZXIocmVzLCAoZXJyLCBvYmosIGZpbGVzKSA9PiB7XG4gICAgICAgICAgaWYgKHRoaXMudGltZWRvdXQpIHtcbiAgICAgICAgICAgIC8vIFRpbWVvdXQgaGFzIGFscmVhZHkgaGFuZGxlZCBhbGwgY2FsbGJhY2tzXG4gICAgICAgICAgICByZXR1cm47XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgLy8gSW50ZW50aW9uYWwgKG5vbi10aW1lb3V0KSBhYm9ydCBpcyBzdXBwb3NlZCB0byBwcmVzZXJ2ZSBwYXJ0aWFsIHJlc3BvbnNlLFxuICAgICAgICAgIC8vIGV2ZW4gaWYgaXQgZG9lc24ndCBwYXJzZS5cbiAgICAgICAgICBpZiAoZXJyICYmICF0aGlzLl9hYm9ydGVkKSB7XG4gICAgICAgICAgICByZXR1cm4gdGhpcy5jYWxsYmFjayhlcnIpO1xuICAgICAgICAgIH1cblxuICAgICAgICAgIGlmIChwYXJzZXJIYW5kbGVzRW5kKSB7XG4gICAgICAgICAgICB0aGlzLmVtaXQoJ2VuZCcpO1xuICAgICAgICAgICAgdGhpcy5jYWxsYmFjayhudWxsLCB0aGlzLl9lbWl0UmVzcG9uc2Uob2JqLCBmaWxlcykpO1xuICAgICAgICAgIH1cbiAgICAgICAgfSk7XG4gICAgICB9IGNhdGNoIChlcnIpIHtcbiAgICAgICAgdGhpcy5jYWxsYmFjayhlcnIpO1xuICAgICAgICByZXR1cm47XG4gICAgICB9XG4gICAgfVxuXG4gICAgdGhpcy5yZXMgPSByZXM7XG5cbiAgICAvLyB1bmJ1ZmZlcmVkXG4gICAgaWYgKCFidWZmZXIpIHtcbiAgICAgIGRlYnVnKCd1bmJ1ZmZlcmVkICVzICVzJywgdGhpcy5tZXRob2QsIHRoaXMudXJsKTtcbiAgICAgIHRoaXMuY2FsbGJhY2sobnVsbCwgdGhpcy5fZW1pdFJlc3BvbnNlKCkpO1xuICAgICAgaWYgKG11bHRpcGFydCkgcmV0dXJuOyAvLyBhbGxvdyBtdWx0aXBhcnQgdG8gaGFuZGxlIGVuZCBldmVudFxuICAgICAgcmVzLm9uY2UoJ2VuZCcsICgpID0+IHtcbiAgICAgICAgZGVidWcoJ2VuZCAlcyAlcycsIHRoaXMubWV0aG9kLCB0aGlzLnVybCk7XG4gICAgICAgIHRoaXMuZW1pdCgnZW5kJyk7XG4gICAgICB9KTtcbiAgICAgIHJldHVybjtcbiAgICB9XG5cbiAgICAvLyB0ZXJtaW5hdGluZyBldmVudHNcbiAgICByZXMub25jZSgnZXJyb3InLCBlcnIgPT4ge1xuICAgICAgcGFyc2VySGFuZGxlc0VuZCA9IGZhbHNlO1xuICAgICAgdGhpcy5jYWxsYmFjayhlcnIsIG51bGwpO1xuICAgIH0pO1xuICAgIGlmICghcGFyc2VySGFuZGxlc0VuZClcbiAgICAgIHJlcy5vbmNlKCdlbmQnLCAoKSA9PiB7XG4gICAgICAgIGRlYnVnKCdlbmQgJXMgJXMnLCB0aGlzLm1ldGhvZCwgdGhpcy51cmwpO1xuICAgICAgICAvLyBUT0RPOiB1bmxlc3MgYnVmZmVyaW5nIGVtaXQgZWFybGllciB0byBzdHJlYW1cbiAgICAgICAgdGhpcy5lbWl0KCdlbmQnKTtcbiAgICAgICAgdGhpcy5jYWxsYmFjayhudWxsLCB0aGlzLl9lbWl0UmVzcG9uc2UoKSk7XG4gICAgICB9KTtcbiAgfSk7XG5cbiAgdGhpcy5lbWl0KCdyZXF1ZXN0JywgdGhpcyk7XG5cbiAgY29uc3QgZ2V0UHJvZ3Jlc3NNb25pdG9yID0gKCkgPT4ge1xuICAgIGNvbnN0IGxlbmd0aENvbXB1dGFibGUgPSB0cnVlO1xuICAgIGNvbnN0IHRvdGFsID0gcmVxLmdldEhlYWRlcignQ29udGVudC1MZW5ndGgnKTtcbiAgICBsZXQgbG9hZGVkID0gMDtcblxuICAgIGNvbnN0IHByb2dyZXNzID0gbmV3IFN0cmVhbS5UcmFuc2Zvcm0oKTtcbiAgICBwcm9ncmVzcy5fdHJhbnNmb3JtID0gKGNodW5rLCBlbmNvZGluZywgY2IpID0+IHtcbiAgICAgIGxvYWRlZCArPSBjaHVuay5sZW5ndGg7XG4gICAgICB0aGlzLmVtaXQoJ3Byb2dyZXNzJywge1xuICAgICAgICBkaXJlY3Rpb246ICd1cGxvYWQnLFxuICAgICAgICBsZW5ndGhDb21wdXRhYmxlLFxuICAgICAgICBsb2FkZWQsXG4gICAgICAgIHRvdGFsXG4gICAgICB9KTtcbiAgICAgIGNiKG51bGwsIGNodW5rKTtcbiAgICB9O1xuXG4gICAgcmV0dXJuIHByb2dyZXNzO1xuICB9O1xuXG4gIGNvbnN0IGJ1ZmZlclRvQ2h1bmtzID0gYnVmZmVyID0+IHtcbiAgICBjb25zdCBjaHVua1NpemUgPSAxNiAqIDEwMjQ7IC8vIGRlZmF1bHQgaGlnaFdhdGVyTWFyayB2YWx1ZVxuICAgIGNvbnN0IGNodW5raW5nID0gbmV3IFN0cmVhbS5SZWFkYWJsZSgpO1xuICAgIGNvbnN0IHRvdGFsTGVuZ3RoID0gYnVmZmVyLmxlbmd0aDtcbiAgICBjb25zdCByZW1haW5kZXIgPSB0b3RhbExlbmd0aCAlIGNodW5rU2l6ZTtcbiAgICBjb25zdCBjdXRvZmYgPSB0b3RhbExlbmd0aCAtIHJlbWFpbmRlcjtcblxuICAgIGZvciAobGV0IGkgPSAwOyBpIDwgY3V0b2ZmOyBpICs9IGNodW5rU2l6ZSkge1xuICAgICAgY29uc3QgY2h1bmsgPSBidWZmZXIuc2xpY2UoaSwgaSArIGNodW5rU2l6ZSk7XG4gICAgICBjaHVua2luZy5wdXNoKGNodW5rKTtcbiAgICB9XG5cbiAgICBpZiAocmVtYWluZGVyID4gMCkge1xuICAgICAgY29uc3QgcmVtYWluZGVyQnVmZmVyID0gYnVmZmVyLnNsaWNlKC1yZW1haW5kZXIpO1xuICAgICAgY2h1bmtpbmcucHVzaChyZW1haW5kZXJCdWZmZXIpO1xuICAgIH1cblxuICAgIGNodW5raW5nLnB1c2gobnVsbCk7IC8vIG5vIG1vcmUgZGF0YVxuXG4gICAgcmV0dXJuIGNodW5raW5nO1xuICB9O1xuXG4gIC8vIGlmIGEgRm9ybURhdGEgaW5zdGFuY2UgZ290IGNyZWF0ZWQsIHRoZW4gd2Ugc2VuZCB0aGF0IGFzIHRoZSByZXF1ZXN0IGJvZHlcbiAgY29uc3QgZm9ybURhdGEgPSB0aGlzLl9mb3JtRGF0YTtcbiAgaWYgKGZvcm1EYXRhKSB7XG4gICAgLy8gc2V0IGhlYWRlcnNcbiAgICBjb25zdCBoZWFkZXJzID0gZm9ybURhdGEuZ2V0SGVhZGVycygpO1xuICAgIGZvciAoY29uc3QgaSBpbiBoZWFkZXJzKSB7XG4gICAgICBpZiAoT2JqZWN0LnByb3RvdHlwZS5oYXNPd25Qcm9wZXJ0eS5jYWxsKGhlYWRlcnMsIGkpKSB7XG4gICAgICAgIGRlYnVnKCdzZXR0aW5nIEZvcm1EYXRhIGhlYWRlcjogXCIlczogJXNcIicsIGksIGhlYWRlcnNbaV0pO1xuICAgICAgICByZXEuc2V0SGVhZGVyKGksIGhlYWRlcnNbaV0pO1xuICAgICAgfVxuICAgIH1cblxuICAgIC8vIGF0dGVtcHQgdG8gZ2V0IFwiQ29udGVudC1MZW5ndGhcIiBoZWFkZXJcbiAgICAvLyBlc2xpbnQtZGlzYWJsZS1uZXh0LWxpbmUgaGFuZGxlLWNhbGxiYWNrLWVyclxuICAgIGZvcm1EYXRhLmdldExlbmd0aCgoZXJyLCBsZW5ndGgpID0+IHtcbiAgICAgIC8vIFRPRE86IEFkZCBjaHVua2VkIGVuY29kaW5nIHdoZW4gbm8gbGVuZ3RoIChpZiBlcnIpXG5cbiAgICAgIGRlYnVnKCdnb3QgRm9ybURhdGEgQ29udGVudC1MZW5ndGg6ICVzJywgbGVuZ3RoKTtcbiAgICAgIGlmICh0eXBlb2YgbGVuZ3RoID09PSAnbnVtYmVyJykge1xuICAgICAgICByZXEuc2V0SGVhZGVyKCdDb250ZW50LUxlbmd0aCcsIGxlbmd0aCk7XG4gICAgICB9XG5cbiAgICAgIGZvcm1EYXRhLnBpcGUoZ2V0UHJvZ3Jlc3NNb25pdG9yKCkpLnBpcGUocmVxKTtcbiAgICB9KTtcbiAgfSBlbHNlIGlmIChCdWZmZXIuaXNCdWZmZXIoZGF0YSkpIHtcbiAgICBidWZmZXJUb0NodW5rcyhkYXRhKVxuICAgICAgLnBpcGUoZ2V0UHJvZ3Jlc3NNb25pdG9yKCkpXG4gICAgICAucGlwZShyZXEpO1xuICB9IGVsc2Uge1xuICAgIHJlcS5lbmQoZGF0YSk7XG4gIH1cbn07XG5cbi8vIENoZWNrIHdoZXRoZXIgcmVzcG9uc2UgaGFzIGEgbm9uLTAtc2l6ZWQgZ3ppcC1lbmNvZGVkIGJvZHlcblJlcXVlc3QucHJvdG90eXBlLl9zaG91bGRVbnppcCA9IHJlcyA9PiB7XG4gIGlmIChyZXMuc3RhdHVzQ29kZSA9PT0gMjA0IHx8IHJlcy5zdGF0dXNDb2RlID09PSAzMDQpIHtcbiAgICAvLyBUaGVzZSBhcmVuJ3Qgc3VwcG9zZWQgdG8gaGF2ZSBhbnkgYm9keVxuICAgIHJldHVybiBmYWxzZTtcbiAgfVxuXG4gIC8vIGhlYWRlciBjb250ZW50IGlzIGEgc3RyaW5nLCBhbmQgZGlzdGluY3Rpb24gYmV0d2VlbiAwIGFuZCBubyBpbmZvcm1hdGlvbiBpcyBjcnVjaWFsXG4gIGlmIChyZXMuaGVhZGVyc1snY29udGVudC1sZW5ndGgnXSA9PT0gJzAnKSB7XG4gICAgLy8gV2Uga25vdyB0aGF0IHRoZSBib2R5IGlzIGVtcHR5ICh1bmZvcnR1bmF0ZWx5LCB0aGlzIGNoZWNrIGRvZXMgbm90IGNvdmVyIGNodW5rZWQgZW5jb2RpbmcpXG4gICAgcmV0dXJuIGZhbHNlO1xuICB9XG5cbiAgLy8gY29uc29sZS5sb2cocmVzKTtcbiAgcmV0dXJuIC9eXFxzKig/OmRlZmxhdGV8Z3ppcClcXHMqJC8udGVzdChyZXMuaGVhZGVyc1snY29udGVudC1lbmNvZGluZyddKTtcbn07XG5cbi8qKlxuICogT3ZlcnJpZGVzIEROUyBmb3Igc2VsZWN0ZWQgaG9zdG5hbWVzLiBUYWtlcyBvYmplY3QgbWFwcGluZyBob3N0bmFtZXMgdG8gSVAgYWRkcmVzc2VzLlxuICpcbiAqIFdoZW4gbWFraW5nIGEgcmVxdWVzdCB0byBhIFVSTCB3aXRoIGEgaG9zdG5hbWUgZXhhY3RseSBtYXRjaGluZyBhIGtleSBpbiB0aGUgb2JqZWN0LFxuICogdXNlIHRoZSBnaXZlbiBJUCBhZGRyZXNzIHRvIGNvbm5lY3QsIGluc3RlYWQgb2YgdXNpbmcgRE5TIHRvIHJlc29sdmUgdGhlIGhvc3RuYW1lLlxuICpcbiAqIEEgc3BlY2lhbCBob3N0IGAqYCBtYXRjaGVzIGV2ZXJ5IGhvc3RuYW1lIChrZWVwIHJlZGlyZWN0cyBpbiBtaW5kISlcbiAqXG4gKiAgICAgIHJlcXVlc3QuY29ubmVjdCh7XG4gKiAgICAgICAgJ3Rlc3QuZXhhbXBsZS5jb20nOiAnMTI3LjAuMC4xJyxcbiAqICAgICAgICAnaXB2Ni5leGFtcGxlLmNvbSc6ICc6OjEnLFxuICogICAgICB9KVxuICovXG5SZXF1ZXN0LnByb3RvdHlwZS5jb25uZWN0ID0gZnVuY3Rpb24oY29ubmVjdE92ZXJyaWRlKSB7XG4gIGlmICh0eXBlb2YgY29ubmVjdE92ZXJyaWRlID09PSAnc3RyaW5nJykge1xuICAgIHRoaXMuX2Nvbm5lY3RPdmVycmlkZSA9IHsgJyonOiBjb25uZWN0T3ZlcnJpZGUgfTtcbiAgfSBlbHNlIGlmICh0eXBlb2YgY29ubmVjdE92ZXJyaWRlID09PSAnb2JqZWN0Jykge1xuICAgIHRoaXMuX2Nvbm5lY3RPdmVycmlkZSA9IGNvbm5lY3RPdmVycmlkZTtcbiAgfSBlbHNlIHtcbiAgICB0aGlzLl9jb25uZWN0T3ZlcnJpZGUgPSB1bmRlZmluZWQ7XG4gIH1cblxuICByZXR1cm4gdGhpcztcbn07XG5cblJlcXVlc3QucHJvdG90eXBlLnRydXN0TG9jYWxob3N0ID0gZnVuY3Rpb24odG9nZ2xlKSB7XG4gIHRoaXMuX3RydXN0TG9jYWxob3N0ID0gdG9nZ2xlID09PSB1bmRlZmluZWQgPyB0cnVlIDogdG9nZ2xlO1xuICByZXR1cm4gdGhpcztcbn07XG5cbi8vIGdlbmVyYXRlIEhUVFAgdmVyYiBtZXRob2RzXG5pZiAoIW1ldGhvZHMuaW5jbHVkZXMoJ2RlbCcpKSB7XG4gIC8vIGNyZWF0ZSBhIGNvcHkgc28gd2UgZG9uJ3QgY2F1c2UgY29uZmxpY3RzIHdpdGhcbiAgLy8gb3RoZXIgcGFja2FnZXMgdXNpbmcgdGhlIG1ldGhvZHMgcGFja2FnZSBhbmRcbiAgLy8gbnBtIDMueFxuICBtZXRob2RzID0gbWV0aG9kcy5zbGljZSgwKTtcbiAgbWV0aG9kcy5wdXNoKCdkZWwnKTtcbn1cblxubWV0aG9kcy5mb3JFYWNoKG1ldGhvZCA9PiB7XG4gIGNvbnN0IG5hbWUgPSBtZXRob2Q7XG4gIG1ldGhvZCA9IG1ldGhvZCA9PT0gJ2RlbCcgPyAnZGVsZXRlJyA6IG1ldGhvZDtcblxuICBtZXRob2QgPSBtZXRob2QudG9VcHBlckNhc2UoKTtcbiAgcmVxdWVzdFtuYW1lXSA9ICh1cmwsIGRhdGEsIGZuKSA9PiB7XG4gICAgY29uc3QgcmVxID0gcmVxdWVzdChtZXRob2QsIHVybCk7XG4gICAgaWYgKHR5cGVvZiBkYXRhID09PSAnZnVuY3Rpb24nKSB7XG4gICAgICBmbiA9IGRhdGE7XG4gICAgICBkYXRhID0gbnVsbDtcbiAgICB9XG5cbiAgICBpZiAoZGF0YSkge1xuICAgICAgaWYgKG1ldGhvZCA9PT0gJ0dFVCcgfHwgbWV0aG9kID09PSAnSEVBRCcpIHtcbiAgICAgICAgcmVxLnF1ZXJ5KGRhdGEpO1xuICAgICAgfSBlbHNlIHtcbiAgICAgICAgcmVxLnNlbmQoZGF0YSk7XG4gICAgICB9XG4gICAgfVxuXG4gICAgaWYgKGZuKSByZXEuZW5kKGZuKTtcbiAgICByZXR1cm4gcmVxO1xuICB9O1xufSk7XG5cbi8qKlxuICogQ2hlY2sgaWYgYG1pbWVgIGlzIHRleHQgYW5kIHNob3VsZCBiZSBidWZmZXJlZC5cbiAqXG4gKiBAcGFyYW0ge1N0cmluZ30gbWltZVxuICogQHJldHVybiB7Qm9vbGVhbn1cbiAqIEBhcGkgcHVibGljXG4gKi9cblxuZnVuY3Rpb24gaXNUZXh0KG1pbWUpIHtcbiAgY29uc3QgcGFydHMgPSBtaW1lLnNwbGl0KCcvJyk7XG4gIGNvbnN0IHR5cGUgPSBwYXJ0c1swXTtcbiAgY29uc3Qgc3VidHlwZSA9IHBhcnRzWzFdO1xuXG4gIHJldHVybiB0eXBlID09PSAndGV4dCcgfHwgc3VidHlwZSA9PT0gJ3gtd3d3LWZvcm0tdXJsZW5jb2RlZCc7XG59XG5cbmZ1bmN0aW9uIGlzSW1hZ2VPclZpZGVvKG1pbWUpIHtcbiAgY29uc3QgdHlwZSA9IG1pbWUuc3BsaXQoJy8nKVswXTtcblxuICByZXR1cm4gdHlwZSA9PT0gJ2ltYWdlJyB8fCB0eXBlID09PSAndmlkZW8nO1xufVxuXG4vKipcbiAqIENoZWNrIGlmIGBtaW1lYCBpcyBqc29uIG9yIGhhcyAranNvbiBzdHJ1Y3R1cmVkIHN5bnRheCBzdWZmaXguXG4gKlxuICogQHBhcmFtIHtTdHJpbmd9IG1pbWVcbiAqIEByZXR1cm4ge0Jvb2xlYW59XG4gKiBAYXBpIHByaXZhdGVcbiAqL1xuXG5mdW5jdGlvbiBpc0pTT04obWltZSkge1xuICAvLyBzaG91bGQgbWF0Y2ggL2pzb24gb3IgK2pzb25cbiAgLy8gYnV0IG5vdCAvanNvbi1zZXFcbiAgcmV0dXJuIC9bLytdanNvbigkfFteLVxcd10pLy50ZXN0KG1pbWUpO1xufVxuXG4vKipcbiAqIENoZWNrIGlmIHdlIHNob3VsZCBmb2xsb3cgdGhlIHJlZGlyZWN0IGBjb2RlYC5cbiAqXG4gKiBAcGFyYW0ge051bWJlcn0gY29kZVxuICogQHJldHVybiB7Qm9vbGVhbn1cbiAqIEBhcGkgcHJpdmF0ZVxuICovXG5cbmZ1bmN0aW9uIGlzUmVkaXJlY3QoY29kZSkge1xuICByZXR1cm4gWzMwMSwgMzAyLCAzMDMsIDMwNSwgMzA3LCAzMDhdLmluY2x1ZGVzKGNvZGUpO1xufVxuIl19 \ No newline at end of file diff --git a/node_modules/superagent/lib/node/parsers/image.js b/node_modules/superagent/lib/node/parsers/image.js new file mode 100644 index 000000000..1537c5e6b --- /dev/null +++ b/node_modules/superagent/lib/node/parsers/image.js @@ -0,0 +1,13 @@ +"use strict"; + +module.exports = function (res, fn) { + var data = []; // Binary data needs binary storage + + res.on('data', function (chunk) { + data.push(chunk); + }); + res.on('end', function () { + fn(null, Buffer.concat(data)); + }); +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9ub2RlL3BhcnNlcnMvaW1hZ2UuanMiXSwibmFtZXMiOlsibW9kdWxlIiwiZXhwb3J0cyIsInJlcyIsImZuIiwiZGF0YSIsIm9uIiwiY2h1bmsiLCJwdXNoIiwiQnVmZmVyIiwiY29uY2F0Il0sIm1hcHBpbmdzIjoiOztBQUFBQSxNQUFNLENBQUNDLE9BQVAsR0FBaUIsVUFBQ0MsR0FBRCxFQUFNQyxFQUFOLEVBQWE7QUFDNUIsTUFBTUMsSUFBSSxHQUFHLEVBQWIsQ0FENEIsQ0FDWDs7QUFFakJGLEVBQUFBLEdBQUcsQ0FBQ0csRUFBSixDQUFPLE1BQVAsRUFBZSxVQUFBQyxLQUFLLEVBQUk7QUFDdEJGLElBQUFBLElBQUksQ0FBQ0csSUFBTCxDQUFVRCxLQUFWO0FBQ0QsR0FGRDtBQUdBSixFQUFBQSxHQUFHLENBQUNHLEVBQUosQ0FBTyxLQUFQLEVBQWMsWUFBTTtBQUNsQkYsSUFBQUEsRUFBRSxDQUFDLElBQUQsRUFBT0ssTUFBTSxDQUFDQyxNQUFQLENBQWNMLElBQWQsQ0FBUCxDQUFGO0FBQ0QsR0FGRDtBQUdELENBVEQiLCJzb3VyY2VzQ29udGVudCI6WyJtb2R1bGUuZXhwb3J0cyA9IChyZXMsIGZuKSA9PiB7XG4gIGNvbnN0IGRhdGEgPSBbXTsgLy8gQmluYXJ5IGRhdGEgbmVlZHMgYmluYXJ5IHN0b3JhZ2VcblxuICByZXMub24oJ2RhdGEnLCBjaHVuayA9PiB7XG4gICAgZGF0YS5wdXNoKGNodW5rKTtcbiAgfSk7XG4gIHJlcy5vbignZW5kJywgKCkgPT4ge1xuICAgIGZuKG51bGwsIEJ1ZmZlci5jb25jYXQoZGF0YSkpO1xuICB9KTtcbn07XG4iXX0= \ No newline at end of file diff --git a/node_modules/superagent/lib/node/parsers/index.js b/node_modules/superagent/lib/node/parsers/index.js new file mode 100644 index 000000000..f08a9f44f --- /dev/null +++ b/node_modules/superagent/lib/node/parsers/index.js @@ -0,0 +1,12 @@ +"use strict"; + +exports['application/x-www-form-urlencoded'] = require('./urlencoded'); +exports['application/json'] = require('./json'); +exports.text = require('./text'); + +var binary = require('./image'); + +exports['application/octet-stream'] = binary; +exports['application/pdf'] = binary; +exports.image = binary; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9ub2RlL3BhcnNlcnMvaW5kZXguanMiXSwibmFtZXMiOlsiZXhwb3J0cyIsInJlcXVpcmUiLCJ0ZXh0IiwiYmluYXJ5IiwiaW1hZ2UiXSwibWFwcGluZ3MiOiI7O0FBQUFBLE9BQU8sQ0FBQyxtQ0FBRCxDQUFQLEdBQStDQyxPQUFPLENBQUMsY0FBRCxDQUF0RDtBQUNBRCxPQUFPLENBQUMsa0JBQUQsQ0FBUCxHQUE4QkMsT0FBTyxDQUFDLFFBQUQsQ0FBckM7QUFDQUQsT0FBTyxDQUFDRSxJQUFSLEdBQWVELE9BQU8sQ0FBQyxRQUFELENBQXRCOztBQUVBLElBQU1FLE1BQU0sR0FBR0YsT0FBTyxDQUFDLFNBQUQsQ0FBdEI7O0FBRUFELE9BQU8sQ0FBQywwQkFBRCxDQUFQLEdBQXNDRyxNQUF0QztBQUNBSCxPQUFPLENBQUMsaUJBQUQsQ0FBUCxHQUE2QkcsTUFBN0I7QUFDQUgsT0FBTyxDQUFDSSxLQUFSLEdBQWdCRCxNQUFoQiIsInNvdXJjZXNDb250ZW50IjpbImV4cG9ydHNbJ2FwcGxpY2F0aW9uL3gtd3d3LWZvcm0tdXJsZW5jb2RlZCddID0gcmVxdWlyZSgnLi91cmxlbmNvZGVkJyk7XG5leHBvcnRzWydhcHBsaWNhdGlvbi9qc29uJ10gPSByZXF1aXJlKCcuL2pzb24nKTtcbmV4cG9ydHMudGV4dCA9IHJlcXVpcmUoJy4vdGV4dCcpO1xuXG5jb25zdCBiaW5hcnkgPSByZXF1aXJlKCcuL2ltYWdlJyk7XG5cbmV4cG9ydHNbJ2FwcGxpY2F0aW9uL29jdGV0LXN0cmVhbSddID0gYmluYXJ5O1xuZXhwb3J0c1snYXBwbGljYXRpb24vcGRmJ10gPSBiaW5hcnk7XG5leHBvcnRzLmltYWdlID0gYmluYXJ5O1xuIl19 \ No newline at end of file diff --git a/node_modules/superagent/lib/node/parsers/json.js b/node_modules/superagent/lib/node/parsers/json.js new file mode 100644 index 000000000..7bb95f57c --- /dev/null +++ b/node_modules/superagent/lib/node/parsers/json.js @@ -0,0 +1,26 @@ +"use strict"; + +module.exports = function (res, fn) { + res.text = ''; + res.setEncoding('utf8'); + res.on('data', function (chunk) { + res.text += chunk; + }); + res.on('end', function () { + var body; + var err; + + try { + body = res.text && JSON.parse(res.text); + } catch (err_) { + err = err_; // issue #675: return the raw response if the response parsing fails + + err.rawResponse = res.text || null; // issue #876: return the http status code if the response parsing fails + + err.statusCode = res.statusCode; + } finally { + fn(err, body); + } + }); +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9ub2RlL3BhcnNlcnMvanNvbi5qcyJdLCJuYW1lcyI6WyJtb2R1bGUiLCJleHBvcnRzIiwicmVzIiwiZm4iLCJ0ZXh0Iiwic2V0RW5jb2RpbmciLCJvbiIsImNodW5rIiwiYm9keSIsImVyciIsIkpTT04iLCJwYXJzZSIsImVycl8iLCJyYXdSZXNwb25zZSIsInN0YXR1c0NvZGUiXSwibWFwcGluZ3MiOiI7O0FBQUFBLE1BQU0sQ0FBQ0MsT0FBUCxHQUFpQixVQUFTQyxHQUFULEVBQWNDLEVBQWQsRUFBa0I7QUFDakNELEVBQUFBLEdBQUcsQ0FBQ0UsSUFBSixHQUFXLEVBQVg7QUFDQUYsRUFBQUEsR0FBRyxDQUFDRyxXQUFKLENBQWdCLE1BQWhCO0FBQ0FILEVBQUFBLEdBQUcsQ0FBQ0ksRUFBSixDQUFPLE1BQVAsRUFBZSxVQUFBQyxLQUFLLEVBQUk7QUFDdEJMLElBQUFBLEdBQUcsQ0FBQ0UsSUFBSixJQUFZRyxLQUFaO0FBQ0QsR0FGRDtBQUdBTCxFQUFBQSxHQUFHLENBQUNJLEVBQUosQ0FBTyxLQUFQLEVBQWMsWUFBTTtBQUNsQixRQUFJRSxJQUFKO0FBQ0EsUUFBSUMsR0FBSjs7QUFDQSxRQUFJO0FBQ0ZELE1BQUFBLElBQUksR0FBR04sR0FBRyxDQUFDRSxJQUFKLElBQVlNLElBQUksQ0FBQ0MsS0FBTCxDQUFXVCxHQUFHLENBQUNFLElBQWYsQ0FBbkI7QUFDRCxLQUZELENBRUUsT0FBT1EsSUFBUCxFQUFhO0FBQ2JILE1BQUFBLEdBQUcsR0FBR0csSUFBTixDQURhLENBRWI7O0FBQ0FILE1BQUFBLEdBQUcsQ0FBQ0ksV0FBSixHQUFrQlgsR0FBRyxDQUFDRSxJQUFKLElBQVksSUFBOUIsQ0FIYSxDQUliOztBQUNBSyxNQUFBQSxHQUFHLENBQUNLLFVBQUosR0FBaUJaLEdBQUcsQ0FBQ1ksVUFBckI7QUFDRCxLQVJELFNBUVU7QUFDUlgsTUFBQUEsRUFBRSxDQUFDTSxHQUFELEVBQU1ELElBQU4sQ0FBRjtBQUNEO0FBQ0YsR0FkRDtBQWVELENBckJEIiwic291cmNlc0NvbnRlbnQiOlsibW9kdWxlLmV4cG9ydHMgPSBmdW5jdGlvbihyZXMsIGZuKSB7XG4gIHJlcy50ZXh0ID0gJyc7XG4gIHJlcy5zZXRFbmNvZGluZygndXRmOCcpO1xuICByZXMub24oJ2RhdGEnLCBjaHVuayA9PiB7XG4gICAgcmVzLnRleHQgKz0gY2h1bms7XG4gIH0pO1xuICByZXMub24oJ2VuZCcsICgpID0+IHtcbiAgICBsZXQgYm9keTtcbiAgICBsZXQgZXJyO1xuICAgIHRyeSB7XG4gICAgICBib2R5ID0gcmVzLnRleHQgJiYgSlNPTi5wYXJzZShyZXMudGV4dCk7XG4gICAgfSBjYXRjaCAoZXJyXykge1xuICAgICAgZXJyID0gZXJyXztcbiAgICAgIC8vIGlzc3VlICM2NzU6IHJldHVybiB0aGUgcmF3IHJlc3BvbnNlIGlmIHRoZSByZXNwb25zZSBwYXJzaW5nIGZhaWxzXG4gICAgICBlcnIucmF3UmVzcG9uc2UgPSByZXMudGV4dCB8fCBudWxsO1xuICAgICAgLy8gaXNzdWUgIzg3NjogcmV0dXJuIHRoZSBodHRwIHN0YXR1cyBjb2RlIGlmIHRoZSByZXNwb25zZSBwYXJzaW5nIGZhaWxzXG4gICAgICBlcnIuc3RhdHVzQ29kZSA9IHJlcy5zdGF0dXNDb2RlO1xuICAgIH0gZmluYWxseSB7XG4gICAgICBmbihlcnIsIGJvZHkpO1xuICAgIH1cbiAgfSk7XG59O1xuIl19 \ No newline at end of file diff --git a/node_modules/superagent/lib/node/parsers/text.js b/node_modules/superagent/lib/node/parsers/text.js new file mode 100644 index 000000000..b1bde9dec --- /dev/null +++ b/node_modules/superagent/lib/node/parsers/text.js @@ -0,0 +1,11 @@ +"use strict"; + +module.exports = function (res, fn) { + res.text = ''; + res.setEncoding('utf8'); + res.on('data', function (chunk) { + res.text += chunk; + }); + res.on('end', fn); +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9ub2RlL3BhcnNlcnMvdGV4dC5qcyJdLCJuYW1lcyI6WyJtb2R1bGUiLCJleHBvcnRzIiwicmVzIiwiZm4iLCJ0ZXh0Iiwic2V0RW5jb2RpbmciLCJvbiIsImNodW5rIl0sIm1hcHBpbmdzIjoiOztBQUFBQSxNQUFNLENBQUNDLE9BQVAsR0FBaUIsVUFBQ0MsR0FBRCxFQUFNQyxFQUFOLEVBQWE7QUFDNUJELEVBQUFBLEdBQUcsQ0FBQ0UsSUFBSixHQUFXLEVBQVg7QUFDQUYsRUFBQUEsR0FBRyxDQUFDRyxXQUFKLENBQWdCLE1BQWhCO0FBQ0FILEVBQUFBLEdBQUcsQ0FBQ0ksRUFBSixDQUFPLE1BQVAsRUFBZSxVQUFBQyxLQUFLLEVBQUk7QUFDdEJMLElBQUFBLEdBQUcsQ0FBQ0UsSUFBSixJQUFZRyxLQUFaO0FBQ0QsR0FGRDtBQUdBTCxFQUFBQSxHQUFHLENBQUNJLEVBQUosQ0FBTyxLQUFQLEVBQWNILEVBQWQ7QUFDRCxDQVBEIiwic291cmNlc0NvbnRlbnQiOlsibW9kdWxlLmV4cG9ydHMgPSAocmVzLCBmbikgPT4ge1xuICByZXMudGV4dCA9ICcnO1xuICByZXMuc2V0RW5jb2RpbmcoJ3V0ZjgnKTtcbiAgcmVzLm9uKCdkYXRhJywgY2h1bmsgPT4ge1xuICAgIHJlcy50ZXh0ICs9IGNodW5rO1xuICB9KTtcbiAgcmVzLm9uKCdlbmQnLCBmbik7XG59O1xuIl19 \ No newline at end of file diff --git a/node_modules/superagent/lib/node/parsers/urlencoded.js b/node_modules/superagent/lib/node/parsers/urlencoded.js new file mode 100644 index 000000000..4aac6eff5 --- /dev/null +++ b/node_modules/superagent/lib/node/parsers/urlencoded.js @@ -0,0 +1,22 @@ +"use strict"; + +/** + * Module dependencies. + */ +var qs = require('qs'); + +module.exports = function (res, fn) { + res.text = ''; + res.setEncoding('ascii'); + res.on('data', function (chunk) { + res.text += chunk; + }); + res.on('end', function () { + try { + fn(null, qs.parse(res.text)); + } catch (err) { + fn(err); + } + }); +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9ub2RlL3BhcnNlcnMvdXJsZW5jb2RlZC5qcyJdLCJuYW1lcyI6WyJxcyIsInJlcXVpcmUiLCJtb2R1bGUiLCJleHBvcnRzIiwicmVzIiwiZm4iLCJ0ZXh0Iiwic2V0RW5jb2RpbmciLCJvbiIsImNodW5rIiwicGFyc2UiLCJlcnIiXSwibWFwcGluZ3MiOiI7O0FBQUE7OztBQUlBLElBQU1BLEVBQUUsR0FBR0MsT0FBTyxDQUFDLElBQUQsQ0FBbEI7O0FBRUFDLE1BQU0sQ0FBQ0MsT0FBUCxHQUFpQixVQUFDQyxHQUFELEVBQU1DLEVBQU4sRUFBYTtBQUM1QkQsRUFBQUEsR0FBRyxDQUFDRSxJQUFKLEdBQVcsRUFBWDtBQUNBRixFQUFBQSxHQUFHLENBQUNHLFdBQUosQ0FBZ0IsT0FBaEI7QUFDQUgsRUFBQUEsR0FBRyxDQUFDSSxFQUFKLENBQU8sTUFBUCxFQUFlLFVBQUFDLEtBQUssRUFBSTtBQUN0QkwsSUFBQUEsR0FBRyxDQUFDRSxJQUFKLElBQVlHLEtBQVo7QUFDRCxHQUZEO0FBR0FMLEVBQUFBLEdBQUcsQ0FBQ0ksRUFBSixDQUFPLEtBQVAsRUFBYyxZQUFNO0FBQ2xCLFFBQUk7QUFDRkgsTUFBQUEsRUFBRSxDQUFDLElBQUQsRUFBT0wsRUFBRSxDQUFDVSxLQUFILENBQVNOLEdBQUcsQ0FBQ0UsSUFBYixDQUFQLENBQUY7QUFDRCxLQUZELENBRUUsT0FBT0ssR0FBUCxFQUFZO0FBQ1pOLE1BQUFBLEVBQUUsQ0FBQ00sR0FBRCxDQUFGO0FBQ0Q7QUFDRixHQU5EO0FBT0QsQ0FiRCIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogTW9kdWxlIGRlcGVuZGVuY2llcy5cbiAqL1xuXG5jb25zdCBxcyA9IHJlcXVpcmUoJ3FzJyk7XG5cbm1vZHVsZS5leHBvcnRzID0gKHJlcywgZm4pID0+IHtcbiAgcmVzLnRleHQgPSAnJztcbiAgcmVzLnNldEVuY29kaW5nKCdhc2NpaScpO1xuICByZXMub24oJ2RhdGEnLCBjaHVuayA9PiB7XG4gICAgcmVzLnRleHQgKz0gY2h1bms7XG4gIH0pO1xuICByZXMub24oJ2VuZCcsICgpID0+IHtcbiAgICB0cnkge1xuICAgICAgZm4obnVsbCwgcXMucGFyc2UocmVzLnRleHQpKTtcbiAgICB9IGNhdGNoIChlcnIpIHtcbiAgICAgIGZuKGVycik7XG4gICAgfVxuICB9KTtcbn07XG4iXX0= \ No newline at end of file diff --git a/node_modules/superagent/lib/node/response.js b/node_modules/superagent/lib/node/response.js new file mode 100644 index 000000000..7da32619b --- /dev/null +++ b/node_modules/superagent/lib/node/response.js @@ -0,0 +1,126 @@ +"use strict"; + +/** + * Module dependencies. + */ +var util = require('util'); + +var Stream = require('stream'); + +var ResponseBase = require('../response-base'); +/** + * Expose `Response`. + */ + + +module.exports = Response; +/** + * Initialize a new `Response` with the given `xhr`. + * + * - set flags (.ok, .error, etc) + * - parse header + * + * @param {Request} req + * @param {Object} options + * @constructor + * @extends {Stream} + * @implements {ReadableStream} + * @api private + */ + +function Response(req) { + Stream.call(this); + this.res = req.res; + var res = this.res; + this.request = req; + this.req = req.req; + this.text = res.text; + this.body = res.body === undefined ? {} : res.body; + this.files = res.files || {}; + this.buffered = req._resBuffered; + this.headers = res.headers; + this.header = this.headers; + + this._setStatusProperties(res.statusCode); + + this._setHeaderProperties(this.header); + + this.setEncoding = res.setEncoding.bind(res); + res.on('data', this.emit.bind(this, 'data')); + res.on('end', this.emit.bind(this, 'end')); + res.on('close', this.emit.bind(this, 'close')); + res.on('error', this.emit.bind(this, 'error')); +} +/** + * Inherit from `Stream`. + */ + + +util.inherits(Response, Stream); // eslint-disable-next-line new-cap + +ResponseBase(Response.prototype); +/** + * Implements methods of a `ReadableStream` + */ + +Response.prototype.destroy = function (err) { + this.res.destroy(err); +}; +/** + * Pause. + */ + + +Response.prototype.pause = function () { + this.res.pause(); +}; +/** + * Resume. + */ + + +Response.prototype.resume = function () { + this.res.resume(); +}; +/** + * Return an `Error` representative of this response. + * + * @return {Error} + * @api public + */ + + +Response.prototype.toError = function () { + var req = this.req; + var method = req.method; + var path = req.path; + var msg = "cannot ".concat(method, " ").concat(path, " (").concat(this.status, ")"); + var err = new Error(msg); + err.status = this.status; + err.text = this.text; + err.method = method; + err.path = path; + return err; +}; + +Response.prototype.setStatusProperties = function (status) { + console.warn('In superagent 2.x setStatusProperties is a private method'); + return this._setStatusProperties(status); +}; +/** + * To json. + * + * @return {Object} + * @api public + */ + + +Response.prototype.toJSON = function () { + return { + req: this.request.toJSON(), + header: this.header, + status: this.status, + text: this.text + }; +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9ub2RlL3Jlc3BvbnNlLmpzIl0sIm5hbWVzIjpbInV0aWwiLCJyZXF1aXJlIiwiU3RyZWFtIiwiUmVzcG9uc2VCYXNlIiwibW9kdWxlIiwiZXhwb3J0cyIsIlJlc3BvbnNlIiwicmVxIiwiY2FsbCIsInJlcyIsInJlcXVlc3QiLCJ0ZXh0IiwiYm9keSIsInVuZGVmaW5lZCIsImZpbGVzIiwiYnVmZmVyZWQiLCJfcmVzQnVmZmVyZWQiLCJoZWFkZXJzIiwiaGVhZGVyIiwiX3NldFN0YXR1c1Byb3BlcnRpZXMiLCJzdGF0dXNDb2RlIiwiX3NldEhlYWRlclByb3BlcnRpZXMiLCJzZXRFbmNvZGluZyIsImJpbmQiLCJvbiIsImVtaXQiLCJpbmhlcml0cyIsInByb3RvdHlwZSIsImRlc3Ryb3kiLCJlcnIiLCJwYXVzZSIsInJlc3VtZSIsInRvRXJyb3IiLCJtZXRob2QiLCJwYXRoIiwibXNnIiwic3RhdHVzIiwiRXJyb3IiLCJzZXRTdGF0dXNQcm9wZXJ0aWVzIiwiY29uc29sZSIsIndhcm4iLCJ0b0pTT04iXSwibWFwcGluZ3MiOiI7O0FBQUE7OztBQUlBLElBQU1BLElBQUksR0FBR0MsT0FBTyxDQUFDLE1BQUQsQ0FBcEI7O0FBQ0EsSUFBTUMsTUFBTSxHQUFHRCxPQUFPLENBQUMsUUFBRCxDQUF0Qjs7QUFDQSxJQUFNRSxZQUFZLEdBQUdGLE9BQU8sQ0FBQyxrQkFBRCxDQUE1QjtBQUVBOzs7OztBQUlBRyxNQUFNLENBQUNDLE9BQVAsR0FBaUJDLFFBQWpCO0FBRUE7Ozs7Ozs7Ozs7Ozs7O0FBY0EsU0FBU0EsUUFBVCxDQUFrQkMsR0FBbEIsRUFBdUI7QUFDckJMLEVBQUFBLE1BQU0sQ0FBQ00sSUFBUCxDQUFZLElBQVo7QUFDQSxPQUFLQyxHQUFMLEdBQVdGLEdBQUcsQ0FBQ0UsR0FBZjtBQUZxQixNQUdiQSxHQUhhLEdBR0wsSUFISyxDQUdiQSxHQUhhO0FBSXJCLE9BQUtDLE9BQUwsR0FBZUgsR0FBZjtBQUNBLE9BQUtBLEdBQUwsR0FBV0EsR0FBRyxDQUFDQSxHQUFmO0FBQ0EsT0FBS0ksSUFBTCxHQUFZRixHQUFHLENBQUNFLElBQWhCO0FBQ0EsT0FBS0MsSUFBTCxHQUFZSCxHQUFHLENBQUNHLElBQUosS0FBYUMsU0FBYixHQUF5QixFQUF6QixHQUE4QkosR0FBRyxDQUFDRyxJQUE5QztBQUNBLE9BQUtFLEtBQUwsR0FBYUwsR0FBRyxDQUFDSyxLQUFKLElBQWEsRUFBMUI7QUFDQSxPQUFLQyxRQUFMLEdBQWdCUixHQUFHLENBQUNTLFlBQXBCO0FBQ0EsT0FBS0MsT0FBTCxHQUFlUixHQUFHLENBQUNRLE9BQW5CO0FBQ0EsT0FBS0MsTUFBTCxHQUFjLEtBQUtELE9BQW5COztBQUNBLE9BQUtFLG9CQUFMLENBQTBCVixHQUFHLENBQUNXLFVBQTlCOztBQUNBLE9BQUtDLG9CQUFMLENBQTBCLEtBQUtILE1BQS9COztBQUNBLE9BQUtJLFdBQUwsR0FBbUJiLEdBQUcsQ0FBQ2EsV0FBSixDQUFnQkMsSUFBaEIsQ0FBcUJkLEdBQXJCLENBQW5CO0FBQ0FBLEVBQUFBLEdBQUcsQ0FBQ2UsRUFBSixDQUFPLE1BQVAsRUFBZSxLQUFLQyxJQUFMLENBQVVGLElBQVYsQ0FBZSxJQUFmLEVBQXFCLE1BQXJCLENBQWY7QUFDQWQsRUFBQUEsR0FBRyxDQUFDZSxFQUFKLENBQU8sS0FBUCxFQUFjLEtBQUtDLElBQUwsQ0FBVUYsSUFBVixDQUFlLElBQWYsRUFBcUIsS0FBckIsQ0FBZDtBQUNBZCxFQUFBQSxHQUFHLENBQUNlLEVBQUosQ0FBTyxPQUFQLEVBQWdCLEtBQUtDLElBQUwsQ0FBVUYsSUFBVixDQUFlLElBQWYsRUFBcUIsT0FBckIsQ0FBaEI7QUFDQWQsRUFBQUEsR0FBRyxDQUFDZSxFQUFKLENBQU8sT0FBUCxFQUFnQixLQUFLQyxJQUFMLENBQVVGLElBQVYsQ0FBZSxJQUFmLEVBQXFCLE9BQXJCLENBQWhCO0FBQ0Q7QUFFRDs7Ozs7QUFJQXZCLElBQUksQ0FBQzBCLFFBQUwsQ0FBY3BCLFFBQWQsRUFBd0JKLE1BQXhCLEUsQ0FDQTs7QUFDQUMsWUFBWSxDQUFDRyxRQUFRLENBQUNxQixTQUFWLENBQVo7QUFFQTs7OztBQUlBckIsUUFBUSxDQUFDcUIsU0FBVCxDQUFtQkMsT0FBbkIsR0FBNkIsVUFBU0MsR0FBVCxFQUFjO0FBQ3pDLE9BQUtwQixHQUFMLENBQVNtQixPQUFULENBQWlCQyxHQUFqQjtBQUNELENBRkQ7QUFJQTs7Ozs7QUFJQXZCLFFBQVEsQ0FBQ3FCLFNBQVQsQ0FBbUJHLEtBQW5CLEdBQTJCLFlBQVc7QUFDcEMsT0FBS3JCLEdBQUwsQ0FBU3FCLEtBQVQ7QUFDRCxDQUZEO0FBSUE7Ozs7O0FBSUF4QixRQUFRLENBQUNxQixTQUFULENBQW1CSSxNQUFuQixHQUE0QixZQUFXO0FBQ3JDLE9BQUt0QixHQUFMLENBQVNzQixNQUFUO0FBQ0QsQ0FGRDtBQUlBOzs7Ozs7OztBQU9BekIsUUFBUSxDQUFDcUIsU0FBVCxDQUFtQkssT0FBbkIsR0FBNkIsWUFBVztBQUFBLE1BQzlCekIsR0FEOEIsR0FDdEIsSUFEc0IsQ0FDOUJBLEdBRDhCO0FBQUEsTUFFOUIwQixNQUY4QixHQUVuQjFCLEdBRm1CLENBRTlCMEIsTUFGOEI7QUFBQSxNQUc5QkMsSUFIOEIsR0FHckIzQixHQUhxQixDQUc5QjJCLElBSDhCO0FBS3RDLE1BQU1DLEdBQUcsb0JBQWFGLE1BQWIsY0FBdUJDLElBQXZCLGVBQWdDLEtBQUtFLE1BQXJDLE1BQVQ7QUFDQSxNQUFNUCxHQUFHLEdBQUcsSUFBSVEsS0FBSixDQUFVRixHQUFWLENBQVo7QUFDQU4sRUFBQUEsR0FBRyxDQUFDTyxNQUFKLEdBQWEsS0FBS0EsTUFBbEI7QUFDQVAsRUFBQUEsR0FBRyxDQUFDbEIsSUFBSixHQUFXLEtBQUtBLElBQWhCO0FBQ0FrQixFQUFBQSxHQUFHLENBQUNJLE1BQUosR0FBYUEsTUFBYjtBQUNBSixFQUFBQSxHQUFHLENBQUNLLElBQUosR0FBV0EsSUFBWDtBQUVBLFNBQU9MLEdBQVA7QUFDRCxDQWJEOztBQWVBdkIsUUFBUSxDQUFDcUIsU0FBVCxDQUFtQlcsbUJBQW5CLEdBQXlDLFVBQVNGLE1BQVQsRUFBaUI7QUFDeERHLEVBQUFBLE9BQU8sQ0FBQ0MsSUFBUixDQUFhLDJEQUFiO0FBQ0EsU0FBTyxLQUFLckIsb0JBQUwsQ0FBMEJpQixNQUExQixDQUFQO0FBQ0QsQ0FIRDtBQUtBOzs7Ozs7OztBQU9BOUIsUUFBUSxDQUFDcUIsU0FBVCxDQUFtQmMsTUFBbkIsR0FBNEIsWUFBVztBQUNyQyxTQUFPO0FBQ0xsQyxJQUFBQSxHQUFHLEVBQUUsS0FBS0csT0FBTCxDQUFhK0IsTUFBYixFQURBO0FBRUx2QixJQUFBQSxNQUFNLEVBQUUsS0FBS0EsTUFGUjtBQUdMa0IsSUFBQUEsTUFBTSxFQUFFLEtBQUtBLE1BSFI7QUFJTHpCLElBQUFBLElBQUksRUFBRSxLQUFLQTtBQUpOLEdBQVA7QUFNRCxDQVBEIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBNb2R1bGUgZGVwZW5kZW5jaWVzLlxuICovXG5cbmNvbnN0IHV0aWwgPSByZXF1aXJlKCd1dGlsJyk7XG5jb25zdCBTdHJlYW0gPSByZXF1aXJlKCdzdHJlYW0nKTtcbmNvbnN0IFJlc3BvbnNlQmFzZSA9IHJlcXVpcmUoJy4uL3Jlc3BvbnNlLWJhc2UnKTtcblxuLyoqXG4gKiBFeHBvc2UgYFJlc3BvbnNlYC5cbiAqL1xuXG5tb2R1bGUuZXhwb3J0cyA9IFJlc3BvbnNlO1xuXG4vKipcbiAqIEluaXRpYWxpemUgYSBuZXcgYFJlc3BvbnNlYCB3aXRoIHRoZSBnaXZlbiBgeGhyYC5cbiAqXG4gKiAgLSBzZXQgZmxhZ3MgKC5vaywgLmVycm9yLCBldGMpXG4gKiAgLSBwYXJzZSBoZWFkZXJcbiAqXG4gKiBAcGFyYW0ge1JlcXVlc3R9IHJlcVxuICogQHBhcmFtIHtPYmplY3R9IG9wdGlvbnNcbiAqIEBjb25zdHJ1Y3RvclxuICogQGV4dGVuZHMge1N0cmVhbX1cbiAqIEBpbXBsZW1lbnRzIHtSZWFkYWJsZVN0cmVhbX1cbiAqIEBhcGkgcHJpdmF0ZVxuICovXG5cbmZ1bmN0aW9uIFJlc3BvbnNlKHJlcSkge1xuICBTdHJlYW0uY2FsbCh0aGlzKTtcbiAgdGhpcy5yZXMgPSByZXEucmVzO1xuICBjb25zdCB7IHJlcyB9ID0gdGhpcztcbiAgdGhpcy5yZXF1ZXN0ID0gcmVxO1xuICB0aGlzLnJlcSA9IHJlcS5yZXE7XG4gIHRoaXMudGV4dCA9IHJlcy50ZXh0O1xuICB0aGlzLmJvZHkgPSByZXMuYm9keSA9PT0gdW5kZWZpbmVkID8ge30gOiByZXMuYm9keTtcbiAgdGhpcy5maWxlcyA9IHJlcy5maWxlcyB8fCB7fTtcbiAgdGhpcy5idWZmZXJlZCA9IHJlcS5fcmVzQnVmZmVyZWQ7XG4gIHRoaXMuaGVhZGVycyA9IHJlcy5oZWFkZXJzO1xuICB0aGlzLmhlYWRlciA9IHRoaXMuaGVhZGVycztcbiAgdGhpcy5fc2V0U3RhdHVzUHJvcGVydGllcyhyZXMuc3RhdHVzQ29kZSk7XG4gIHRoaXMuX3NldEhlYWRlclByb3BlcnRpZXModGhpcy5oZWFkZXIpO1xuICB0aGlzLnNldEVuY29kaW5nID0gcmVzLnNldEVuY29kaW5nLmJpbmQocmVzKTtcbiAgcmVzLm9uKCdkYXRhJywgdGhpcy5lbWl0LmJpbmQodGhpcywgJ2RhdGEnKSk7XG4gIHJlcy5vbignZW5kJywgdGhpcy5lbWl0LmJpbmQodGhpcywgJ2VuZCcpKTtcbiAgcmVzLm9uKCdjbG9zZScsIHRoaXMuZW1pdC5iaW5kKHRoaXMsICdjbG9zZScpKTtcbiAgcmVzLm9uKCdlcnJvcicsIHRoaXMuZW1pdC5iaW5kKHRoaXMsICdlcnJvcicpKTtcbn1cblxuLyoqXG4gKiBJbmhlcml0IGZyb20gYFN0cmVhbWAuXG4gKi9cblxudXRpbC5pbmhlcml0cyhSZXNwb25zZSwgU3RyZWFtKTtcbi8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBuZXctY2FwXG5SZXNwb25zZUJhc2UoUmVzcG9uc2UucHJvdG90eXBlKTtcblxuLyoqXG4gKiBJbXBsZW1lbnRzIG1ldGhvZHMgb2YgYSBgUmVhZGFibGVTdHJlYW1gXG4gKi9cblxuUmVzcG9uc2UucHJvdG90eXBlLmRlc3Ryb3kgPSBmdW5jdGlvbihlcnIpIHtcbiAgdGhpcy5yZXMuZGVzdHJveShlcnIpO1xufTtcblxuLyoqXG4gKiBQYXVzZS5cbiAqL1xuXG5SZXNwb25zZS5wcm90b3R5cGUucGF1c2UgPSBmdW5jdGlvbigpIHtcbiAgdGhpcy5yZXMucGF1c2UoKTtcbn07XG5cbi8qKlxuICogUmVzdW1lLlxuICovXG5cblJlc3BvbnNlLnByb3RvdHlwZS5yZXN1bWUgPSBmdW5jdGlvbigpIHtcbiAgdGhpcy5yZXMucmVzdW1lKCk7XG59O1xuXG4vKipcbiAqIFJldHVybiBhbiBgRXJyb3JgIHJlcHJlc2VudGF0aXZlIG9mIHRoaXMgcmVzcG9uc2UuXG4gKlxuICogQHJldHVybiB7RXJyb3J9XG4gKiBAYXBpIHB1YmxpY1xuICovXG5cblJlc3BvbnNlLnByb3RvdHlwZS50b0Vycm9yID0gZnVuY3Rpb24oKSB7XG4gIGNvbnN0IHsgcmVxIH0gPSB0aGlzO1xuICBjb25zdCB7IG1ldGhvZCB9ID0gcmVxO1xuICBjb25zdCB7IHBhdGggfSA9IHJlcTtcblxuICBjb25zdCBtc2cgPSBgY2Fubm90ICR7bWV0aG9kfSAke3BhdGh9ICgke3RoaXMuc3RhdHVzfSlgO1xuICBjb25zdCBlcnIgPSBuZXcgRXJyb3IobXNnKTtcbiAgZXJyLnN0YXR1cyA9IHRoaXMuc3RhdHVzO1xuICBlcnIudGV4dCA9IHRoaXMudGV4dDtcbiAgZXJyLm1ldGhvZCA9IG1ldGhvZDtcbiAgZXJyLnBhdGggPSBwYXRoO1xuXG4gIHJldHVybiBlcnI7XG59O1xuXG5SZXNwb25zZS5wcm90b3R5cGUuc2V0U3RhdHVzUHJvcGVydGllcyA9IGZ1bmN0aW9uKHN0YXR1cykge1xuICBjb25zb2xlLndhcm4oJ0luIHN1cGVyYWdlbnQgMi54IHNldFN0YXR1c1Byb3BlcnRpZXMgaXMgYSBwcml2YXRlIG1ldGhvZCcpO1xuICByZXR1cm4gdGhpcy5fc2V0U3RhdHVzUHJvcGVydGllcyhzdGF0dXMpO1xufTtcblxuLyoqXG4gKiBUbyBqc29uLlxuICpcbiAqIEByZXR1cm4ge09iamVjdH1cbiAqIEBhcGkgcHVibGljXG4gKi9cblxuUmVzcG9uc2UucHJvdG90eXBlLnRvSlNPTiA9IGZ1bmN0aW9uKCkge1xuICByZXR1cm4ge1xuICAgIHJlcTogdGhpcy5yZXF1ZXN0LnRvSlNPTigpLFxuICAgIGhlYWRlcjogdGhpcy5oZWFkZXIsXG4gICAgc3RhdHVzOiB0aGlzLnN0YXR1cyxcbiAgICB0ZXh0OiB0aGlzLnRleHRcbiAgfTtcbn07XG4iXX0= \ No newline at end of file diff --git a/node_modules/superagent/lib/node/unzip.js b/node_modules/superagent/lib/node/unzip.js new file mode 100644 index 000000000..7f0793f0f --- /dev/null +++ b/node_modules/superagent/lib/node/unzip.js @@ -0,0 +1,72 @@ +"use strict"; + +/** + * Module dependencies. + */ +var _require = require('string_decoder'), + StringDecoder = _require.StringDecoder; + +var Stream = require('stream'); + +var zlib = require('zlib'); +/** + * Buffers response data events and re-emits when they're unzipped. + * + * @param {Request} req + * @param {Response} res + * @api private + */ + + +exports.unzip = function (req, res) { + var unzip = zlib.createUnzip(); + var stream = new Stream(); + var decoder; // make node responseOnEnd() happy + + stream.req = req; + unzip.on('error', function (err) { + if (err && err.code === 'Z_BUF_ERROR') { + // unexpected end of file is ignored by browsers and curl + stream.emit('end'); + return; + } + + stream.emit('error', err); + }); // pipe to unzip + + res.pipe(unzip); // override `setEncoding` to capture encoding + + res.setEncoding = function (type) { + decoder = new StringDecoder(type); + }; // decode upon decompressing with captured encoding + + + unzip.on('data', function (buf) { + if (decoder) { + var str = decoder.write(buf); + if (str.length > 0) stream.emit('data', str); + } else { + stream.emit('data', buf); + } + }); + unzip.on('end', function () { + stream.emit('end'); + }); // override `on` to capture data listeners + + var _on = res.on; + + res.on = function (type, fn) { + if (type === 'data' || type === 'end') { + stream.on(type, fn.bind(res)); + } else if (type === 'error') { + stream.on(type, fn.bind(res)); + + _on.call(res, type, fn); + } else { + _on.call(res, type, fn); + } + + return this; + }; +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9ub2RlL3VuemlwLmpzIl0sIm5hbWVzIjpbInJlcXVpcmUiLCJTdHJpbmdEZWNvZGVyIiwiU3RyZWFtIiwiemxpYiIsImV4cG9ydHMiLCJ1bnppcCIsInJlcSIsInJlcyIsImNyZWF0ZVVuemlwIiwic3RyZWFtIiwiZGVjb2RlciIsIm9uIiwiZXJyIiwiY29kZSIsImVtaXQiLCJwaXBlIiwic2V0RW5jb2RpbmciLCJ0eXBlIiwiYnVmIiwic3RyIiwid3JpdGUiLCJsZW5ndGgiLCJfb24iLCJmbiIsImJpbmQiLCJjYWxsIl0sIm1hcHBpbmdzIjoiOztBQUFBOzs7ZUFJMEJBLE9BQU8sQ0FBQyxnQkFBRCxDO0lBQXpCQyxhLFlBQUFBLGE7O0FBQ1IsSUFBTUMsTUFBTSxHQUFHRixPQUFPLENBQUMsUUFBRCxDQUF0Qjs7QUFDQSxJQUFNRyxJQUFJLEdBQUdILE9BQU8sQ0FBQyxNQUFELENBQXBCO0FBRUE7Ozs7Ozs7OztBQVFBSSxPQUFPLENBQUNDLEtBQVIsR0FBZ0IsVUFBQ0MsR0FBRCxFQUFNQyxHQUFOLEVBQWM7QUFDNUIsTUFBTUYsS0FBSyxHQUFHRixJQUFJLENBQUNLLFdBQUwsRUFBZDtBQUNBLE1BQU1DLE1BQU0sR0FBRyxJQUFJUCxNQUFKLEVBQWY7QUFDQSxNQUFJUSxPQUFKLENBSDRCLENBSzVCOztBQUNBRCxFQUFBQSxNQUFNLENBQUNILEdBQVAsR0FBYUEsR0FBYjtBQUVBRCxFQUFBQSxLQUFLLENBQUNNLEVBQU4sQ0FBUyxPQUFULEVBQWtCLFVBQUFDLEdBQUcsRUFBSTtBQUN2QixRQUFJQSxHQUFHLElBQUlBLEdBQUcsQ0FBQ0MsSUFBSixLQUFhLGFBQXhCLEVBQXVDO0FBQ3JDO0FBQ0FKLE1BQUFBLE1BQU0sQ0FBQ0ssSUFBUCxDQUFZLEtBQVo7QUFDQTtBQUNEOztBQUVETCxJQUFBQSxNQUFNLENBQUNLLElBQVAsQ0FBWSxPQUFaLEVBQXFCRixHQUFyQjtBQUNELEdBUkQsRUFSNEIsQ0FrQjVCOztBQUNBTCxFQUFBQSxHQUFHLENBQUNRLElBQUosQ0FBU1YsS0FBVCxFQW5CNEIsQ0FxQjVCOztBQUNBRSxFQUFBQSxHQUFHLENBQUNTLFdBQUosR0FBa0IsVUFBQUMsSUFBSSxFQUFJO0FBQ3hCUCxJQUFBQSxPQUFPLEdBQUcsSUFBSVQsYUFBSixDQUFrQmdCLElBQWxCLENBQVY7QUFDRCxHQUZELENBdEI0QixDQTBCNUI7OztBQUNBWixFQUFBQSxLQUFLLENBQUNNLEVBQU4sQ0FBUyxNQUFULEVBQWlCLFVBQUFPLEdBQUcsRUFBSTtBQUN0QixRQUFJUixPQUFKLEVBQWE7QUFDWCxVQUFNUyxHQUFHLEdBQUdULE9BQU8sQ0FBQ1UsS0FBUixDQUFjRixHQUFkLENBQVo7QUFDQSxVQUFJQyxHQUFHLENBQUNFLE1BQUosR0FBYSxDQUFqQixFQUFvQlosTUFBTSxDQUFDSyxJQUFQLENBQVksTUFBWixFQUFvQkssR0FBcEI7QUFDckIsS0FIRCxNQUdPO0FBQ0xWLE1BQUFBLE1BQU0sQ0FBQ0ssSUFBUCxDQUFZLE1BQVosRUFBb0JJLEdBQXBCO0FBQ0Q7QUFDRixHQVBEO0FBU0FiLEVBQUFBLEtBQUssQ0FBQ00sRUFBTixDQUFTLEtBQVQsRUFBZ0IsWUFBTTtBQUNwQkYsSUFBQUEsTUFBTSxDQUFDSyxJQUFQLENBQVksS0FBWjtBQUNELEdBRkQsRUFwQzRCLENBd0M1Qjs7QUFDQSxNQUFNUSxHQUFHLEdBQUdmLEdBQUcsQ0FBQ0ksRUFBaEI7O0FBQ0FKLEVBQUFBLEdBQUcsQ0FBQ0ksRUFBSixHQUFTLFVBQVNNLElBQVQsRUFBZU0sRUFBZixFQUFtQjtBQUMxQixRQUFJTixJQUFJLEtBQUssTUFBVCxJQUFtQkEsSUFBSSxLQUFLLEtBQWhDLEVBQXVDO0FBQ3JDUixNQUFBQSxNQUFNLENBQUNFLEVBQVAsQ0FBVU0sSUFBVixFQUFnQk0sRUFBRSxDQUFDQyxJQUFILENBQVFqQixHQUFSLENBQWhCO0FBQ0QsS0FGRCxNQUVPLElBQUlVLElBQUksS0FBSyxPQUFiLEVBQXNCO0FBQzNCUixNQUFBQSxNQUFNLENBQUNFLEVBQVAsQ0FBVU0sSUFBVixFQUFnQk0sRUFBRSxDQUFDQyxJQUFILENBQVFqQixHQUFSLENBQWhCOztBQUNBZSxNQUFBQSxHQUFHLENBQUNHLElBQUosQ0FBU2xCLEdBQVQsRUFBY1UsSUFBZCxFQUFvQk0sRUFBcEI7QUFDRCxLQUhNLE1BR0E7QUFDTEQsTUFBQUEsR0FBRyxDQUFDRyxJQUFKLENBQVNsQixHQUFULEVBQWNVLElBQWQsRUFBb0JNLEVBQXBCO0FBQ0Q7O0FBRUQsV0FBTyxJQUFQO0FBQ0QsR0FYRDtBQVlELENBdEREIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBNb2R1bGUgZGVwZW5kZW5jaWVzLlxuICovXG5cbmNvbnN0IHsgU3RyaW5nRGVjb2RlciB9ID0gcmVxdWlyZSgnc3RyaW5nX2RlY29kZXInKTtcbmNvbnN0IFN0cmVhbSA9IHJlcXVpcmUoJ3N0cmVhbScpO1xuY29uc3QgemxpYiA9IHJlcXVpcmUoJ3psaWInKTtcblxuLyoqXG4gKiBCdWZmZXJzIHJlc3BvbnNlIGRhdGEgZXZlbnRzIGFuZCByZS1lbWl0cyB3aGVuIHRoZXkncmUgdW56aXBwZWQuXG4gKlxuICogQHBhcmFtIHtSZXF1ZXN0fSByZXFcbiAqIEBwYXJhbSB7UmVzcG9uc2V9IHJlc1xuICogQGFwaSBwcml2YXRlXG4gKi9cblxuZXhwb3J0cy51bnppcCA9IChyZXEsIHJlcykgPT4ge1xuICBjb25zdCB1bnppcCA9IHpsaWIuY3JlYXRlVW56aXAoKTtcbiAgY29uc3Qgc3RyZWFtID0gbmV3IFN0cmVhbSgpO1xuICBsZXQgZGVjb2RlcjtcblxuICAvLyBtYWtlIG5vZGUgcmVzcG9uc2VPbkVuZCgpIGhhcHB5XG4gIHN0cmVhbS5yZXEgPSByZXE7XG5cbiAgdW56aXAub24oJ2Vycm9yJywgZXJyID0+IHtcbiAgICBpZiAoZXJyICYmIGVyci5jb2RlID09PSAnWl9CVUZfRVJST1InKSB7XG4gICAgICAvLyB1bmV4cGVjdGVkIGVuZCBvZiBmaWxlIGlzIGlnbm9yZWQgYnkgYnJvd3NlcnMgYW5kIGN1cmxcbiAgICAgIHN0cmVhbS5lbWl0KCdlbmQnKTtcbiAgICAgIHJldHVybjtcbiAgICB9XG5cbiAgICBzdHJlYW0uZW1pdCgnZXJyb3InLCBlcnIpO1xuICB9KTtcblxuICAvLyBwaXBlIHRvIHVuemlwXG4gIHJlcy5waXBlKHVuemlwKTtcblxuICAvLyBvdmVycmlkZSBgc2V0RW5jb2RpbmdgIHRvIGNhcHR1cmUgZW5jb2RpbmdcbiAgcmVzLnNldEVuY29kaW5nID0gdHlwZSA9PiB7XG4gICAgZGVjb2RlciA9IG5ldyBTdHJpbmdEZWNvZGVyKHR5cGUpO1xuICB9O1xuXG4gIC8vIGRlY29kZSB1cG9uIGRlY29tcHJlc3Npbmcgd2l0aCBjYXB0dXJlZCBlbmNvZGluZ1xuICB1bnppcC5vbignZGF0YScsIGJ1ZiA9PiB7XG4gICAgaWYgKGRlY29kZXIpIHtcbiAgICAgIGNvbnN0IHN0ciA9IGRlY29kZXIud3JpdGUoYnVmKTtcbiAgICAgIGlmIChzdHIubGVuZ3RoID4gMCkgc3RyZWFtLmVtaXQoJ2RhdGEnLCBzdHIpO1xuICAgIH0gZWxzZSB7XG4gICAgICBzdHJlYW0uZW1pdCgnZGF0YScsIGJ1Zik7XG4gICAgfVxuICB9KTtcblxuICB1bnppcC5vbignZW5kJywgKCkgPT4ge1xuICAgIHN0cmVhbS5lbWl0KCdlbmQnKTtcbiAgfSk7XG5cbiAgLy8gb3ZlcnJpZGUgYG9uYCB0byBjYXB0dXJlIGRhdGEgbGlzdGVuZXJzXG4gIGNvbnN0IF9vbiA9IHJlcy5vbjtcbiAgcmVzLm9uID0gZnVuY3Rpb24odHlwZSwgZm4pIHtcbiAgICBpZiAodHlwZSA9PT0gJ2RhdGEnIHx8IHR5cGUgPT09ICdlbmQnKSB7XG4gICAgICBzdHJlYW0ub24odHlwZSwgZm4uYmluZChyZXMpKTtcbiAgICB9IGVsc2UgaWYgKHR5cGUgPT09ICdlcnJvcicpIHtcbiAgICAgIHN0cmVhbS5vbih0eXBlLCBmbi5iaW5kKHJlcykpO1xuICAgICAgX29uLmNhbGwocmVzLCB0eXBlLCBmbik7XG4gICAgfSBlbHNlIHtcbiAgICAgIF9vbi5jYWxsKHJlcywgdHlwZSwgZm4pO1xuICAgIH1cblxuICAgIHJldHVybiB0aGlzO1xuICB9O1xufTtcbiJdfQ== \ No newline at end of file diff --git a/node_modules/superagent/lib/request-base.js b/node_modules/superagent/lib/request-base.js new file mode 100644 index 000000000..36e54cdb0 --- /dev/null +++ b/node_modules/superagent/lib/request-base.js @@ -0,0 +1,757 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Module of mixed-in functions shared between node and client code + */ +var isObject = require('./is-object'); +/** + * Expose `RequestBase`. + */ + + +module.exports = RequestBase; +/** + * Initialize a new `RequestBase`. + * + * @api public + */ + +function RequestBase(obj) { + if (obj) return mixin(obj); +} +/** + * Mixin the prototype properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + + +function mixin(obj) { + for (var key in RequestBase.prototype) { + if (Object.prototype.hasOwnProperty.call(RequestBase.prototype, key)) obj[key] = RequestBase.prototype[key]; + } + + return obj; +} +/** + * Clear previous timeout. + * + * @return {Request} for chaining + * @api public + */ + + +RequestBase.prototype.clearTimeout = function () { + clearTimeout(this._timer); + clearTimeout(this._responseTimeoutTimer); + clearTimeout(this._uploadTimeoutTimer); + delete this._timer; + delete this._responseTimeoutTimer; + delete this._uploadTimeoutTimer; + return this; +}; +/** + * Override default response body parser + * + * This function will be called to convert incoming data into request.body + * + * @param {Function} + * @api public + */ + + +RequestBase.prototype.parse = function (fn) { + this._parser = fn; + return this; +}; +/** + * Set format of binary response body. + * In browser valid formats are 'blob' and 'arraybuffer', + * which return Blob and ArrayBuffer, respectively. + * + * In Node all values result in Buffer. + * + * Examples: + * + * req.get('/') + * .responseType('blob') + * .end(callback); + * + * @param {String} val + * @return {Request} for chaining + * @api public + */ + + +RequestBase.prototype.responseType = function (val) { + this._responseType = val; + return this; +}; +/** + * Override default request body serializer + * + * This function will be called to convert data set via .send or .attach into payload to send + * + * @param {Function} + * @api public + */ + + +RequestBase.prototype.serialize = function (fn) { + this._serializer = fn; + return this; +}; +/** + * Set timeouts. + * + * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time. + * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections. + * - upload is the time since last bit of data was sent or received. This timeout works only if deadline timeout is off + * + * Value of 0 or false means no timeout. + * + * @param {Number|Object} ms or {response, deadline} + * @return {Request} for chaining + * @api public + */ + + +RequestBase.prototype.timeout = function (options) { + if (!options || _typeof(options) !== 'object') { + this._timeout = options; + this._responseTimeout = 0; + this._uploadTimeout = 0; + return this; + } + + for (var option in options) { + if (Object.prototype.hasOwnProperty.call(options, option)) { + switch (option) { + case 'deadline': + this._timeout = options.deadline; + break; + + case 'response': + this._responseTimeout = options.response; + break; + + case 'upload': + this._uploadTimeout = options.upload; + break; + + default: + console.warn('Unknown timeout option', option); + } + } + } + + return this; +}; +/** + * Set number of retry attempts on error. + * + * Failed requests will be retried 'count' times if timeout or err.code >= 500. + * + * @param {Number} count + * @param {Function} [fn] + * @return {Request} for chaining + * @api public + */ + + +RequestBase.prototype.retry = function (count, fn) { + // Default to 1 if no count passed or true + if (arguments.length === 0 || count === true) count = 1; + if (count <= 0) count = 0; + this._maxRetries = count; + this._retries = 0; + this._retryCallback = fn; + return this; +}; + +var ERROR_CODES = ['ECONNRESET', 'ETIMEDOUT', 'EADDRINFO', 'ESOCKETTIMEDOUT']; +/** + * Determine if a request should be retried. + * (Borrowed from segmentio/superagent-retry) + * + * @param {Error} err an error + * @param {Response} [res] response + * @returns {Boolean} if segment should be retried + */ + +RequestBase.prototype._shouldRetry = function (err, res) { + if (!this._maxRetries || this._retries++ >= this._maxRetries) { + return false; + } + + if (this._retryCallback) { + try { + var override = this._retryCallback(err, res); + + if (override === true) return true; + if (override === false) return false; // undefined falls back to defaults + } catch (err_) { + console.error(err_); + } + } + + if (res && res.status && res.status >= 500 && res.status !== 501) return true; + + if (err) { + if (err.code && ERROR_CODES.includes(err.code)) return true; // Superagent timeout + + if (err.timeout && err.code === 'ECONNABORTED') return true; + if (err.crossDomain) return true; + } + + return false; +}; +/** + * Retry request + * + * @return {Request} for chaining + * @api private + */ + + +RequestBase.prototype._retry = function () { + this.clearTimeout(); // node + + if (this.req) { + this.req = null; + this.req = this.request(); + } + + this._aborted = false; + this.timedout = false; + this.timedoutError = null; + return this._end(); +}; +/** + * Promise support + * + * @param {Function} resolve + * @param {Function} [reject] + * @return {Request} + */ + + +RequestBase.prototype.then = function (resolve, reject) { + var _this = this; + + if (!this._fullfilledPromise) { + var self = this; + + if (this._endCalled) { + console.warn('Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises'); + } + + this._fullfilledPromise = new Promise(function (resolve, reject) { + self.on('abort', function () { + if (_this._maxRetries && _this._maxRetries > _this._retries) { + return; + } + + if (_this.timedout && _this.timedoutError) { + reject(_this.timedoutError); + return; + } + + var err = new Error('Aborted'); + err.code = 'ABORTED'; + err.status = _this.status; + err.method = _this.method; + err.url = _this.url; + reject(err); + }); + self.end(function (err, res) { + if (err) reject(err);else resolve(res); + }); + }); + } + + return this._fullfilledPromise.then(resolve, reject); +}; + +RequestBase.prototype.catch = function (cb) { + return this.then(undefined, cb); +}; +/** + * Allow for extension + */ + + +RequestBase.prototype.use = function (fn) { + fn(this); + return this; +}; + +RequestBase.prototype.ok = function (cb) { + if (typeof cb !== 'function') throw new Error('Callback required'); + this._okCallback = cb; + return this; +}; + +RequestBase.prototype._isResponseOK = function (res) { + if (!res) { + return false; + } + + if (this._okCallback) { + return this._okCallback(res); + } + + return res.status >= 200 && res.status < 300; +}; +/** + * Get request header `field`. + * Case-insensitive. + * + * @param {String} field + * @return {String} + * @api public + */ + + +RequestBase.prototype.get = function (field) { + return this._header[field.toLowerCase()]; +}; +/** + * Get case-insensitive header `field` value. + * This is a deprecated internal API. Use `.get(field)` instead. + * + * (getHeader is no longer used internally by the superagent code base) + * + * @param {String} field + * @return {String} + * @api private + * @deprecated + */ + + +RequestBase.prototype.getHeader = RequestBase.prototype.get; +/** + * Set header `field` to `val`, or multiple fields with one object. + * Case-insensitive. + * + * Examples: + * + * req.get('/') + * .set('Accept', 'application/json') + * .set('X-API-Key', 'foobar') + * .end(callback); + * + * req.get('/') + * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) + * .end(callback); + * + * @param {String|Object} field + * @param {String} val + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.set = function (field, val) { + if (isObject(field)) { + for (var key in field) { + if (Object.prototype.hasOwnProperty.call(field, key)) this.set(key, field[key]); + } + + return this; + } + + this._header[field.toLowerCase()] = val; + this.header[field] = val; + return this; +}; +/** + * Remove header `field`. + * Case-insensitive. + * + * Example: + * + * req.get('/') + * .unset('User-Agent') + * .end(callback); + * + * @param {String} field field name + */ + + +RequestBase.prototype.unset = function (field) { + delete this._header[field.toLowerCase()]; + delete this.header[field]; + return this; +}; +/** + * Write the field `name` and `val`, or multiple fields with one object + * for "multipart/form-data" request bodies. + * + * ``` js + * request.post('/upload') + * .field('foo', 'bar') + * .end(callback); + * + * request.post('/upload') + * .field({ foo: 'bar', baz: 'qux' }) + * .end(callback); + * ``` + * + * @param {String|Object} name name of field + * @param {String|Blob|File|Buffer|fs.ReadStream} val value of field + * @return {Request} for chaining + * @api public + */ + + +RequestBase.prototype.field = function (name, val) { + // name should be either a string or an object. + if (name === null || undefined === name) { + throw new Error('.field(name, val) name can not be empty'); + } + + if (this._data) { + throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()"); + } + + if (isObject(name)) { + for (var key in name) { + if (Object.prototype.hasOwnProperty.call(name, key)) this.field(key, name[key]); + } + + return this; + } + + if (Array.isArray(val)) { + for (var i in val) { + if (Object.prototype.hasOwnProperty.call(val, i)) this.field(name, val[i]); + } + + return this; + } // val should be defined now + + + if (val === null || undefined === val) { + throw new Error('.field(name, val) val can not be empty'); + } + + if (typeof val === 'boolean') { + val = String(val); + } + + this._getFormData().append(name, val); + + return this; +}; +/** + * Abort the request, and clear potential timeout. + * + * @return {Request} request + * @api public + */ + + +RequestBase.prototype.abort = function () { + if (this._aborted) { + return this; + } + + this._aborted = true; + if (this.xhr) this.xhr.abort(); // browser + + if (this.req) this.req.abort(); // node + + this.clearTimeout(); + this.emit('abort'); + return this; +}; + +RequestBase.prototype._auth = function (user, pass, options, base64Encoder) { + switch (options.type) { + case 'basic': + this.set('Authorization', "Basic ".concat(base64Encoder("".concat(user, ":").concat(pass)))); + break; + + case 'auto': + this.username = user; + this.password = pass; + break; + + case 'bearer': + // usage would be .auth(accessToken, { type: 'bearer' }) + this.set('Authorization', "Bearer ".concat(user)); + break; + + default: + break; + } + + return this; +}; +/** + * Enable transmission of cookies with x-domain requests. + * + * Note that for this to work the origin must not be + * using "Access-Control-Allow-Origin" with a wildcard, + * and also must set "Access-Control-Allow-Credentials" + * to "true". + * + * @api public + */ + + +RequestBase.prototype.withCredentials = function (on) { + // This is browser-only functionality. Node side is no-op. + if (on === undefined) on = true; + this._withCredentials = on; + return this; +}; +/** + * Set the max redirects to `n`. Does nothing in browser XHR implementation. + * + * @param {Number} n + * @return {Request} for chaining + * @api public + */ + + +RequestBase.prototype.redirects = function (n) { + this._maxRedirects = n; + return this; +}; +/** + * Maximum size of buffered response body, in bytes. Counts uncompressed size. + * Default 200MB. + * + * @param {Number} n number of bytes + * @return {Request} for chaining + */ + + +RequestBase.prototype.maxResponseSize = function (n) { + if (typeof n !== 'number') { + throw new TypeError('Invalid argument'); + } + + this._maxResponseSize = n; + return this; +}; +/** + * Convert to a plain javascript object (not JSON string) of scalar properties. + * Note as this method is designed to return a useful non-this value, + * it cannot be chained. + * + * @return {Object} describing method, url, and data of this request + * @api public + */ + + +RequestBase.prototype.toJSON = function () { + return { + method: this.method, + url: this.url, + data: this._data, + headers: this._header + }; +}; +/** + * Send `data` as the request body, defaulting the `.type()` to "json" when + * an object is given. + * + * Examples: + * + * // manual json + * request.post('/user') + * .type('json') + * .send('{"name":"tj"}') + * .end(callback) + * + * // auto json + * request.post('/user') + * .send({ name: 'tj' }) + * .end(callback) + * + * // manual x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send('name=tj') + * .end(callback) + * + * // auto x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send({ name: 'tj' }) + * .end(callback) + * + * // defaults to x-www-form-urlencoded + * request.post('/user') + * .send('name=tobi') + * .send('species=ferret') + * .end(callback) + * + * @param {String|Object} data + * @return {Request} for chaining + * @api public + */ +// eslint-disable-next-line complexity + + +RequestBase.prototype.send = function (data) { + var isObj = isObject(data); + var type = this._header['content-type']; + + if (this._formData) { + throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()"); + } + + if (isObj && !this._data) { + if (Array.isArray(data)) { + this._data = []; + } else if (!this._isHost(data)) { + this._data = {}; + } + } else if (data && this._data && this._isHost(this._data)) { + throw new Error("Can't merge these send calls"); + } // merge + + + if (isObj && isObject(this._data)) { + for (var key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) this._data[key] = data[key]; + } + } else if (typeof data === 'string') { + // default to x-www-form-urlencoded + if (!type) this.type('form'); + type = this._header['content-type']; + + if (type === 'application/x-www-form-urlencoded') { + this._data = this._data ? "".concat(this._data, "&").concat(data) : data; + } else { + this._data = (this._data || '') + data; + } + } else { + this._data = data; + } + + if (!isObj || this._isHost(data)) { + return this; + } // default to json + + + if (!type) this.type('json'); + return this; +}; +/** + * Sort `querystring` by the sort function + * + * + * Examples: + * + * // default order + * request.get('/user') + * .query('name=Nick') + * .query('search=Manny') + * .sortQuery() + * .end(callback) + * + * // customized sort function + * request.get('/user') + * .query('name=Nick') + * .query('search=Manny') + * .sortQuery(function(a, b){ + * return a.length - b.length; + * }) + * .end(callback) + * + * + * @param {Function} sort + * @return {Request} for chaining + * @api public + */ + + +RequestBase.prototype.sortQuery = function (sort) { + // _sort default to true but otherwise can be a function or boolean + this._sort = typeof sort === 'undefined' ? true : sort; + return this; +}; +/** + * Compose querystring to append to req.url + * + * @api private + */ + + +RequestBase.prototype._finalizeQueryString = function () { + var query = this._query.join('&'); + + if (query) { + this.url += (this.url.includes('?') ? '&' : '?') + query; + } + + this._query.length = 0; // Makes the call idempotent + + if (this._sort) { + var index = this.url.indexOf('?'); + + if (index >= 0) { + var queryArr = this.url.slice(index + 1).split('&'); + + if (typeof this._sort === 'function') { + queryArr.sort(this._sort); + } else { + queryArr.sort(); + } + + this.url = this.url.slice(0, index) + '?' + queryArr.join('&'); + } + } +}; // For backwards compat only + + +RequestBase.prototype._appendQueryString = function () { + console.warn('Unsupported'); +}; +/** + * Invoke callback with timeout error. + * + * @api private + */ + + +RequestBase.prototype._timeoutError = function (reason, timeout, errno) { + if (this._aborted) { + return; + } + + var err = new Error("".concat(reason + timeout, "ms exceeded")); + err.timeout = timeout; + err.code = 'ECONNABORTED'; + err.errno = errno; + this.timedout = true; + this.timedoutError = err; + this.abort(); + this.callback(err); +}; + +RequestBase.prototype._setTimeouts = function () { + var self = this; // deadline + + if (this._timeout && !this._timer) { + this._timer = setTimeout(function () { + self._timeoutError('Timeout of ', self._timeout, 'ETIME'); + }, this._timeout); + } // response timeout + + + if (this._responseTimeout && !this._responseTimeoutTimer) { + this._responseTimeoutTimer = setTimeout(function () { + self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT'); + }, this._responseTimeout); + } +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uL3NyYy9yZXF1ZXN0LWJhc2UuanMiXSwibmFtZXMiOlsiaXNPYmplY3QiLCJyZXF1aXJlIiwibW9kdWxlIiwiZXhwb3J0cyIsIlJlcXVlc3RCYXNlIiwib2JqIiwibWl4aW4iLCJrZXkiLCJwcm90b3R5cGUiLCJPYmplY3QiLCJoYXNPd25Qcm9wZXJ0eSIsImNhbGwiLCJjbGVhclRpbWVvdXQiLCJfdGltZXIiLCJfcmVzcG9uc2VUaW1lb3V0VGltZXIiLCJfdXBsb2FkVGltZW91dFRpbWVyIiwicGFyc2UiLCJmbiIsIl9wYXJzZXIiLCJyZXNwb25zZVR5cGUiLCJ2YWwiLCJfcmVzcG9uc2VUeXBlIiwic2VyaWFsaXplIiwiX3NlcmlhbGl6ZXIiLCJ0aW1lb3V0Iiwib3B0aW9ucyIsIl90aW1lb3V0IiwiX3Jlc3BvbnNlVGltZW91dCIsIl91cGxvYWRUaW1lb3V0Iiwib3B0aW9uIiwiZGVhZGxpbmUiLCJyZXNwb25zZSIsInVwbG9hZCIsImNvbnNvbGUiLCJ3YXJuIiwicmV0cnkiLCJjb3VudCIsImFyZ3VtZW50cyIsImxlbmd0aCIsIl9tYXhSZXRyaWVzIiwiX3JldHJpZXMiLCJfcmV0cnlDYWxsYmFjayIsIkVSUk9SX0NPREVTIiwiX3Nob3VsZFJldHJ5IiwiZXJyIiwicmVzIiwib3ZlcnJpZGUiLCJlcnJfIiwiZXJyb3IiLCJzdGF0dXMiLCJjb2RlIiwiaW5jbHVkZXMiLCJjcm9zc0RvbWFpbiIsIl9yZXRyeSIsInJlcSIsInJlcXVlc3QiLCJfYWJvcnRlZCIsInRpbWVkb3V0IiwidGltZWRvdXRFcnJvciIsIl9lbmQiLCJ0aGVuIiwicmVzb2x2ZSIsInJlamVjdCIsIl9mdWxsZmlsbGVkUHJvbWlzZSIsInNlbGYiLCJfZW5kQ2FsbGVkIiwiUHJvbWlzZSIsIm9uIiwiRXJyb3IiLCJtZXRob2QiLCJ1cmwiLCJlbmQiLCJjYXRjaCIsImNiIiwidW5kZWZpbmVkIiwidXNlIiwib2siLCJfb2tDYWxsYmFjayIsIl9pc1Jlc3BvbnNlT0siLCJnZXQiLCJmaWVsZCIsIl9oZWFkZXIiLCJ0b0xvd2VyQ2FzZSIsImdldEhlYWRlciIsInNldCIsImhlYWRlciIsInVuc2V0IiwibmFtZSIsIl9kYXRhIiwiQXJyYXkiLCJpc0FycmF5IiwiaSIsIlN0cmluZyIsIl9nZXRGb3JtRGF0YSIsImFwcGVuZCIsImFib3J0IiwieGhyIiwiZW1pdCIsIl9hdXRoIiwidXNlciIsInBhc3MiLCJiYXNlNjRFbmNvZGVyIiwidHlwZSIsInVzZXJuYW1lIiwicGFzc3dvcmQiLCJ3aXRoQ3JlZGVudGlhbHMiLCJfd2l0aENyZWRlbnRpYWxzIiwicmVkaXJlY3RzIiwibiIsIl9tYXhSZWRpcmVjdHMiLCJtYXhSZXNwb25zZVNpemUiLCJUeXBlRXJyb3IiLCJfbWF4UmVzcG9uc2VTaXplIiwidG9KU09OIiwiZGF0YSIsImhlYWRlcnMiLCJzZW5kIiwiaXNPYmoiLCJfZm9ybURhdGEiLCJfaXNIb3N0Iiwic29ydFF1ZXJ5Iiwic29ydCIsIl9zb3J0IiwiX2ZpbmFsaXplUXVlcnlTdHJpbmciLCJxdWVyeSIsIl9xdWVyeSIsImpvaW4iLCJpbmRleCIsImluZGV4T2YiLCJxdWVyeUFyciIsInNsaWNlIiwic3BsaXQiLCJfYXBwZW5kUXVlcnlTdHJpbmciLCJfdGltZW91dEVycm9yIiwicmVhc29uIiwiZXJybm8iLCJjYWxsYmFjayIsIl9zZXRUaW1lb3V0cyIsInNldFRpbWVvdXQiXSwibWFwcGluZ3MiOiI7Ozs7QUFBQTs7O0FBR0EsSUFBTUEsUUFBUSxHQUFHQyxPQUFPLENBQUMsYUFBRCxDQUF4QjtBQUVBOzs7OztBQUlBQyxNQUFNLENBQUNDLE9BQVAsR0FBaUJDLFdBQWpCO0FBRUE7Ozs7OztBQU1BLFNBQVNBLFdBQVQsQ0FBcUJDLEdBQXJCLEVBQTBCO0FBQ3hCLE1BQUlBLEdBQUosRUFBUyxPQUFPQyxLQUFLLENBQUNELEdBQUQsQ0FBWjtBQUNWO0FBRUQ7Ozs7Ozs7OztBQVFBLFNBQVNDLEtBQVQsQ0FBZUQsR0FBZixFQUFvQjtBQUNsQixPQUFLLElBQU1FLEdBQVgsSUFBa0JILFdBQVcsQ0FBQ0ksU0FBOUIsRUFBeUM7QUFDdkMsUUFBSUMsTUFBTSxDQUFDRCxTQUFQLENBQWlCRSxjQUFqQixDQUFnQ0MsSUFBaEMsQ0FBcUNQLFdBQVcsQ0FBQ0ksU0FBakQsRUFBNERELEdBQTVELENBQUosRUFDRUYsR0FBRyxDQUFDRSxHQUFELENBQUgsR0FBV0gsV0FBVyxDQUFDSSxTQUFaLENBQXNCRCxHQUF0QixDQUFYO0FBQ0g7O0FBRUQsU0FBT0YsR0FBUDtBQUNEO0FBRUQ7Ozs7Ozs7O0FBT0FELFdBQVcsQ0FBQ0ksU0FBWixDQUFzQkksWUFBdEIsR0FBcUMsWUFBVztBQUM5Q0EsRUFBQUEsWUFBWSxDQUFDLEtBQUtDLE1BQU4sQ0FBWjtBQUNBRCxFQUFBQSxZQUFZLENBQUMsS0FBS0UscUJBQU4sQ0FBWjtBQUNBRixFQUFBQSxZQUFZLENBQUMsS0FBS0csbUJBQU4sQ0FBWjtBQUNBLFNBQU8sS0FBS0YsTUFBWjtBQUNBLFNBQU8sS0FBS0MscUJBQVo7QUFDQSxTQUFPLEtBQUtDLG1CQUFaO0FBQ0EsU0FBTyxJQUFQO0FBQ0QsQ0FSRDtBQVVBOzs7Ozs7Ozs7O0FBU0FYLFdBQVcsQ0FBQ0ksU0FBWixDQUFzQlEsS0FBdEIsR0FBOEIsVUFBU0MsRUFBVCxFQUFhO0FBQ3pDLE9BQUtDLE9BQUwsR0FBZUQsRUFBZjtBQUNBLFNBQU8sSUFBUDtBQUNELENBSEQ7QUFLQTs7Ozs7Ozs7Ozs7Ozs7Ozs7OztBQWtCQWIsV0FBVyxDQUFDSSxTQUFaLENBQXNCVyxZQUF0QixHQUFxQyxVQUFTQyxHQUFULEVBQWM7QUFDakQsT0FBS0MsYUFBTCxHQUFxQkQsR0FBckI7QUFDQSxTQUFPLElBQVA7QUFDRCxDQUhEO0FBS0E7Ozs7Ozs7Ozs7QUFTQWhCLFdBQVcsQ0FBQ0ksU0FBWixDQUFzQmMsU0FBdEIsR0FBa0MsVUFBU0wsRUFBVCxFQUFhO0FBQzdDLE9BQUtNLFdBQUwsR0FBbUJOLEVBQW5CO0FBQ0EsU0FBTyxJQUFQO0FBQ0QsQ0FIRDtBQUtBOzs7Ozs7Ozs7Ozs7Ozs7QUFjQWIsV0FBVyxDQUFDSSxTQUFaLENBQXNCZ0IsT0FBdEIsR0FBZ0MsVUFBU0MsT0FBVCxFQUFrQjtBQUNoRCxNQUFJLENBQUNBLE9BQUQsSUFBWSxRQUFPQSxPQUFQLE1BQW1CLFFBQW5DLEVBQTZDO0FBQzNDLFNBQUtDLFFBQUwsR0FBZ0JELE9BQWhCO0FBQ0EsU0FBS0UsZ0JBQUwsR0FBd0IsQ0FBeEI7QUFDQSxTQUFLQyxjQUFMLEdBQXNCLENBQXRCO0FBQ0EsV0FBTyxJQUFQO0FBQ0Q7O0FBRUQsT0FBSyxJQUFNQyxNQUFYLElBQXFCSixPQUFyQixFQUE4QjtBQUM1QixRQUFJaEIsTUFBTSxDQUFDRCxTQUFQLENBQWlCRSxjQUFqQixDQUFnQ0MsSUFBaEMsQ0FBcUNjLE9BQXJDLEVBQThDSSxNQUE5QyxDQUFKLEVBQTJEO0FBQ3pELGNBQVFBLE1BQVI7QUFDRSxhQUFLLFVBQUw7QUFDRSxlQUFLSCxRQUFMLEdBQWdCRCxPQUFPLENBQUNLLFFBQXhCO0FBQ0E7O0FBQ0YsYUFBSyxVQUFMO0FBQ0UsZUFBS0gsZ0JBQUwsR0FBd0JGLE9BQU8sQ0FBQ00sUUFBaEM7QUFDQTs7QUFDRixhQUFLLFFBQUw7QUFDRSxlQUFLSCxjQUFMLEdBQXNCSCxPQUFPLENBQUNPLE1BQTlCO0FBQ0E7O0FBQ0Y7QUFDRUMsVUFBQUEsT0FBTyxDQUFDQyxJQUFSLENBQWEsd0JBQWIsRUFBdUNMLE1BQXZDO0FBWEo7QUFhRDtBQUNGOztBQUVELFNBQU8sSUFBUDtBQUNELENBM0JEO0FBNkJBOzs7Ozs7Ozs7Ozs7QUFXQXpCLFdBQVcsQ0FBQ0ksU0FBWixDQUFzQjJCLEtBQXRCLEdBQThCLFVBQVNDLEtBQVQsRUFBZ0JuQixFQUFoQixFQUFvQjtBQUNoRDtBQUNBLE1BQUlvQixTQUFTLENBQUNDLE1BQVYsS0FBcUIsQ0FBckIsSUFBMEJGLEtBQUssS0FBSyxJQUF4QyxFQUE4Q0EsS0FBSyxHQUFHLENBQVI7QUFDOUMsTUFBSUEsS0FBSyxJQUFJLENBQWIsRUFBZ0JBLEtBQUssR0FBRyxDQUFSO0FBQ2hCLE9BQUtHLFdBQUwsR0FBbUJILEtBQW5CO0FBQ0EsT0FBS0ksUUFBTCxHQUFnQixDQUFoQjtBQUNBLE9BQUtDLGNBQUwsR0FBc0J4QixFQUF0QjtBQUNBLFNBQU8sSUFBUDtBQUNELENBUkQ7O0FBVUEsSUFBTXlCLFdBQVcsR0FBRyxDQUFDLFlBQUQsRUFBZSxXQUFmLEVBQTRCLFdBQTVCLEVBQXlDLGlCQUF6QyxDQUFwQjtBQUVBOzs7Ozs7Ozs7QUFRQXRDLFdBQVcsQ0FBQ0ksU0FBWixDQUFzQm1DLFlBQXRCLEdBQXFDLFVBQVNDLEdBQVQsRUFBY0MsR0FBZCxFQUFtQjtBQUN0RCxNQUFJLENBQUMsS0FBS04sV0FBTixJQUFxQixLQUFLQyxRQUFMLE1BQW1CLEtBQUtELFdBQWpELEVBQThEO0FBQzVELFdBQU8sS0FBUDtBQUNEOztBQUVELE1BQUksS0FBS0UsY0FBVCxFQUF5QjtBQUN2QixRQUFJO0FBQ0YsVUFBTUssUUFBUSxHQUFHLEtBQUtMLGNBQUwsQ0FBb0JHLEdBQXBCLEVBQXlCQyxHQUF6QixDQUFqQjs7QUFDQSxVQUFJQyxRQUFRLEtBQUssSUFBakIsRUFBdUIsT0FBTyxJQUFQO0FBQ3ZCLFVBQUlBLFFBQVEsS0FBSyxLQUFqQixFQUF3QixPQUFPLEtBQVAsQ0FIdEIsQ0FJRjtBQUNELEtBTEQsQ0FLRSxPQUFPQyxJQUFQLEVBQWE7QUFDYmQsTUFBQUEsT0FBTyxDQUFDZSxLQUFSLENBQWNELElBQWQ7QUFDRDtBQUNGOztBQUVELE1BQUlGLEdBQUcsSUFBSUEsR0FBRyxDQUFDSSxNQUFYLElBQXFCSixHQUFHLENBQUNJLE1BQUosSUFBYyxHQUFuQyxJQUEwQ0osR0FBRyxDQUFDSSxNQUFKLEtBQWUsR0FBN0QsRUFBa0UsT0FBTyxJQUFQOztBQUNsRSxNQUFJTCxHQUFKLEVBQVM7QUFDUCxRQUFJQSxHQUFHLENBQUNNLElBQUosSUFBWVIsV0FBVyxDQUFDUyxRQUFaLENBQXFCUCxHQUFHLENBQUNNLElBQXpCLENBQWhCLEVBQWdELE9BQU8sSUFBUCxDQUR6QyxDQUVQOztBQUNBLFFBQUlOLEdBQUcsQ0FBQ3BCLE9BQUosSUFBZW9CLEdBQUcsQ0FBQ00sSUFBSixLQUFhLGNBQWhDLEVBQWdELE9BQU8sSUFBUDtBQUNoRCxRQUFJTixHQUFHLENBQUNRLFdBQVIsRUFBcUIsT0FBTyxJQUFQO0FBQ3RCOztBQUVELFNBQU8sS0FBUDtBQUNELENBekJEO0FBMkJBOzs7Ozs7OztBQU9BaEQsV0FBVyxDQUFDSSxTQUFaLENBQXNCNkMsTUFBdEIsR0FBK0IsWUFBVztBQUN4QyxPQUFLekMsWUFBTCxHQUR3QyxDQUd4Qzs7QUFDQSxNQUFJLEtBQUswQyxHQUFULEVBQWM7QUFDWixTQUFLQSxHQUFMLEdBQVcsSUFBWDtBQUNBLFNBQUtBLEdBQUwsR0FBVyxLQUFLQyxPQUFMLEVBQVg7QUFDRDs7QUFFRCxPQUFLQyxRQUFMLEdBQWdCLEtBQWhCO0FBQ0EsT0FBS0MsUUFBTCxHQUFnQixLQUFoQjtBQUNBLE9BQUtDLGFBQUwsR0FBcUIsSUFBckI7QUFFQSxTQUFPLEtBQUtDLElBQUwsRUFBUDtBQUNELENBZEQ7QUFnQkE7Ozs7Ozs7OztBQVFBdkQsV0FBVyxDQUFDSSxTQUFaLENBQXNCb0QsSUFBdEIsR0FBNkIsVUFBU0MsT0FBVCxFQUFrQkMsTUFBbEIsRUFBMEI7QUFBQTs7QUFDckQsTUFBSSxDQUFDLEtBQUtDLGtCQUFWLEVBQThCO0FBQzVCLFFBQU1DLElBQUksR0FBRyxJQUFiOztBQUNBLFFBQUksS0FBS0MsVUFBVCxFQUFxQjtBQUNuQmhDLE1BQUFBLE9BQU8sQ0FBQ0MsSUFBUixDQUNFLGdJQURGO0FBR0Q7O0FBRUQsU0FBSzZCLGtCQUFMLEdBQTBCLElBQUlHLE9BQUosQ0FBWSxVQUFDTCxPQUFELEVBQVVDLE1BQVYsRUFBcUI7QUFDekRFLE1BQUFBLElBQUksQ0FBQ0csRUFBTCxDQUFRLE9BQVIsRUFBaUIsWUFBTTtBQUNyQixZQUFJLEtBQUksQ0FBQzVCLFdBQUwsSUFBb0IsS0FBSSxDQUFDQSxXQUFMLEdBQW1CLEtBQUksQ0FBQ0MsUUFBaEQsRUFBMEQ7QUFDeEQ7QUFDRDs7QUFFRCxZQUFJLEtBQUksQ0FBQ2lCLFFBQUwsSUFBaUIsS0FBSSxDQUFDQyxhQUExQixFQUF5QztBQUN2Q0ksVUFBQUEsTUFBTSxDQUFDLEtBQUksQ0FBQ0osYUFBTixDQUFOO0FBQ0E7QUFDRDs7QUFFRCxZQUFNZCxHQUFHLEdBQUcsSUFBSXdCLEtBQUosQ0FBVSxTQUFWLENBQVo7QUFDQXhCLFFBQUFBLEdBQUcsQ0FBQ00sSUFBSixHQUFXLFNBQVg7QUFDQU4sUUFBQUEsR0FBRyxDQUFDSyxNQUFKLEdBQWEsS0FBSSxDQUFDQSxNQUFsQjtBQUNBTCxRQUFBQSxHQUFHLENBQUN5QixNQUFKLEdBQWEsS0FBSSxDQUFDQSxNQUFsQjtBQUNBekIsUUFBQUEsR0FBRyxDQUFDMEIsR0FBSixHQUFVLEtBQUksQ0FBQ0EsR0FBZjtBQUNBUixRQUFBQSxNQUFNLENBQUNsQixHQUFELENBQU47QUFDRCxPQWhCRDtBQWlCQW9CLE1BQUFBLElBQUksQ0FBQ08sR0FBTCxDQUFTLFVBQUMzQixHQUFELEVBQU1DLEdBQU4sRUFBYztBQUNyQixZQUFJRCxHQUFKLEVBQVNrQixNQUFNLENBQUNsQixHQUFELENBQU4sQ0FBVCxLQUNLaUIsT0FBTyxDQUFDaEIsR0FBRCxDQUFQO0FBQ04sT0FIRDtBQUlELEtBdEJ5QixDQUExQjtBQXVCRDs7QUFFRCxTQUFPLEtBQUtrQixrQkFBTCxDQUF3QkgsSUFBeEIsQ0FBNkJDLE9BQTdCLEVBQXNDQyxNQUF0QyxDQUFQO0FBQ0QsQ0FuQ0Q7O0FBcUNBMUQsV0FBVyxDQUFDSSxTQUFaLENBQXNCZ0UsS0FBdEIsR0FBOEIsVUFBU0MsRUFBVCxFQUFhO0FBQ3pDLFNBQU8sS0FBS2IsSUFBTCxDQUFVYyxTQUFWLEVBQXFCRCxFQUFyQixDQUFQO0FBQ0QsQ0FGRDtBQUlBOzs7OztBQUlBckUsV0FBVyxDQUFDSSxTQUFaLENBQXNCbUUsR0FBdEIsR0FBNEIsVUFBUzFELEVBQVQsRUFBYTtBQUN2Q0EsRUFBQUEsRUFBRSxDQUFDLElBQUQsQ0FBRjtBQUNBLFNBQU8sSUFBUDtBQUNELENBSEQ7O0FBS0FiLFdBQVcsQ0FBQ0ksU0FBWixDQUFzQm9FLEVBQXRCLEdBQTJCLFVBQVNILEVBQVQsRUFBYTtBQUN0QyxNQUFJLE9BQU9BLEVBQVAsS0FBYyxVQUFsQixFQUE4QixNQUFNLElBQUlMLEtBQUosQ0FBVSxtQkFBVixDQUFOO0FBQzlCLE9BQUtTLFdBQUwsR0FBbUJKLEVBQW5CO0FBQ0EsU0FBTyxJQUFQO0FBQ0QsQ0FKRDs7QUFNQXJFLFdBQVcsQ0FBQ0ksU0FBWixDQUFzQnNFLGFBQXRCLEdBQXNDLFVBQVNqQyxHQUFULEVBQWM7QUFDbEQsTUFBSSxDQUFDQSxHQUFMLEVBQVU7QUFDUixXQUFPLEtBQVA7QUFDRDs7QUFFRCxNQUFJLEtBQUtnQyxXQUFULEVBQXNCO0FBQ3BCLFdBQU8sS0FBS0EsV0FBTCxDQUFpQmhDLEdBQWpCLENBQVA7QUFDRDs7QUFFRCxTQUFPQSxHQUFHLENBQUNJLE1BQUosSUFBYyxHQUFkLElBQXFCSixHQUFHLENBQUNJLE1BQUosR0FBYSxHQUF6QztBQUNELENBVkQ7QUFZQTs7Ozs7Ozs7OztBQVNBN0MsV0FBVyxDQUFDSSxTQUFaLENBQXNCdUUsR0FBdEIsR0FBNEIsVUFBU0MsS0FBVCxFQUFnQjtBQUMxQyxTQUFPLEtBQUtDLE9BQUwsQ0FBYUQsS0FBSyxDQUFDRSxXQUFOLEVBQWIsQ0FBUDtBQUNELENBRkQ7QUFJQTs7Ozs7Ozs7Ozs7OztBQVlBOUUsV0FBVyxDQUFDSSxTQUFaLENBQXNCMkUsU0FBdEIsR0FBa0MvRSxXQUFXLENBQUNJLFNBQVosQ0FBc0J1RSxHQUF4RDtBQUVBOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7QUFxQkEzRSxXQUFXLENBQUNJLFNBQVosQ0FBc0I0RSxHQUF0QixHQUE0QixVQUFTSixLQUFULEVBQWdCNUQsR0FBaEIsRUFBcUI7QUFDL0MsTUFBSXBCLFFBQVEsQ0FBQ2dGLEtBQUQsQ0FBWixFQUFxQjtBQUNuQixTQUFLLElBQU16RSxHQUFYLElBQWtCeUUsS0FBbEIsRUFBeUI7QUFDdkIsVUFBSXZFLE1BQU0sQ0FBQ0QsU0FBUCxDQUFpQkUsY0FBakIsQ0FBZ0NDLElBQWhDLENBQXFDcUUsS0FBckMsRUFBNEN6RSxHQUE1QyxDQUFKLEVBQ0UsS0FBSzZFLEdBQUwsQ0FBUzdFLEdBQVQsRUFBY3lFLEtBQUssQ0FBQ3pFLEdBQUQsQ0FBbkI7QUFDSDs7QUFFRCxXQUFPLElBQVA7QUFDRDs7QUFFRCxPQUFLMEUsT0FBTCxDQUFhRCxLQUFLLENBQUNFLFdBQU4sRUFBYixJQUFvQzlELEdBQXBDO0FBQ0EsT0FBS2lFLE1BQUwsQ0FBWUwsS0FBWixJQUFxQjVELEdBQXJCO0FBQ0EsU0FBTyxJQUFQO0FBQ0QsQ0FiRDtBQWVBOzs7Ozs7Ozs7Ozs7OztBQVlBaEIsV0FBVyxDQUFDSSxTQUFaLENBQXNCOEUsS0FBdEIsR0FBOEIsVUFBU04sS0FBVCxFQUFnQjtBQUM1QyxTQUFPLEtBQUtDLE9BQUwsQ0FBYUQsS0FBSyxDQUFDRSxXQUFOLEVBQWIsQ0FBUDtBQUNBLFNBQU8sS0FBS0csTUFBTCxDQUFZTCxLQUFaLENBQVA7QUFDQSxTQUFPLElBQVA7QUFDRCxDQUpEO0FBTUE7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztBQW1CQTVFLFdBQVcsQ0FBQ0ksU0FBWixDQUFzQndFLEtBQXRCLEdBQThCLFVBQVNPLElBQVQsRUFBZW5FLEdBQWYsRUFBb0I7QUFDaEQ7QUFDQSxNQUFJbUUsSUFBSSxLQUFLLElBQVQsSUFBaUJiLFNBQVMsS0FBS2EsSUFBbkMsRUFBeUM7QUFDdkMsVUFBTSxJQUFJbkIsS0FBSixDQUFVLHlDQUFWLENBQU47QUFDRDs7QUFFRCxNQUFJLEtBQUtvQixLQUFULEVBQWdCO0FBQ2QsVUFBTSxJQUFJcEIsS0FBSixDQUNKLGlHQURJLENBQU47QUFHRDs7QUFFRCxNQUFJcEUsUUFBUSxDQUFDdUYsSUFBRCxDQUFaLEVBQW9CO0FBQ2xCLFNBQUssSUFBTWhGLEdBQVgsSUFBa0JnRixJQUFsQixFQUF3QjtBQUN0QixVQUFJOUUsTUFBTSxDQUFDRCxTQUFQLENBQWlCRSxjQUFqQixDQUFnQ0MsSUFBaEMsQ0FBcUM0RSxJQUFyQyxFQUEyQ2hGLEdBQTNDLENBQUosRUFDRSxLQUFLeUUsS0FBTCxDQUFXekUsR0FBWCxFQUFnQmdGLElBQUksQ0FBQ2hGLEdBQUQsQ0FBcEI7QUFDSDs7QUFFRCxXQUFPLElBQVA7QUFDRDs7QUFFRCxNQUFJa0YsS0FBSyxDQUFDQyxPQUFOLENBQWN0RSxHQUFkLENBQUosRUFBd0I7QUFDdEIsU0FBSyxJQUFNdUUsQ0FBWCxJQUFnQnZFLEdBQWhCLEVBQXFCO0FBQ25CLFVBQUlYLE1BQU0sQ0FBQ0QsU0FBUCxDQUFpQkUsY0FBakIsQ0FBZ0NDLElBQWhDLENBQXFDUyxHQUFyQyxFQUEwQ3VFLENBQTFDLENBQUosRUFDRSxLQUFLWCxLQUFMLENBQVdPLElBQVgsRUFBaUJuRSxHQUFHLENBQUN1RSxDQUFELENBQXBCO0FBQ0g7O0FBRUQsV0FBTyxJQUFQO0FBQ0QsR0E1QitDLENBOEJoRDs7O0FBQ0EsTUFBSXZFLEdBQUcsS0FBSyxJQUFSLElBQWdCc0QsU0FBUyxLQUFLdEQsR0FBbEMsRUFBdUM7QUFDckMsVUFBTSxJQUFJZ0QsS0FBSixDQUFVLHdDQUFWLENBQU47QUFDRDs7QUFFRCxNQUFJLE9BQU9oRCxHQUFQLEtBQWUsU0FBbkIsRUFBOEI7QUFDNUJBLElBQUFBLEdBQUcsR0FBR3dFLE1BQU0sQ0FBQ3hFLEdBQUQsQ0FBWjtBQUNEOztBQUVELE9BQUt5RSxZQUFMLEdBQW9CQyxNQUFwQixDQUEyQlAsSUFBM0IsRUFBaUNuRSxHQUFqQzs7QUFDQSxTQUFPLElBQVA7QUFDRCxDQXpDRDtBQTJDQTs7Ozs7Ozs7QUFNQWhCLFdBQVcsQ0FBQ0ksU0FBWixDQUFzQnVGLEtBQXRCLEdBQThCLFlBQVc7QUFDdkMsTUFBSSxLQUFLdkMsUUFBVCxFQUFtQjtBQUNqQixXQUFPLElBQVA7QUFDRDs7QUFFRCxPQUFLQSxRQUFMLEdBQWdCLElBQWhCO0FBQ0EsTUFBSSxLQUFLd0MsR0FBVCxFQUFjLEtBQUtBLEdBQUwsQ0FBU0QsS0FBVCxHQU55QixDQU1QOztBQUNoQyxNQUFJLEtBQUt6QyxHQUFULEVBQWMsS0FBS0EsR0FBTCxDQUFTeUMsS0FBVCxHQVB5QixDQU9QOztBQUNoQyxPQUFLbkYsWUFBTDtBQUNBLE9BQUtxRixJQUFMLENBQVUsT0FBVjtBQUNBLFNBQU8sSUFBUDtBQUNELENBWEQ7O0FBYUE3RixXQUFXLENBQUNJLFNBQVosQ0FBc0IwRixLQUF0QixHQUE4QixVQUFTQyxJQUFULEVBQWVDLElBQWYsRUFBcUIzRSxPQUFyQixFQUE4QjRFLGFBQTlCLEVBQTZDO0FBQ3pFLFVBQVE1RSxPQUFPLENBQUM2RSxJQUFoQjtBQUNFLFNBQUssT0FBTDtBQUNFLFdBQUtsQixHQUFMLENBQVMsZUFBVCxrQkFBbUNpQixhQUFhLFdBQUlGLElBQUosY0FBWUMsSUFBWixFQUFoRDtBQUNBOztBQUVGLFNBQUssTUFBTDtBQUNFLFdBQUtHLFFBQUwsR0FBZ0JKLElBQWhCO0FBQ0EsV0FBS0ssUUFBTCxHQUFnQkosSUFBaEI7QUFDQTs7QUFFRixTQUFLLFFBQUw7QUFBZTtBQUNiLFdBQUtoQixHQUFMLENBQVMsZUFBVCxtQkFBb0NlLElBQXBDO0FBQ0E7O0FBQ0Y7QUFDRTtBQWRKOztBQWlCQSxTQUFPLElBQVA7QUFDRCxDQW5CRDtBQXFCQTs7Ozs7Ozs7Ozs7O0FBV0EvRixXQUFXLENBQUNJLFNBQVosQ0FBc0JpRyxlQUF0QixHQUF3QyxVQUFTdEMsRUFBVCxFQUFhO0FBQ25EO0FBQ0EsTUFBSUEsRUFBRSxLQUFLTyxTQUFYLEVBQXNCUCxFQUFFLEdBQUcsSUFBTDtBQUN0QixPQUFLdUMsZ0JBQUwsR0FBd0J2QyxFQUF4QjtBQUNBLFNBQU8sSUFBUDtBQUNELENBTEQ7QUFPQTs7Ozs7Ozs7O0FBUUEvRCxXQUFXLENBQUNJLFNBQVosQ0FBc0JtRyxTQUF0QixHQUFrQyxVQUFTQyxDQUFULEVBQVk7QUFDNUMsT0FBS0MsYUFBTCxHQUFxQkQsQ0FBckI7QUFDQSxTQUFPLElBQVA7QUFDRCxDQUhEO0FBS0E7Ozs7Ozs7OztBQU9BeEcsV0FBVyxDQUFDSSxTQUFaLENBQXNCc0csZUFBdEIsR0FBd0MsVUFBU0YsQ0FBVCxFQUFZO0FBQ2xELE1BQUksT0FBT0EsQ0FBUCxLQUFhLFFBQWpCLEVBQTJCO0FBQ3pCLFVBQU0sSUFBSUcsU0FBSixDQUFjLGtCQUFkLENBQU47QUFDRDs7QUFFRCxPQUFLQyxnQkFBTCxHQUF3QkosQ0FBeEI7QUFDQSxTQUFPLElBQVA7QUFDRCxDQVBEO0FBU0E7Ozs7Ozs7Ozs7QUFTQXhHLFdBQVcsQ0FBQ0ksU0FBWixDQUFzQnlHLE1BQXRCLEdBQStCLFlBQVc7QUFDeEMsU0FBTztBQUNMNUMsSUFBQUEsTUFBTSxFQUFFLEtBQUtBLE1BRFI7QUFFTEMsSUFBQUEsR0FBRyxFQUFFLEtBQUtBLEdBRkw7QUFHTDRDLElBQUFBLElBQUksRUFBRSxLQUFLMUIsS0FITjtBQUlMMkIsSUFBQUEsT0FBTyxFQUFFLEtBQUtsQztBQUpULEdBQVA7QUFNRCxDQVBEO0FBU0E7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztBQXdDQTs7O0FBQ0E3RSxXQUFXLENBQUNJLFNBQVosQ0FBc0I0RyxJQUF0QixHQUE2QixVQUFTRixJQUFULEVBQWU7QUFDMUMsTUFBTUcsS0FBSyxHQUFHckgsUUFBUSxDQUFDa0gsSUFBRCxDQUF0QjtBQUNBLE1BQUlaLElBQUksR0FBRyxLQUFLckIsT0FBTCxDQUFhLGNBQWIsQ0FBWDs7QUFFQSxNQUFJLEtBQUtxQyxTQUFULEVBQW9CO0FBQ2xCLFVBQU0sSUFBSWxELEtBQUosQ0FDSiw4R0FESSxDQUFOO0FBR0Q7O0FBRUQsTUFBSWlELEtBQUssSUFBSSxDQUFDLEtBQUs3QixLQUFuQixFQUEwQjtBQUN4QixRQUFJQyxLQUFLLENBQUNDLE9BQU4sQ0FBY3dCLElBQWQsQ0FBSixFQUF5QjtBQUN2QixXQUFLMUIsS0FBTCxHQUFhLEVBQWI7QUFDRCxLQUZELE1BRU8sSUFBSSxDQUFDLEtBQUsrQixPQUFMLENBQWFMLElBQWIsQ0FBTCxFQUF5QjtBQUM5QixXQUFLMUIsS0FBTCxHQUFhLEVBQWI7QUFDRDtBQUNGLEdBTkQsTUFNTyxJQUFJMEIsSUFBSSxJQUFJLEtBQUsxQixLQUFiLElBQXNCLEtBQUsrQixPQUFMLENBQWEsS0FBSy9CLEtBQWxCLENBQTFCLEVBQW9EO0FBQ3pELFVBQU0sSUFBSXBCLEtBQUosQ0FBVSw4QkFBVixDQUFOO0FBQ0QsR0FsQnlDLENBb0IxQzs7O0FBQ0EsTUFBSWlELEtBQUssSUFBSXJILFFBQVEsQ0FBQyxLQUFLd0YsS0FBTixDQUFyQixFQUFtQztBQUNqQyxTQUFLLElBQU1qRixHQUFYLElBQWtCMkcsSUFBbEIsRUFBd0I7QUFDdEIsVUFBSXpHLE1BQU0sQ0FBQ0QsU0FBUCxDQUFpQkUsY0FBakIsQ0FBZ0NDLElBQWhDLENBQXFDdUcsSUFBckMsRUFBMkMzRyxHQUEzQyxDQUFKLEVBQ0UsS0FBS2lGLEtBQUwsQ0FBV2pGLEdBQVgsSUFBa0IyRyxJQUFJLENBQUMzRyxHQUFELENBQXRCO0FBQ0g7QUFDRixHQUxELE1BS08sSUFBSSxPQUFPMkcsSUFBUCxLQUFnQixRQUFwQixFQUE4QjtBQUNuQztBQUNBLFFBQUksQ0FBQ1osSUFBTCxFQUFXLEtBQUtBLElBQUwsQ0FBVSxNQUFWO0FBQ1hBLElBQUFBLElBQUksR0FBRyxLQUFLckIsT0FBTCxDQUFhLGNBQWIsQ0FBUDs7QUFDQSxRQUFJcUIsSUFBSSxLQUFLLG1DQUFiLEVBQWtEO0FBQ2hELFdBQUtkLEtBQUwsR0FBYSxLQUFLQSxLQUFMLGFBQWdCLEtBQUtBLEtBQXJCLGNBQThCMEIsSUFBOUIsSUFBdUNBLElBQXBEO0FBQ0QsS0FGRCxNQUVPO0FBQ0wsV0FBSzFCLEtBQUwsR0FBYSxDQUFDLEtBQUtBLEtBQUwsSUFBYyxFQUFmLElBQXFCMEIsSUFBbEM7QUFDRDtBQUNGLEdBVE0sTUFTQTtBQUNMLFNBQUsxQixLQUFMLEdBQWEwQixJQUFiO0FBQ0Q7O0FBRUQsTUFBSSxDQUFDRyxLQUFELElBQVUsS0FBS0UsT0FBTCxDQUFhTCxJQUFiLENBQWQsRUFBa0M7QUFDaEMsV0FBTyxJQUFQO0FBQ0QsR0F6Q3lDLENBMkMxQzs7O0FBQ0EsTUFBSSxDQUFDWixJQUFMLEVBQVcsS0FBS0EsSUFBTCxDQUFVLE1BQVY7QUFDWCxTQUFPLElBQVA7QUFDRCxDQTlDRDtBQWdEQTs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7QUE0QkFsRyxXQUFXLENBQUNJLFNBQVosQ0FBc0JnSCxTQUF0QixHQUFrQyxVQUFTQyxJQUFULEVBQWU7QUFDL0M7QUFDQSxPQUFLQyxLQUFMLEdBQWEsT0FBT0QsSUFBUCxLQUFnQixXQUFoQixHQUE4QixJQUE5QixHQUFxQ0EsSUFBbEQ7QUFDQSxTQUFPLElBQVA7QUFDRCxDQUpEO0FBTUE7Ozs7Ozs7QUFLQXJILFdBQVcsQ0FBQ0ksU0FBWixDQUFzQm1ILG9CQUF0QixHQUE2QyxZQUFXO0FBQ3RELE1BQU1DLEtBQUssR0FBRyxLQUFLQyxNQUFMLENBQVlDLElBQVosQ0FBaUIsR0FBakIsQ0FBZDs7QUFDQSxNQUFJRixLQUFKLEVBQVc7QUFDVCxTQUFLdEQsR0FBTCxJQUFZLENBQUMsS0FBS0EsR0FBTCxDQUFTbkIsUUFBVCxDQUFrQixHQUFsQixJQUF5QixHQUF6QixHQUErQixHQUFoQyxJQUF1Q3lFLEtBQW5EO0FBQ0Q7O0FBRUQsT0FBS0MsTUFBTCxDQUFZdkYsTUFBWixHQUFxQixDQUFyQixDQU5zRCxDQU05Qjs7QUFFeEIsTUFBSSxLQUFLb0YsS0FBVCxFQUFnQjtBQUNkLFFBQU1LLEtBQUssR0FBRyxLQUFLekQsR0FBTCxDQUFTMEQsT0FBVCxDQUFpQixHQUFqQixDQUFkOztBQUNBLFFBQUlELEtBQUssSUFBSSxDQUFiLEVBQWdCO0FBQ2QsVUFBTUUsUUFBUSxHQUFHLEtBQUszRCxHQUFMLENBQVM0RCxLQUFULENBQWVILEtBQUssR0FBRyxDQUF2QixFQUEwQkksS0FBMUIsQ0FBZ0MsR0FBaEMsQ0FBakI7O0FBQ0EsVUFBSSxPQUFPLEtBQUtULEtBQVosS0FBc0IsVUFBMUIsRUFBc0M7QUFDcENPLFFBQUFBLFFBQVEsQ0FBQ1IsSUFBVCxDQUFjLEtBQUtDLEtBQW5CO0FBQ0QsT0FGRCxNQUVPO0FBQ0xPLFFBQUFBLFFBQVEsQ0FBQ1IsSUFBVDtBQUNEOztBQUVELFdBQUtuRCxHQUFMLEdBQVcsS0FBS0EsR0FBTCxDQUFTNEQsS0FBVCxDQUFlLENBQWYsRUFBa0JILEtBQWxCLElBQTJCLEdBQTNCLEdBQWlDRSxRQUFRLENBQUNILElBQVQsQ0FBYyxHQUFkLENBQTVDO0FBQ0Q7QUFDRjtBQUNGLENBckJELEMsQ0F1QkE7OztBQUNBMUgsV0FBVyxDQUFDSSxTQUFaLENBQXNCNEgsa0JBQXRCLEdBQTJDLFlBQU07QUFDL0NuRyxFQUFBQSxPQUFPLENBQUNDLElBQVIsQ0FBYSxhQUFiO0FBQ0QsQ0FGRDtBQUlBOzs7Ozs7O0FBTUE5QixXQUFXLENBQUNJLFNBQVosQ0FBc0I2SCxhQUF0QixHQUFzQyxVQUFTQyxNQUFULEVBQWlCOUcsT0FBakIsRUFBMEIrRyxLQUExQixFQUFpQztBQUNyRSxNQUFJLEtBQUsvRSxRQUFULEVBQW1CO0FBQ2pCO0FBQ0Q7O0FBRUQsTUFBTVosR0FBRyxHQUFHLElBQUl3QixLQUFKLFdBQWFrRSxNQUFNLEdBQUc5RyxPQUF0QixpQkFBWjtBQUNBb0IsRUFBQUEsR0FBRyxDQUFDcEIsT0FBSixHQUFjQSxPQUFkO0FBQ0FvQixFQUFBQSxHQUFHLENBQUNNLElBQUosR0FBVyxjQUFYO0FBQ0FOLEVBQUFBLEdBQUcsQ0FBQzJGLEtBQUosR0FBWUEsS0FBWjtBQUNBLE9BQUs5RSxRQUFMLEdBQWdCLElBQWhCO0FBQ0EsT0FBS0MsYUFBTCxHQUFxQmQsR0FBckI7QUFDQSxPQUFLbUQsS0FBTDtBQUNBLE9BQUt5QyxRQUFMLENBQWM1RixHQUFkO0FBQ0QsQ0FiRDs7QUFlQXhDLFdBQVcsQ0FBQ0ksU0FBWixDQUFzQmlJLFlBQXRCLEdBQXFDLFlBQVc7QUFDOUMsTUFBTXpFLElBQUksR0FBRyxJQUFiLENBRDhDLENBRzlDOztBQUNBLE1BQUksS0FBS3RDLFFBQUwsSUFBaUIsQ0FBQyxLQUFLYixNQUEzQixFQUFtQztBQUNqQyxTQUFLQSxNQUFMLEdBQWM2SCxVQUFVLENBQUMsWUFBTTtBQUM3QjFFLE1BQUFBLElBQUksQ0FBQ3FFLGFBQUwsQ0FBbUIsYUFBbkIsRUFBa0NyRSxJQUFJLENBQUN0QyxRQUF2QyxFQUFpRCxPQUFqRDtBQUNELEtBRnVCLEVBRXJCLEtBQUtBLFFBRmdCLENBQXhCO0FBR0QsR0FSNkMsQ0FVOUM7OztBQUNBLE1BQUksS0FBS0MsZ0JBQUwsSUFBeUIsQ0FBQyxLQUFLYixxQkFBbkMsRUFBMEQ7QUFDeEQsU0FBS0EscUJBQUwsR0FBNkI0SCxVQUFVLENBQUMsWUFBTTtBQUM1QzFFLE1BQUFBLElBQUksQ0FBQ3FFLGFBQUwsQ0FDRSxzQkFERixFQUVFckUsSUFBSSxDQUFDckMsZ0JBRlAsRUFHRSxXQUhGO0FBS0QsS0FOc0MsRUFNcEMsS0FBS0EsZ0JBTitCLENBQXZDO0FBT0Q7QUFDRixDQXBCRCIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogTW9kdWxlIG9mIG1peGVkLWluIGZ1bmN0aW9ucyBzaGFyZWQgYmV0d2VlbiBub2RlIGFuZCBjbGllbnQgY29kZVxuICovXG5jb25zdCBpc09iamVjdCA9IHJlcXVpcmUoJy4vaXMtb2JqZWN0Jyk7XG5cbi8qKlxuICogRXhwb3NlIGBSZXF1ZXN0QmFzZWAuXG4gKi9cblxubW9kdWxlLmV4cG9ydHMgPSBSZXF1ZXN0QmFzZTtcblxuLyoqXG4gKiBJbml0aWFsaXplIGEgbmV3IGBSZXF1ZXN0QmFzZWAuXG4gKlxuICogQGFwaSBwdWJsaWNcbiAqL1xuXG5mdW5jdGlvbiBSZXF1ZXN0QmFzZShvYmopIHtcbiAgaWYgKG9iaikgcmV0dXJuIG1peGluKG9iaik7XG59XG5cbi8qKlxuICogTWl4aW4gdGhlIHByb3RvdHlwZSBwcm9wZXJ0aWVzLlxuICpcbiAqIEBwYXJhbSB7T2JqZWN0fSBvYmpcbiAqIEByZXR1cm4ge09iamVjdH1cbiAqIEBhcGkgcHJpdmF0ZVxuICovXG5cbmZ1bmN0aW9uIG1peGluKG9iaikge1xuICBmb3IgKGNvbnN0IGtleSBpbiBSZXF1ZXN0QmFzZS5wcm90b3R5cGUpIHtcbiAgICBpZiAoT2JqZWN0LnByb3RvdHlwZS5oYXNPd25Qcm9wZXJ0eS5jYWxsKFJlcXVlc3RCYXNlLnByb3RvdHlwZSwga2V5KSlcbiAgICAgIG9ialtrZXldID0gUmVxdWVzdEJhc2UucHJvdG90eXBlW2tleV07XG4gIH1cblxuICByZXR1cm4gb2JqO1xufVxuXG4vKipcbiAqIENsZWFyIHByZXZpb3VzIHRpbWVvdXQuXG4gKlxuICogQHJldHVybiB7UmVxdWVzdH0gZm9yIGNoYWluaW5nXG4gKiBAYXBpIHB1YmxpY1xuICovXG5cblJlcXVlc3RCYXNlLnByb3RvdHlwZS5jbGVhclRpbWVvdXQgPSBmdW5jdGlvbigpIHtcbiAgY2xlYXJUaW1lb3V0KHRoaXMuX3RpbWVyKTtcbiAgY2xlYXJUaW1lb3V0KHRoaXMuX3Jlc3BvbnNlVGltZW91dFRpbWVyKTtcbiAgY2xlYXJUaW1lb3V0KHRoaXMuX3VwbG9hZFRpbWVvdXRUaW1lcik7XG4gIGRlbGV0ZSB0aGlzLl90aW1lcjtcbiAgZGVsZXRlIHRoaXMuX3Jlc3BvbnNlVGltZW91dFRpbWVyO1xuICBkZWxldGUgdGhpcy5fdXBsb2FkVGltZW91dFRpbWVyO1xuICByZXR1cm4gdGhpcztcbn07XG5cbi8qKlxuICogT3ZlcnJpZGUgZGVmYXVsdCByZXNwb25zZSBib2R5IHBhcnNlclxuICpcbiAqIFRoaXMgZnVuY3Rpb24gd2lsbCBiZSBjYWxsZWQgdG8gY29udmVydCBpbmNvbWluZyBkYXRhIGludG8gcmVxdWVzdC5ib2R5XG4gKlxuICogQHBhcmFtIHtGdW5jdGlvbn1cbiAqIEBhcGkgcHVibGljXG4gKi9cblxuUmVxdWVzdEJhc2UucHJvdG90eXBlLnBhcnNlID0gZnVuY3Rpb24oZm4pIHtcbiAgdGhpcy5fcGFyc2VyID0gZm47XG4gIHJldHVybiB0aGlzO1xufTtcblxuLyoqXG4gKiBTZXQgZm9ybWF0IG9mIGJpbmFyeSByZXNwb25zZSBib2R5LlxuICogSW4gYnJvd3NlciB2YWxpZCBmb3JtYXRzIGFyZSAnYmxvYicgYW5kICdhcnJheWJ1ZmZlcicsXG4gKiB3aGljaCByZXR1cm4gQmxvYiBhbmQgQXJyYXlCdWZmZXIsIHJlc3BlY3RpdmVseS5cbiAqXG4gKiBJbiBOb2RlIGFsbCB2YWx1ZXMgcmVzdWx0IGluIEJ1ZmZlci5cbiAqXG4gKiBFeGFtcGxlczpcbiAqXG4gKiAgICAgIHJlcS5nZXQoJy8nKVxuICogICAgICAgIC5yZXNwb25zZVR5cGUoJ2Jsb2InKVxuICogICAgICAgIC5lbmQoY2FsbGJhY2spO1xuICpcbiAqIEBwYXJhbSB7U3RyaW5nfSB2YWxcbiAqIEByZXR1cm4ge1JlcXVlc3R9IGZvciBjaGFpbmluZ1xuICogQGFwaSBwdWJsaWNcbiAqL1xuXG5SZXF1ZXN0QmFzZS5wcm90b3R5cGUucmVzcG9uc2VUeXBlID0gZnVuY3Rpb24odmFsKSB7XG4gIHRoaXMuX3Jlc3BvbnNlVHlwZSA9IHZhbDtcbiAgcmV0dXJuIHRoaXM7XG59O1xuXG4vKipcbiAqIE92ZXJyaWRlIGRlZmF1bHQgcmVxdWVzdCBib2R5IHNlcmlhbGl6ZXJcbiAqXG4gKiBUaGlzIGZ1bmN0aW9uIHdpbGwgYmUgY2FsbGVkIHRvIGNvbnZlcnQgZGF0YSBzZXQgdmlhIC5zZW5kIG9yIC5hdHRhY2ggaW50byBwYXlsb2FkIHRvIHNlbmRcbiAqXG4gKiBAcGFyYW0ge0Z1bmN0aW9ufVxuICogQGFwaSBwdWJsaWNcbiAqL1xuXG5SZXF1ZXN0QmFzZS5wcm90b3R5cGUuc2VyaWFsaXplID0gZnVuY3Rpb24oZm4pIHtcbiAgdGhpcy5fc2VyaWFsaXplciA9IGZuO1xuICByZXR1cm4gdGhpcztcbn07XG5cbi8qKlxuICogU2V0IHRpbWVvdXRzLlxuICpcbiAqIC0gcmVzcG9uc2UgdGltZW91dCBpcyB0aW1lIGJldHdlZW4gc2VuZGluZyByZXF1ZXN0IGFuZCByZWNlaXZpbmcgdGhlIGZpcnN0IGJ5dGUgb2YgdGhlIHJlc3BvbnNlLiBJbmNsdWRlcyBETlMgYW5kIGNvbm5lY3Rpb24gdGltZS5cbiAqIC0gZGVhZGxpbmUgaXMgdGhlIHRpbWUgZnJvbSBzdGFydCBvZiB0aGUgcmVxdWVzdCB0byByZWNlaXZpbmcgcmVzcG9uc2UgYm9keSBpbiBmdWxsLiBJZiB0aGUgZGVhZGxpbmUgaXMgdG9vIHNob3J0IGxhcmdlIGZpbGVzIG1heSBub3QgbG9hZCBhdCBhbGwgb24gc2xvdyBjb25uZWN0aW9ucy5cbiAqIC0gdXBsb2FkIGlzIHRoZSB0aW1lICBzaW5jZSBsYXN0IGJpdCBvZiBkYXRhIHdhcyBzZW50IG9yIHJlY2VpdmVkLiBUaGlzIHRpbWVvdXQgd29ya3Mgb25seSBpZiBkZWFkbGluZSB0aW1lb3V0IGlzIG9mZlxuICpcbiAqIFZhbHVlIG9mIDAgb3IgZmFsc2UgbWVhbnMgbm8gdGltZW91dC5cbiAqXG4gKiBAcGFyYW0ge051bWJlcnxPYmplY3R9IG1zIG9yIHtyZXNwb25zZSwgZGVhZGxpbmV9XG4gKiBAcmV0dXJuIHtSZXF1ZXN0fSBmb3IgY2hhaW5pbmdcbiAqIEBhcGkgcHVibGljXG4gKi9cblxuUmVxdWVzdEJhc2UucHJvdG90eXBlLnRpbWVvdXQgPSBmdW5jdGlvbihvcHRpb25zKSB7XG4gIGlmICghb3B0aW9ucyB8fCB0eXBlb2Ygb3B0aW9ucyAhPT0gJ29iamVjdCcpIHtcbiAgICB0aGlzLl90aW1lb3V0ID0gb3B0aW9ucztcbiAgICB0aGlzLl9yZXNwb25zZVRpbWVvdXQgPSAwO1xuICAgIHRoaXMuX3VwbG9hZFRpbWVvdXQgPSAwO1xuICAgIHJldHVybiB0aGlzO1xuICB9XG5cbiAgZm9yIChjb25zdCBvcHRpb24gaW4gb3B0aW9ucykge1xuICAgIGlmIChPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwob3B0aW9ucywgb3B0aW9uKSkge1xuICAgICAgc3dpdGNoIChvcHRpb24pIHtcbiAgICAgICAgY2FzZSAnZGVhZGxpbmUnOlxuICAgICAgICAgIHRoaXMuX3RpbWVvdXQgPSBvcHRpb25zLmRlYWRsaW5lO1xuICAgICAgICAgIGJyZWFrO1xuICAgICAgICBjYXNlICdyZXNwb25zZSc6XG4gICAgICAgICAgdGhpcy5fcmVzcG9uc2VUaW1lb3V0ID0gb3B0aW9ucy5yZXNwb25zZTtcbiAgICAgICAgICBicmVhaztcbiAgICAgICAgY2FzZSAndXBsb2FkJzpcbiAgICAgICAgICB0aGlzLl91cGxvYWRUaW1lb3V0ID0gb3B0aW9ucy51cGxvYWQ7XG4gICAgICAgICAgYnJlYWs7XG4gICAgICAgIGRlZmF1bHQ6XG4gICAgICAgICAgY29uc29sZS53YXJuKCdVbmtub3duIHRpbWVvdXQgb3B0aW9uJywgb3B0aW9uKTtcbiAgICAgIH1cbiAgICB9XG4gIH1cblxuICByZXR1cm4gdGhpcztcbn07XG5cbi8qKlxuICogU2V0IG51bWJlciBvZiByZXRyeSBhdHRlbXB0cyBvbiBlcnJvci5cbiAqXG4gKiBGYWlsZWQgcmVxdWVzdHMgd2lsbCBiZSByZXRyaWVkICdjb3VudCcgdGltZXMgaWYgdGltZW91dCBvciBlcnIuY29kZSA+PSA1MDAuXG4gKlxuICogQHBhcmFtIHtOdW1iZXJ9IGNvdW50XG4gKiBAcGFyYW0ge0Z1bmN0aW9ufSBbZm5dXG4gKiBAcmV0dXJuIHtSZXF1ZXN0fSBmb3IgY2hhaW5pbmdcbiAqIEBhcGkgcHVibGljXG4gKi9cblxuUmVxdWVzdEJhc2UucHJvdG90eXBlLnJldHJ5ID0gZnVuY3Rpb24oY291bnQsIGZuKSB7XG4gIC8vIERlZmF1bHQgdG8gMSBpZiBubyBjb3VudCBwYXNzZWQgb3IgdHJ1ZVxuICBpZiAoYXJndW1lbnRzLmxlbmd0aCA9PT0gMCB8fCBjb3VudCA9PT0gdHJ1ZSkgY291bnQgPSAxO1xuICBpZiAoY291bnQgPD0gMCkgY291bnQgPSAwO1xuICB0aGlzLl9tYXhSZXRyaWVzID0gY291bnQ7XG4gIHRoaXMuX3JldHJpZXMgPSAwO1xuICB0aGlzLl9yZXRyeUNhbGxiYWNrID0gZm47XG4gIHJldHVybiB0aGlzO1xufTtcblxuY29uc3QgRVJST1JfQ09ERVMgPSBbJ0VDT05OUkVTRVQnLCAnRVRJTUVET1VUJywgJ0VBRERSSU5GTycsICdFU09DS0VUVElNRURPVVQnXTtcblxuLyoqXG4gKiBEZXRlcm1pbmUgaWYgYSByZXF1ZXN0IHNob3VsZCBiZSByZXRyaWVkLlxuICogKEJvcnJvd2VkIGZyb20gc2VnbWVudGlvL3N1cGVyYWdlbnQtcmV0cnkpXG4gKlxuICogQHBhcmFtIHtFcnJvcn0gZXJyIGFuIGVycm9yXG4gKiBAcGFyYW0ge1Jlc3BvbnNlfSBbcmVzXSByZXNwb25zZVxuICogQHJldHVybnMge0Jvb2xlYW59IGlmIHNlZ21lbnQgc2hvdWxkIGJlIHJldHJpZWRcbiAqL1xuUmVxdWVzdEJhc2UucHJvdG90eXBlLl9zaG91bGRSZXRyeSA9IGZ1bmN0aW9uKGVyciwgcmVzKSB7XG4gIGlmICghdGhpcy5fbWF4UmV0cmllcyB8fCB0aGlzLl9yZXRyaWVzKysgPj0gdGhpcy5fbWF4UmV0cmllcykge1xuICAgIHJldHVybiBmYWxzZTtcbiAgfVxuXG4gIGlmICh0aGlzLl9yZXRyeUNhbGxiYWNrKSB7XG4gICAgdHJ5IHtcbiAgICAgIGNvbnN0IG92ZXJyaWRlID0gdGhpcy5fcmV0cnlDYWxsYmFjayhlcnIsIHJlcyk7XG4gICAgICBpZiAob3ZlcnJpZGUgPT09IHRydWUpIHJldHVybiB0cnVlO1xuICAgICAgaWYgKG92ZXJyaWRlID09PSBmYWxzZSkgcmV0dXJuIGZhbHNlO1xuICAgICAgLy8gdW5kZWZpbmVkIGZhbGxzIGJhY2sgdG8gZGVmYXVsdHNcbiAgICB9IGNhdGNoIChlcnJfKSB7XG4gICAgICBjb25zb2xlLmVycm9yKGVycl8pO1xuICAgIH1cbiAgfVxuXG4gIGlmIChyZXMgJiYgcmVzLnN0YXR1cyAmJiByZXMuc3RhdHVzID49IDUwMCAmJiByZXMuc3RhdHVzICE9PSA1MDEpIHJldHVybiB0cnVlO1xuICBpZiAoZXJyKSB7XG4gICAgaWYgKGVyci5jb2RlICYmIEVSUk9SX0NPREVTLmluY2x1ZGVzKGVyci5jb2RlKSkgcmV0dXJuIHRydWU7XG4gICAgLy8gU3VwZXJhZ2VudCB0aW1lb3V0XG4gICAgaWYgKGVyci50aW1lb3V0ICYmIGVyci5jb2RlID09PSAnRUNPTk5BQk9SVEVEJykgcmV0dXJuIHRydWU7XG4gICAgaWYgKGVyci5jcm9zc0RvbWFpbikgcmV0dXJuIHRydWU7XG4gIH1cblxuICByZXR1cm4gZmFsc2U7XG59O1xuXG4vKipcbiAqIFJldHJ5IHJlcXVlc3RcbiAqXG4gKiBAcmV0dXJuIHtSZXF1ZXN0fSBmb3IgY2hhaW5pbmdcbiAqIEBhcGkgcHJpdmF0ZVxuICovXG5cblJlcXVlc3RCYXNlLnByb3RvdHlwZS5fcmV0cnkgPSBmdW5jdGlvbigpIHtcbiAgdGhpcy5jbGVhclRpbWVvdXQoKTtcblxuICAvLyBub2RlXG4gIGlmICh0aGlzLnJlcSkge1xuICAgIHRoaXMucmVxID0gbnVsbDtcbiAgICB0aGlzLnJlcSA9IHRoaXMucmVxdWVzdCgpO1xuICB9XG5cbiAgdGhpcy5fYWJvcnRlZCA9IGZhbHNlO1xuICB0aGlzLnRpbWVkb3V0ID0gZmFsc2U7XG4gIHRoaXMudGltZWRvdXRFcnJvciA9IG51bGw7XG5cbiAgcmV0dXJuIHRoaXMuX2VuZCgpO1xufTtcblxuLyoqXG4gKiBQcm9taXNlIHN1cHBvcnRcbiAqXG4gKiBAcGFyYW0ge0Z1bmN0aW9ufSByZXNvbHZlXG4gKiBAcGFyYW0ge0Z1bmN0aW9ufSBbcmVqZWN0XVxuICogQHJldHVybiB7UmVxdWVzdH1cbiAqL1xuXG5SZXF1ZXN0QmFzZS5wcm90b3R5cGUudGhlbiA9IGZ1bmN0aW9uKHJlc29sdmUsIHJlamVjdCkge1xuICBpZiAoIXRoaXMuX2Z1bGxmaWxsZWRQcm9taXNlKSB7XG4gICAgY29uc3Qgc2VsZiA9IHRoaXM7XG4gICAgaWYgKHRoaXMuX2VuZENhbGxlZCkge1xuICAgICAgY29uc29sZS53YXJuKFxuICAgICAgICAnV2FybmluZzogc3VwZXJhZ2VudCByZXF1ZXN0IHdhcyBzZW50IHR3aWNlLCBiZWNhdXNlIGJvdGggLmVuZCgpIGFuZCAudGhlbigpIHdlcmUgY2FsbGVkLiBOZXZlciBjYWxsIC5lbmQoKSBpZiB5b3UgdXNlIHByb21pc2VzJ1xuICAgICAgKTtcbiAgICB9XG5cbiAgICB0aGlzLl9mdWxsZmlsbGVkUHJvbWlzZSA9IG5ldyBQcm9taXNlKChyZXNvbHZlLCByZWplY3QpID0+IHtcbiAgICAgIHNlbGYub24oJ2Fib3J0JywgKCkgPT4ge1xuICAgICAgICBpZiAodGhpcy5fbWF4UmV0cmllcyAmJiB0aGlzLl9tYXhSZXRyaWVzID4gdGhpcy5fcmV0cmllcykge1xuICAgICAgICAgIHJldHVybjtcbiAgICAgICAgfVxuXG4gICAgICAgIGlmICh0aGlzLnRpbWVkb3V0ICYmIHRoaXMudGltZWRvdXRFcnJvcikge1xuICAgICAgICAgIHJlamVjdCh0aGlzLnRpbWVkb3V0RXJyb3IpO1xuICAgICAgICAgIHJldHVybjtcbiAgICAgICAgfVxuXG4gICAgICAgIGNvbnN0IGVyciA9IG5ldyBFcnJvcignQWJvcnRlZCcpO1xuICAgICAgICBlcnIuY29kZSA9ICdBQk9SVEVEJztcbiAgICAgICAgZXJyLnN0YXR1cyA9IHRoaXMuc3RhdHVzO1xuICAgICAgICBlcnIubWV0aG9kID0gdGhpcy5tZXRob2Q7XG4gICAgICAgIGVyci51cmwgPSB0aGlzLnVybDtcbiAgICAgICAgcmVqZWN0KGVycik7XG4gICAgICB9KTtcbiAgICAgIHNlbGYuZW5kKChlcnIsIHJlcykgPT4ge1xuICAgICAgICBpZiAoZXJyKSByZWplY3QoZXJyKTtcbiAgICAgICAgZWxzZSByZXNvbHZlKHJlcyk7XG4gICAgICB9KTtcbiAgICB9KTtcbiAgfVxuXG4gIHJldHVybiB0aGlzLl9mdWxsZmlsbGVkUHJvbWlzZS50aGVuKHJlc29sdmUsIHJlamVjdCk7XG59O1xuXG5SZXF1ZXN0QmFzZS5wcm90b3R5cGUuY2F0Y2ggPSBmdW5jdGlvbihjYikge1xuICByZXR1cm4gdGhpcy50aGVuKHVuZGVmaW5lZCwgY2IpO1xufTtcblxuLyoqXG4gKiBBbGxvdyBmb3IgZXh0ZW5zaW9uXG4gKi9cblxuUmVxdWVzdEJhc2UucHJvdG90eXBlLnVzZSA9IGZ1bmN0aW9uKGZuKSB7XG4gIGZuKHRoaXMpO1xuICByZXR1cm4gdGhpcztcbn07XG5cblJlcXVlc3RCYXNlLnByb3RvdHlwZS5vayA9IGZ1bmN0aW9uKGNiKSB7XG4gIGlmICh0eXBlb2YgY2IgIT09ICdmdW5jdGlvbicpIHRocm93IG5ldyBFcnJvcignQ2FsbGJhY2sgcmVxdWlyZWQnKTtcbiAgdGhpcy5fb2tDYWxsYmFjayA9IGNiO1xuICByZXR1cm4gdGhpcztcbn07XG5cblJlcXVlc3RCYXNlLnByb3RvdHlwZS5faXNSZXNwb25zZU9LID0gZnVuY3Rpb24ocmVzKSB7XG4gIGlmICghcmVzKSB7XG4gICAgcmV0dXJuIGZhbHNlO1xuICB9XG5cbiAgaWYgKHRoaXMuX29rQ2FsbGJhY2spIHtcbiAgICByZXR1cm4gdGhpcy5fb2tDYWxsYmFjayhyZXMpO1xuICB9XG5cbiAgcmV0dXJuIHJlcy5zdGF0dXMgPj0gMjAwICYmIHJlcy5zdGF0dXMgPCAzMDA7XG59O1xuXG4vKipcbiAqIEdldCByZXF1ZXN0IGhlYWRlciBgZmllbGRgLlxuICogQ2FzZS1pbnNlbnNpdGl2ZS5cbiAqXG4gKiBAcGFyYW0ge1N0cmluZ30gZmllbGRcbiAqIEByZXR1cm4ge1N0cmluZ31cbiAqIEBhcGkgcHVibGljXG4gKi9cblxuUmVxdWVzdEJhc2UucHJvdG90eXBlLmdldCA9IGZ1bmN0aW9uKGZpZWxkKSB7XG4gIHJldHVybiB0aGlzLl9oZWFkZXJbZmllbGQudG9Mb3dlckNhc2UoKV07XG59O1xuXG4vKipcbiAqIEdldCBjYXNlLWluc2Vuc2l0aXZlIGhlYWRlciBgZmllbGRgIHZhbHVlLlxuICogVGhpcyBpcyBhIGRlcHJlY2F0ZWQgaW50ZXJuYWwgQVBJLiBVc2UgYC5nZXQoZmllbGQpYCBpbnN0ZWFkLlxuICpcbiAqIChnZXRIZWFkZXIgaXMgbm8gbG9uZ2VyIHVzZWQgaW50ZXJuYWxseSBieSB0aGUgc3VwZXJhZ2VudCBjb2RlIGJhc2UpXG4gKlxuICogQHBhcmFtIHtTdHJpbmd9IGZpZWxkXG4gKiBAcmV0dXJuIHtTdHJpbmd9XG4gKiBAYXBpIHByaXZhdGVcbiAqIEBkZXByZWNhdGVkXG4gKi9cblxuUmVxdWVzdEJhc2UucHJvdG90eXBlLmdldEhlYWRlciA9IFJlcXVlc3RCYXNlLnByb3RvdHlwZS5nZXQ7XG5cbi8qKlxuICogU2V0IGhlYWRlciBgZmllbGRgIHRvIGB2YWxgLCBvciBtdWx0aXBsZSBmaWVsZHMgd2l0aCBvbmUgb2JqZWN0LlxuICogQ2FzZS1pbnNlbnNpdGl2ZS5cbiAqXG4gKiBFeGFtcGxlczpcbiAqXG4gKiAgICAgIHJlcS5nZXQoJy8nKVxuICogICAgICAgIC5zZXQoJ0FjY2VwdCcsICdhcHBsaWNhdGlvbi9qc29uJylcbiAqICAgICAgICAuc2V0KCdYLUFQSS1LZXknLCAnZm9vYmFyJylcbiAqICAgICAgICAuZW5kKGNhbGxiYWNrKTtcbiAqXG4gKiAgICAgIHJlcS5nZXQoJy8nKVxuICogICAgICAgIC5zZXQoeyBBY2NlcHQ6ICdhcHBsaWNhdGlvbi9qc29uJywgJ1gtQVBJLUtleSc6ICdmb29iYXInIH0pXG4gKiAgICAgICAgLmVuZChjYWxsYmFjayk7XG4gKlxuICogQHBhcmFtIHtTdHJpbmd8T2JqZWN0fSBmaWVsZFxuICogQHBhcmFtIHtTdHJpbmd9IHZhbFxuICogQHJldHVybiB7UmVxdWVzdH0gZm9yIGNoYWluaW5nXG4gKiBAYXBpIHB1YmxpY1xuICovXG5cblJlcXVlc3RCYXNlLnByb3RvdHlwZS5zZXQgPSBmdW5jdGlvbihmaWVsZCwgdmFsKSB7XG4gIGlmIChpc09iamVjdChmaWVsZCkpIHtcbiAgICBmb3IgKGNvbnN0IGtleSBpbiBmaWVsZCkge1xuICAgICAgaWYgKE9iamVjdC5wcm90b3R5cGUuaGFzT3duUHJvcGVydHkuY2FsbChmaWVsZCwga2V5KSlcbiAgICAgICAgdGhpcy5zZXQoa2V5LCBmaWVsZFtrZXldKTtcbiAgICB9XG5cbiAgICByZXR1cm4gdGhpcztcbiAgfVxuXG4gIHRoaXMuX2hlYWRlcltmaWVsZC50b0xvd2VyQ2FzZSgpXSA9IHZhbDtcbiAgdGhpcy5oZWFkZXJbZmllbGRdID0gdmFsO1xuICByZXR1cm4gdGhpcztcbn07XG5cbi8qKlxuICogUmVtb3ZlIGhlYWRlciBgZmllbGRgLlxuICogQ2FzZS1pbnNlbnNpdGl2ZS5cbiAqXG4gKiBFeGFtcGxlOlxuICpcbiAqICAgICAgcmVxLmdldCgnLycpXG4gKiAgICAgICAgLnVuc2V0KCdVc2VyLUFnZW50JylcbiAqICAgICAgICAuZW5kKGNhbGxiYWNrKTtcbiAqXG4gKiBAcGFyYW0ge1N0cmluZ30gZmllbGQgZmllbGQgbmFtZVxuICovXG5SZXF1ZXN0QmFzZS5wcm90b3R5cGUudW5zZXQgPSBmdW5jdGlvbihmaWVsZCkge1xuICBkZWxldGUgdGhpcy5faGVhZGVyW2ZpZWxkLnRvTG93ZXJDYXNlKCldO1xuICBkZWxldGUgdGhpcy5oZWFkZXJbZmllbGRdO1xuICByZXR1cm4gdGhpcztcbn07XG5cbi8qKlxuICogV3JpdGUgdGhlIGZpZWxkIGBuYW1lYCBhbmQgYHZhbGAsIG9yIG11bHRpcGxlIGZpZWxkcyB3aXRoIG9uZSBvYmplY3RcbiAqIGZvciBcIm11bHRpcGFydC9mb3JtLWRhdGFcIiByZXF1ZXN0IGJvZGllcy5cbiAqXG4gKiBgYGAganNcbiAqIHJlcXVlc3QucG9zdCgnL3VwbG9hZCcpXG4gKiAgIC5maWVsZCgnZm9vJywgJ2JhcicpXG4gKiAgIC5lbmQoY2FsbGJhY2spO1xuICpcbiAqIHJlcXVlc3QucG9zdCgnL3VwbG9hZCcpXG4gKiAgIC5maWVsZCh7IGZvbzogJ2JhcicsIGJhejogJ3F1eCcgfSlcbiAqICAgLmVuZChjYWxsYmFjayk7XG4gKiBgYGBcbiAqXG4gKiBAcGFyYW0ge1N0cmluZ3xPYmplY3R9IG5hbWUgbmFtZSBvZiBmaWVsZFxuICogQHBhcmFtIHtTdHJpbmd8QmxvYnxGaWxlfEJ1ZmZlcnxmcy5SZWFkU3RyZWFtfSB2YWwgdmFsdWUgb2YgZmllbGRcbiAqIEByZXR1cm4ge1JlcXVlc3R9IGZvciBjaGFpbmluZ1xuICogQGFwaSBwdWJsaWNcbiAqL1xuUmVxdWVzdEJhc2UucHJvdG90eXBlLmZpZWxkID0gZnVuY3Rpb24obmFtZSwgdmFsKSB7XG4gIC8vIG5hbWUgc2hvdWxkIGJlIGVpdGhlciBhIHN0cmluZyBvciBhbiBvYmplY3QuXG4gIGlmIChuYW1lID09PSBudWxsIHx8IHVuZGVmaW5lZCA9PT0gbmFtZSkge1xuICAgIHRocm93IG5ldyBFcnJvcignLmZpZWxkKG5hbWUsIHZhbCkgbmFtZSBjYW4gbm90IGJlIGVtcHR5Jyk7XG4gIH1cblxuICBpZiAodGhpcy5fZGF0YSkge1xuICAgIHRocm93IG5ldyBFcnJvcihcbiAgICAgIFwiLmZpZWxkKCkgY2FuJ3QgYmUgdXNlZCBpZiAuc2VuZCgpIGlzIHVzZWQuIFBsZWFzZSB1c2Ugb25seSAuc2VuZCgpIG9yIG9ubHkgLmZpZWxkKCkgJiAuYXR0YWNoKClcIlxuICAgICk7XG4gIH1cblxuICBpZiAoaXNPYmplY3QobmFtZSkpIHtcbiAgICBmb3IgKGNvbnN0IGtleSBpbiBuYW1lKSB7XG4gICAgICBpZiAoT2JqZWN0LnByb3RvdHlwZS5oYXNPd25Qcm9wZXJ0eS5jYWxsKG5hbWUsIGtleSkpXG4gICAgICAgIHRoaXMuZmllbGQoa2V5LCBuYW1lW2tleV0pO1xuICAgIH1cblxuICAgIHJldHVybiB0aGlzO1xuICB9XG5cbiAgaWYgKEFycmF5LmlzQXJyYXkodmFsKSkge1xuICAgIGZvciAoY29uc3QgaSBpbiB2YWwpIHtcbiAgICAgIGlmIChPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwodmFsLCBpKSlcbiAgICAgICAgdGhpcy5maWVsZChuYW1lLCB2YWxbaV0pO1xuICAgIH1cblxuICAgIHJldHVybiB0aGlzO1xuICB9XG5cbiAgLy8gdmFsIHNob3VsZCBiZSBkZWZpbmVkIG5vd1xuICBpZiAodmFsID09PSBudWxsIHx8IHVuZGVmaW5lZCA9PT0gdmFsKSB7XG4gICAgdGhyb3cgbmV3IEVycm9yKCcuZmllbGQobmFtZSwgdmFsKSB2YWwgY2FuIG5vdCBiZSBlbXB0eScpO1xuICB9XG5cbiAgaWYgKHR5cGVvZiB2YWwgPT09ICdib29sZWFuJykge1xuICAgIHZhbCA9IFN0cmluZyh2YWwpO1xuICB9XG5cbiAgdGhpcy5fZ2V0Rm9ybURhdGEoKS5hcHBlbmQobmFtZSwgdmFsKTtcbiAgcmV0dXJuIHRoaXM7XG59O1xuXG4vKipcbiAqIEFib3J0IHRoZSByZXF1ZXN0LCBhbmQgY2xlYXIgcG90ZW50aWFsIHRpbWVvdXQuXG4gKlxuICogQHJldHVybiB7UmVxdWVzdH0gcmVxdWVzdFxuICogQGFwaSBwdWJsaWNcbiAqL1xuUmVxdWVzdEJhc2UucHJvdG90eXBlLmFib3J0ID0gZnVuY3Rpb24oKSB7XG4gIGlmICh0aGlzLl9hYm9ydGVkKSB7XG4gICAgcmV0dXJuIHRoaXM7XG4gIH1cblxuICB0aGlzLl9hYm9ydGVkID0gdHJ1ZTtcbiAgaWYgKHRoaXMueGhyKSB0aGlzLnhoci5hYm9ydCgpOyAvLyBicm93c2VyXG4gIGlmICh0aGlzLnJlcSkgdGhpcy5yZXEuYWJvcnQoKTsgLy8gbm9kZVxuICB0aGlzLmNsZWFyVGltZW91dCgpO1xuICB0aGlzLmVtaXQoJ2Fib3J0Jyk7XG4gIHJldHVybiB0aGlzO1xufTtcblxuUmVxdWVzdEJhc2UucHJvdG90eXBlLl9hdXRoID0gZnVuY3Rpb24odXNlciwgcGFzcywgb3B0aW9ucywgYmFzZTY0RW5jb2Rlcikge1xuICBzd2l0Y2ggKG9wdGlvbnMudHlwZSkge1xuICAgIGNhc2UgJ2Jhc2ljJzpcbiAgICAgIHRoaXMuc2V0KCdBdXRob3JpemF0aW9uJywgYEJhc2ljICR7YmFzZTY0RW5jb2RlcihgJHt1c2VyfToke3Bhc3N9YCl9YCk7XG4gICAgICBicmVhaztcblxuICAgIGNhc2UgJ2F1dG8nOlxuICAgICAgdGhpcy51c2VybmFtZSA9IHVzZXI7XG4gICAgICB0aGlzLnBhc3N3b3JkID0gcGFzcztcbiAgICAgIGJyZWFrO1xuXG4gICAgY2FzZSAnYmVhcmVyJzogLy8gdXNhZ2Ugd291bGQgYmUgLmF1dGgoYWNjZXNzVG9rZW4sIHsgdHlwZTogJ2JlYXJlcicgfSlcbiAgICAgIHRoaXMuc2V0KCdBdXRob3JpemF0aW9uJywgYEJlYXJlciAke3VzZXJ9YCk7XG4gICAgICBicmVhaztcbiAgICBkZWZhdWx0OlxuICAgICAgYnJlYWs7XG4gIH1cblxuICByZXR1cm4gdGhpcztcbn07XG5cbi8qKlxuICogRW5hYmxlIHRyYW5zbWlzc2lvbiBvZiBjb29raWVzIHdpdGggeC1kb21haW4gcmVxdWVzdHMuXG4gKlxuICogTm90ZSB0aGF0IGZvciB0aGlzIHRvIHdvcmsgdGhlIG9yaWdpbiBtdXN0IG5vdCBiZVxuICogdXNpbmcgXCJBY2Nlc3MtQ29udHJvbC1BbGxvdy1PcmlnaW5cIiB3aXRoIGEgd2lsZGNhcmQsXG4gKiBhbmQgYWxzbyBtdXN0IHNldCBcIkFjY2Vzcy1Db250cm9sLUFsbG93LUNyZWRlbnRpYWxzXCJcbiAqIHRvIFwidHJ1ZVwiLlxuICpcbiAqIEBhcGkgcHVibGljXG4gKi9cblxuUmVxdWVzdEJhc2UucHJvdG90eXBlLndpdGhDcmVkZW50aWFscyA9IGZ1bmN0aW9uKG9uKSB7XG4gIC8vIFRoaXMgaXMgYnJvd3Nlci1vbmx5IGZ1bmN0aW9uYWxpdHkuIE5vZGUgc2lkZSBpcyBuby1vcC5cbiAgaWYgKG9uID09PSB1bmRlZmluZWQpIG9uID0gdHJ1ZTtcbiAgdGhpcy5fd2l0aENyZWRlbnRpYWxzID0gb247XG4gIHJldHVybiB0aGlzO1xufTtcblxuLyoqXG4gKiBTZXQgdGhlIG1heCByZWRpcmVjdHMgdG8gYG5gLiBEb2VzIG5vdGhpbmcgaW4gYnJvd3NlciBYSFIgaW1wbGVtZW50YXRpb24uXG4gKlxuICogQHBhcmFtIHtOdW1iZXJ9IG5cbiAqIEByZXR1cm4ge1JlcXVlc3R9IGZvciBjaGFpbmluZ1xuICogQGFwaSBwdWJsaWNcbiAqL1xuXG5SZXF1ZXN0QmFzZS5wcm90b3R5cGUucmVkaXJlY3RzID0gZnVuY3Rpb24obikge1xuICB0aGlzLl9tYXhSZWRpcmVjdHMgPSBuO1xuICByZXR1cm4gdGhpcztcbn07XG5cbi8qKlxuICogTWF4aW11bSBzaXplIG9mIGJ1ZmZlcmVkIHJlc3BvbnNlIGJvZHksIGluIGJ5dGVzLiBDb3VudHMgdW5jb21wcmVzc2VkIHNpemUuXG4gKiBEZWZhdWx0IDIwME1CLlxuICpcbiAqIEBwYXJhbSB7TnVtYmVyfSBuIG51bWJlciBvZiBieXRlc1xuICogQHJldHVybiB7UmVxdWVzdH0gZm9yIGNoYWluaW5nXG4gKi9cblJlcXVlc3RCYXNlLnByb3RvdHlwZS5tYXhSZXNwb25zZVNpemUgPSBmdW5jdGlvbihuKSB7XG4gIGlmICh0eXBlb2YgbiAhPT0gJ251bWJlcicpIHtcbiAgICB0aHJvdyBuZXcgVHlwZUVycm9yKCdJbnZhbGlkIGFyZ3VtZW50Jyk7XG4gIH1cblxuICB0aGlzLl9tYXhSZXNwb25zZVNpemUgPSBuO1xuICByZXR1cm4gdGhpcztcbn07XG5cbi8qKlxuICogQ29udmVydCB0byBhIHBsYWluIGphdmFzY3JpcHQgb2JqZWN0IChub3QgSlNPTiBzdHJpbmcpIG9mIHNjYWxhciBwcm9wZXJ0aWVzLlxuICogTm90ZSBhcyB0aGlzIG1ldGhvZCBpcyBkZXNpZ25lZCB0byByZXR1cm4gYSB1c2VmdWwgbm9uLXRoaXMgdmFsdWUsXG4gKiBpdCBjYW5ub3QgYmUgY2hhaW5lZC5cbiAqXG4gKiBAcmV0dXJuIHtPYmplY3R9IGRlc2NyaWJpbmcgbWV0aG9kLCB1cmwsIGFuZCBkYXRhIG9mIHRoaXMgcmVxdWVzdFxuICogQGFwaSBwdWJsaWNcbiAqL1xuXG5SZXF1ZXN0QmFzZS5wcm90b3R5cGUudG9KU09OID0gZnVuY3Rpb24oKSB7XG4gIHJldHVybiB7XG4gICAgbWV0aG9kOiB0aGlzLm1ldGhvZCxcbiAgICB1cmw6IHRoaXMudXJsLFxuICAgIGRhdGE6IHRoaXMuX2RhdGEsXG4gICAgaGVhZGVyczogdGhpcy5faGVhZGVyXG4gIH07XG59O1xuXG4vKipcbiAqIFNlbmQgYGRhdGFgIGFzIHRoZSByZXF1ZXN0IGJvZHksIGRlZmF1bHRpbmcgdGhlIGAudHlwZSgpYCB0byBcImpzb25cIiB3aGVuXG4gKiBhbiBvYmplY3QgaXMgZ2l2ZW4uXG4gKlxuICogRXhhbXBsZXM6XG4gKlxuICogICAgICAgLy8gbWFudWFsIGpzb25cbiAqICAgICAgIHJlcXVlc3QucG9zdCgnL3VzZXInKVxuICogICAgICAgICAudHlwZSgnanNvbicpXG4gKiAgICAgICAgIC5zZW5kKCd7XCJuYW1lXCI6XCJ0alwifScpXG4gKiAgICAgICAgIC5lbmQoY2FsbGJhY2spXG4gKlxuICogICAgICAgLy8gYXV0byBqc29uXG4gKiAgICAgICByZXF1ZXN0LnBvc3QoJy91c2VyJylcbiAqICAgICAgICAgLnNlbmQoeyBuYW1lOiAndGonIH0pXG4gKiAgICAgICAgIC5lbmQoY2FsbGJhY2spXG4gKlxuICogICAgICAgLy8gbWFudWFsIHgtd3d3LWZvcm0tdXJsZW5jb2RlZFxuICogICAgICAgcmVxdWVzdC5wb3N0KCcvdXNlcicpXG4gKiAgICAgICAgIC50eXBlKCdmb3JtJylcbiAqICAgICAgICAgLnNlbmQoJ25hbWU9dGonKVxuICogICAgICAgICAuZW5kKGNhbGxiYWNrKVxuICpcbiAqICAgICAgIC8vIGF1dG8geC13d3ctZm9ybS11cmxlbmNvZGVkXG4gKiAgICAgICByZXF1ZXN0LnBvc3QoJy91c2VyJylcbiAqICAgICAgICAgLnR5cGUoJ2Zvcm0nKVxuICogICAgICAgICAuc2VuZCh7IG5hbWU6ICd0aicgfSlcbiAqICAgICAgICAgLmVuZChjYWxsYmFjaylcbiAqXG4gKiAgICAgICAvLyBkZWZhdWx0cyB0byB4LXd3dy1mb3JtLXVybGVuY29kZWRcbiAqICAgICAgcmVxdWVzdC5wb3N0KCcvdXNlcicpXG4gKiAgICAgICAgLnNlbmQoJ25hbWU9dG9iaScpXG4gKiAgICAgICAgLnNlbmQoJ3NwZWNpZXM9ZmVycmV0JylcbiAqICAgICAgICAuZW5kKGNhbGxiYWNrKVxuICpcbiAqIEBwYXJhbSB7U3RyaW5nfE9iamVjdH0gZGF0YVxuICogQHJldHVybiB7UmVxdWVzdH0gZm9yIGNoYWluaW5nXG4gKiBAYXBpIHB1YmxpY1xuICovXG5cbi8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBjb21wbGV4aXR5XG5SZXF1ZXN0QmFzZS5wcm90b3R5cGUuc2VuZCA9IGZ1bmN0aW9uKGRhdGEpIHtcbiAgY29uc3QgaXNPYmogPSBpc09iamVjdChkYXRhKTtcbiAgbGV0IHR5cGUgPSB0aGlzLl9oZWFkZXJbJ2NvbnRlbnQtdHlwZSddO1xuXG4gIGlmICh0aGlzLl9mb3JtRGF0YSkge1xuICAgIHRocm93IG5ldyBFcnJvcihcbiAgICAgIFwiLnNlbmQoKSBjYW4ndCBiZSB1c2VkIGlmIC5hdHRhY2goKSBvciAuZmllbGQoKSBpcyB1c2VkLiBQbGVhc2UgdXNlIG9ubHkgLnNlbmQoKSBvciBvbmx5IC5maWVsZCgpICYgLmF0dGFjaCgpXCJcbiAgICApO1xuICB9XG5cbiAgaWYgKGlzT2JqICYmICF0aGlzLl9kYXRhKSB7XG4gICAgaWYgKEFycmF5LmlzQXJyYXkoZGF0YSkpIHtcbiAgICAgIHRoaXMuX2RhdGEgPSBbXTtcbiAgICB9IGVsc2UgaWYgKCF0aGlzLl9pc0hvc3QoZGF0YSkpIHtcbiAgICAgIHRoaXMuX2RhdGEgPSB7fTtcbiAgICB9XG4gIH0gZWxzZSBpZiAoZGF0YSAmJiB0aGlzLl9kYXRhICYmIHRoaXMuX2lzSG9zdCh0aGlzLl9kYXRhKSkge1xuICAgIHRocm93IG5ldyBFcnJvcihcIkNhbid0IG1lcmdlIHRoZXNlIHNlbmQgY2FsbHNcIik7XG4gIH1cblxuICAvLyBtZXJnZVxuICBpZiAoaXNPYmogJiYgaXNPYmplY3QodGhpcy5fZGF0YSkpIHtcbiAgICBmb3IgKGNvbnN0IGtleSBpbiBkYXRhKSB7XG4gICAgICBpZiAoT2JqZWN0LnByb3RvdHlwZS5oYXNPd25Qcm9wZXJ0eS5jYWxsKGRhdGEsIGtleSkpXG4gICAgICAgIHRoaXMuX2RhdGFba2V5XSA9IGRhdGFba2V5XTtcbiAgICB9XG4gIH0gZWxzZSBpZiAodHlwZW9mIGRhdGEgPT09ICdzdHJpbmcnKSB7XG4gICAgLy8gZGVmYXVsdCB0byB4LXd3dy1mb3JtLXVybGVuY29kZWRcbiAgICBpZiAoIXR5cGUpIHRoaXMudHlwZSgnZm9ybScpO1xuICAgIHR5cGUgPSB0aGlzLl9oZWFkZXJbJ2NvbnRlbnQtdHlwZSddO1xuICAgIGlmICh0eXBlID09PSAnYXBwbGljYXRpb24veC13d3ctZm9ybS11cmxlbmNvZGVkJykge1xuICAgICAgdGhpcy5fZGF0YSA9IHRoaXMuX2RhdGEgPyBgJHt0aGlzLl9kYXRhfSYke2RhdGF9YCA6IGRhdGE7XG4gICAgfSBlbHNlIHtcbiAgICAgIHRoaXMuX2RhdGEgPSAodGhpcy5fZGF0YSB8fCAnJykgKyBkYXRhO1xuICAgIH1cbiAgfSBlbHNlIHtcbiAgICB0aGlzLl9kYXRhID0gZGF0YTtcbiAgfVxuXG4gIGlmICghaXNPYmogfHwgdGhpcy5faXNIb3N0KGRhdGEpKSB7XG4gICAgcmV0dXJuIHRoaXM7XG4gIH1cblxuICAvLyBkZWZhdWx0IHRvIGpzb25cbiAgaWYgKCF0eXBlKSB0aGlzLnR5cGUoJ2pzb24nKTtcbiAgcmV0dXJuIHRoaXM7XG59O1xuXG4vKipcbiAqIFNvcnQgYHF1ZXJ5c3RyaW5nYCBieSB0aGUgc29ydCBmdW5jdGlvblxuICpcbiAqXG4gKiBFeGFtcGxlczpcbiAqXG4gKiAgICAgICAvLyBkZWZhdWx0IG9yZGVyXG4gKiAgICAgICByZXF1ZXN0LmdldCgnL3VzZXInKVxuICogICAgICAgICAucXVlcnkoJ25hbWU9TmljaycpXG4gKiAgICAgICAgIC5xdWVyeSgnc2VhcmNoPU1hbm55JylcbiAqICAgICAgICAgLnNvcnRRdWVyeSgpXG4gKiAgICAgICAgIC5lbmQoY2FsbGJhY2spXG4gKlxuICogICAgICAgLy8gY3VzdG9taXplZCBzb3J0IGZ1bmN0aW9uXG4gKiAgICAgICByZXF1ZXN0LmdldCgnL3VzZXInKVxuICogICAgICAgICAucXVlcnkoJ25hbWU9TmljaycpXG4gKiAgICAgICAgIC5xdWVyeSgnc2VhcmNoPU1hbm55JylcbiAqICAgICAgICAgLnNvcnRRdWVyeShmdW5jdGlvbihhLCBiKXtcbiAqICAgICAgICAgICByZXR1cm4gYS5sZW5ndGggLSBiLmxlbmd0aDtcbiAqICAgICAgICAgfSlcbiAqICAgICAgICAgLmVuZChjYWxsYmFjaylcbiAqXG4gKlxuICogQHBhcmFtIHtGdW5jdGlvbn0gc29ydFxuICogQHJldHVybiB7UmVxdWVzdH0gZm9yIGNoYWluaW5nXG4gKiBAYXBpIHB1YmxpY1xuICovXG5cblJlcXVlc3RCYXNlLnByb3RvdHlwZS5zb3J0UXVlcnkgPSBmdW5jdGlvbihzb3J0KSB7XG4gIC8vIF9zb3J0IGRlZmF1bHQgdG8gdHJ1ZSBidXQgb3RoZXJ3aXNlIGNhbiBiZSBhIGZ1bmN0aW9uIG9yIGJvb2xlYW5cbiAgdGhpcy5fc29ydCA9IHR5cGVvZiBzb3J0ID09PSAndW5kZWZpbmVkJyA/IHRydWUgOiBzb3J0O1xuICByZXR1cm4gdGhpcztcbn07XG5cbi8qKlxuICogQ29tcG9zZSBxdWVyeXN0cmluZyB0byBhcHBlbmQgdG8gcmVxLnVybFxuICpcbiAqIEBhcGkgcHJpdmF0ZVxuICovXG5SZXF1ZXN0QmFzZS5wcm90b3R5cGUuX2ZpbmFsaXplUXVlcnlTdHJpbmcgPSBmdW5jdGlvbigpIHtcbiAgY29uc3QgcXVlcnkgPSB0aGlzLl9xdWVyeS5qb2luKCcmJyk7XG4gIGlmIChxdWVyeSkge1xuICAgIHRoaXMudXJsICs9ICh0aGlzLnVybC5pbmNsdWRlcygnPycpID8gJyYnIDogJz8nKSArIHF1ZXJ5O1xuICB9XG5cbiAgdGhpcy5fcXVlcnkubGVuZ3RoID0gMDsgLy8gTWFrZXMgdGhlIGNhbGwgaWRlbXBvdGVudFxuXG4gIGlmICh0aGlzLl9zb3J0KSB7XG4gICAgY29uc3QgaW5kZXggPSB0aGlzLnVybC5pbmRleE9mKCc/Jyk7XG4gICAgaWYgKGluZGV4ID49IDApIHtcbiAgICAgIGNvbnN0IHF1ZXJ5QXJyID0gdGhpcy51cmwuc2xpY2UoaW5kZXggKyAxKS5zcGxpdCgnJicpO1xuICAgICAgaWYgKHR5cGVvZiB0aGlzLl9zb3J0ID09PSAnZnVuY3Rpb24nKSB7XG4gICAgICAgIHF1ZXJ5QXJyLnNvcnQodGhpcy5fc29ydCk7XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBxdWVyeUFyci5zb3J0KCk7XG4gICAgICB9XG5cbiAgICAgIHRoaXMudXJsID0gdGhpcy51cmwuc2xpY2UoMCwgaW5kZXgpICsgJz8nICsgcXVlcnlBcnIuam9pbignJicpO1xuICAgIH1cbiAgfVxufTtcblxuLy8gRm9yIGJhY2t3YXJkcyBjb21wYXQgb25seVxuUmVxdWVzdEJhc2UucHJvdG90eXBlLl9hcHBlbmRRdWVyeVN0cmluZyA9ICgpID0+IHtcbiAgY29uc29sZS53YXJuKCdVbnN1cHBvcnRlZCcpO1xufTtcblxuLyoqXG4gKiBJbnZva2UgY2FsbGJhY2sgd2l0aCB0aW1lb3V0IGVycm9yLlxuICpcbiAqIEBhcGkgcHJpdmF0ZVxuICovXG5cblJlcXVlc3RCYXNlLnByb3RvdHlwZS5fdGltZW91dEVycm9yID0gZnVuY3Rpb24ocmVhc29uLCB0aW1lb3V0LCBlcnJubykge1xuICBpZiAodGhpcy5fYWJvcnRlZCkge1xuICAgIHJldHVybjtcbiAgfVxuXG4gIGNvbnN0IGVyciA9IG5ldyBFcnJvcihgJHtyZWFzb24gKyB0aW1lb3V0fW1zIGV4Y2VlZGVkYCk7XG4gIGVyci50aW1lb3V0ID0gdGltZW91dDtcbiAgZXJyLmNvZGUgPSAnRUNPTk5BQk9SVEVEJztcbiAgZXJyLmVycm5vID0gZXJybm87XG4gIHRoaXMudGltZWRvdXQgPSB0cnVlO1xuICB0aGlzLnRpbWVkb3V0RXJyb3IgPSBlcnI7XG4gIHRoaXMuYWJvcnQoKTtcbiAgdGhpcy5jYWxsYmFjayhlcnIpO1xufTtcblxuUmVxdWVzdEJhc2UucHJvdG90eXBlLl9zZXRUaW1lb3V0cyA9IGZ1bmN0aW9uKCkge1xuICBjb25zdCBzZWxmID0gdGhpcztcblxuICAvLyBkZWFkbGluZVxuICBpZiAodGhpcy5fdGltZW91dCAmJiAhdGhpcy5fdGltZXIpIHtcbiAgICB0aGlzLl90aW1lciA9IHNldFRpbWVvdXQoKCkgPT4ge1xuICAgICAgc2VsZi5fdGltZW91dEVycm9yKCdUaW1lb3V0IG9mICcsIHNlbGYuX3RpbWVvdXQsICdFVElNRScpO1xuICAgIH0sIHRoaXMuX3RpbWVvdXQpO1xuICB9XG5cbiAgLy8gcmVzcG9uc2UgdGltZW91dFxuICBpZiAodGhpcy5fcmVzcG9uc2VUaW1lb3V0ICYmICF0aGlzLl9yZXNwb25zZVRpbWVvdXRUaW1lcikge1xuICAgIHRoaXMuX3Jlc3BvbnNlVGltZW91dFRpbWVyID0gc2V0VGltZW91dCgoKSA9PiB7XG4gICAgICBzZWxmLl90aW1lb3V0RXJyb3IoXG4gICAgICAgICdSZXNwb25zZSB0aW1lb3V0IG9mICcsXG4gICAgICAgIHNlbGYuX3Jlc3BvbnNlVGltZW91dCxcbiAgICAgICAgJ0VUSU1FRE9VVCdcbiAgICAgICk7XG4gICAgfSwgdGhpcy5fcmVzcG9uc2VUaW1lb3V0KTtcbiAgfVxufTtcbiJdfQ== \ No newline at end of file diff --git a/node_modules/superagent/lib/response-base.js b/node_modules/superagent/lib/response-base.js new file mode 100644 index 000000000..ef7bf25a3 --- /dev/null +++ b/node_modules/superagent/lib/response-base.js @@ -0,0 +1,131 @@ +"use strict"; + +/** + * Module dependencies. + */ +var utils = require('./utils'); +/** + * Expose `ResponseBase`. + */ + + +module.exports = ResponseBase; +/** + * Initialize a new `ResponseBase`. + * + * @api public + */ + +function ResponseBase(obj) { + if (obj) return mixin(obj); +} +/** + * Mixin the prototype properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + + +function mixin(obj) { + for (var key in ResponseBase.prototype) { + if (Object.prototype.hasOwnProperty.call(ResponseBase.prototype, key)) obj[key] = ResponseBase.prototype[key]; + } + + return obj; +} +/** + * Get case-insensitive `field` value. + * + * @param {String} field + * @return {String} + * @api public + */ + + +ResponseBase.prototype.get = function (field) { + return this.header[field.toLowerCase()]; +}; +/** + * Set header related properties: + * + * - `.type` the content type without params + * + * A response of "Content-Type: text/plain; charset=utf-8" + * will provide you with a `.type` of "text/plain". + * + * @param {Object} header + * @api private + */ + + +ResponseBase.prototype._setHeaderProperties = function (header) { + // TODO: moar! + // TODO: make this a util + // content-type + var ct = header['content-type'] || ''; + this.type = utils.type(ct); // params + + var params = utils.params(ct); + + for (var key in params) { + if (Object.prototype.hasOwnProperty.call(params, key)) this[key] = params[key]; + } + + this.links = {}; // links + + try { + if (header.link) { + this.links = utils.parseLinks(header.link); + } + } catch (_unused) {// ignore + } +}; +/** + * Set flags such as `.ok` based on `status`. + * + * For example a 2xx response will give you a `.ok` of __true__ + * whereas 5xx will be __false__ and `.error` will be __true__. The + * `.clientError` and `.serverError` are also available to be more + * specific, and `.statusType` is the class of error ranging from 1..5 + * sometimes useful for mapping respond colors etc. + * + * "sugar" properties are also defined for common cases. Currently providing: + * + * - .noContent + * - .badRequest + * - .unauthorized + * - .notAcceptable + * - .notFound + * + * @param {Number} status + * @api private + */ + + +ResponseBase.prototype._setStatusProperties = function (status) { + var type = status / 100 | 0; // status / class + + this.statusCode = status; + this.status = this.statusCode; + this.statusType = type; // basics + + this.info = type === 1; + this.ok = type === 2; + this.redirect = type === 3; + this.clientError = type === 4; + this.serverError = type === 5; + this.error = type === 4 || type === 5 ? this.toError() : false; // sugar + + this.created = status === 201; + this.accepted = status === 202; + this.noContent = status === 204; + this.badRequest = status === 400; + this.unauthorized = status === 401; + this.notAcceptable = status === 406; + this.forbidden = status === 403; + this.notFound = status === 404; + this.unprocessableEntity = status === 422; +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uL3NyYy9yZXNwb25zZS1iYXNlLmpzIl0sIm5hbWVzIjpbInV0aWxzIiwicmVxdWlyZSIsIm1vZHVsZSIsImV4cG9ydHMiLCJSZXNwb25zZUJhc2UiLCJvYmoiLCJtaXhpbiIsImtleSIsInByb3RvdHlwZSIsIk9iamVjdCIsImhhc093blByb3BlcnR5IiwiY2FsbCIsImdldCIsImZpZWxkIiwiaGVhZGVyIiwidG9Mb3dlckNhc2UiLCJfc2V0SGVhZGVyUHJvcGVydGllcyIsImN0IiwidHlwZSIsInBhcmFtcyIsImxpbmtzIiwibGluayIsInBhcnNlTGlua3MiLCJfc2V0U3RhdHVzUHJvcGVydGllcyIsInN0YXR1cyIsInN0YXR1c0NvZGUiLCJzdGF0dXNUeXBlIiwiaW5mbyIsIm9rIiwicmVkaXJlY3QiLCJjbGllbnRFcnJvciIsInNlcnZlckVycm9yIiwiZXJyb3IiLCJ0b0Vycm9yIiwiY3JlYXRlZCIsImFjY2VwdGVkIiwibm9Db250ZW50IiwiYmFkUmVxdWVzdCIsInVuYXV0aG9yaXplZCIsIm5vdEFjY2VwdGFibGUiLCJmb3JiaWRkZW4iLCJub3RGb3VuZCIsInVucHJvY2Vzc2FibGVFbnRpdHkiXSwibWFwcGluZ3MiOiI7O0FBQUE7OztBQUlBLElBQU1BLEtBQUssR0FBR0MsT0FBTyxDQUFDLFNBQUQsQ0FBckI7QUFFQTs7Ozs7QUFJQUMsTUFBTSxDQUFDQyxPQUFQLEdBQWlCQyxZQUFqQjtBQUVBOzs7Ozs7QUFNQSxTQUFTQSxZQUFULENBQXNCQyxHQUF0QixFQUEyQjtBQUN6QixNQUFJQSxHQUFKLEVBQVMsT0FBT0MsS0FBSyxDQUFDRCxHQUFELENBQVo7QUFDVjtBQUVEOzs7Ozs7Ozs7QUFRQSxTQUFTQyxLQUFULENBQWVELEdBQWYsRUFBb0I7QUFDbEIsT0FBSyxJQUFNRSxHQUFYLElBQWtCSCxZQUFZLENBQUNJLFNBQS9CLEVBQTBDO0FBQ3hDLFFBQUlDLE1BQU0sQ0FBQ0QsU0FBUCxDQUFpQkUsY0FBakIsQ0FBZ0NDLElBQWhDLENBQXFDUCxZQUFZLENBQUNJLFNBQWxELEVBQTZERCxHQUE3RCxDQUFKLEVBQ0VGLEdBQUcsQ0FBQ0UsR0FBRCxDQUFILEdBQVdILFlBQVksQ0FBQ0ksU0FBYixDQUF1QkQsR0FBdkIsQ0FBWDtBQUNIOztBQUVELFNBQU9GLEdBQVA7QUFDRDtBQUVEOzs7Ozs7Ozs7QUFRQUQsWUFBWSxDQUFDSSxTQUFiLENBQXVCSSxHQUF2QixHQUE2QixVQUFTQyxLQUFULEVBQWdCO0FBQzNDLFNBQU8sS0FBS0MsTUFBTCxDQUFZRCxLQUFLLENBQUNFLFdBQU4sRUFBWixDQUFQO0FBQ0QsQ0FGRDtBQUlBOzs7Ozs7Ozs7Ozs7O0FBWUFYLFlBQVksQ0FBQ0ksU0FBYixDQUF1QlEsb0JBQXZCLEdBQThDLFVBQVNGLE1BQVQsRUFBaUI7QUFDN0Q7QUFDQTtBQUVBO0FBQ0EsTUFBTUcsRUFBRSxHQUFHSCxNQUFNLENBQUMsY0FBRCxDQUFOLElBQTBCLEVBQXJDO0FBQ0EsT0FBS0ksSUFBTCxHQUFZbEIsS0FBSyxDQUFDa0IsSUFBTixDQUFXRCxFQUFYLENBQVosQ0FONkQsQ0FRN0Q7O0FBQ0EsTUFBTUUsTUFBTSxHQUFHbkIsS0FBSyxDQUFDbUIsTUFBTixDQUFhRixFQUFiLENBQWY7O0FBQ0EsT0FBSyxJQUFNVixHQUFYLElBQWtCWSxNQUFsQixFQUEwQjtBQUN4QixRQUFJVixNQUFNLENBQUNELFNBQVAsQ0FBaUJFLGNBQWpCLENBQWdDQyxJQUFoQyxDQUFxQ1EsTUFBckMsRUFBNkNaLEdBQTdDLENBQUosRUFDRSxLQUFLQSxHQUFMLElBQVlZLE1BQU0sQ0FBQ1osR0FBRCxDQUFsQjtBQUNIOztBQUVELE9BQUthLEtBQUwsR0FBYSxFQUFiLENBZjZELENBaUI3RDs7QUFDQSxNQUFJO0FBQ0YsUUFBSU4sTUFBTSxDQUFDTyxJQUFYLEVBQWlCO0FBQ2YsV0FBS0QsS0FBTCxHQUFhcEIsS0FBSyxDQUFDc0IsVUFBTixDQUFpQlIsTUFBTSxDQUFDTyxJQUF4QixDQUFiO0FBQ0Q7QUFDRixHQUpELENBSUUsZ0JBQU0sQ0FDTjtBQUNEO0FBQ0YsQ0F6QkQ7QUEyQkE7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7QUFxQkFqQixZQUFZLENBQUNJLFNBQWIsQ0FBdUJlLG9CQUF2QixHQUE4QyxVQUFTQyxNQUFULEVBQWlCO0FBQzdELE1BQU1OLElBQUksR0FBSU0sTUFBTSxHQUFHLEdBQVYsR0FBaUIsQ0FBOUIsQ0FENkQsQ0FHN0Q7O0FBQ0EsT0FBS0MsVUFBTCxHQUFrQkQsTUFBbEI7QUFDQSxPQUFLQSxNQUFMLEdBQWMsS0FBS0MsVUFBbkI7QUFDQSxPQUFLQyxVQUFMLEdBQWtCUixJQUFsQixDQU42RCxDQVE3RDs7QUFDQSxPQUFLUyxJQUFMLEdBQVlULElBQUksS0FBSyxDQUFyQjtBQUNBLE9BQUtVLEVBQUwsR0FBVVYsSUFBSSxLQUFLLENBQW5CO0FBQ0EsT0FBS1csUUFBTCxHQUFnQlgsSUFBSSxLQUFLLENBQXpCO0FBQ0EsT0FBS1ksV0FBTCxHQUFtQlosSUFBSSxLQUFLLENBQTVCO0FBQ0EsT0FBS2EsV0FBTCxHQUFtQmIsSUFBSSxLQUFLLENBQTVCO0FBQ0EsT0FBS2MsS0FBTCxHQUFhZCxJQUFJLEtBQUssQ0FBVCxJQUFjQSxJQUFJLEtBQUssQ0FBdkIsR0FBMkIsS0FBS2UsT0FBTCxFQUEzQixHQUE0QyxLQUF6RCxDQWQ2RCxDQWdCN0Q7O0FBQ0EsT0FBS0MsT0FBTCxHQUFlVixNQUFNLEtBQUssR0FBMUI7QUFDQSxPQUFLVyxRQUFMLEdBQWdCWCxNQUFNLEtBQUssR0FBM0I7QUFDQSxPQUFLWSxTQUFMLEdBQWlCWixNQUFNLEtBQUssR0FBNUI7QUFDQSxPQUFLYSxVQUFMLEdBQWtCYixNQUFNLEtBQUssR0FBN0I7QUFDQSxPQUFLYyxZQUFMLEdBQW9CZCxNQUFNLEtBQUssR0FBL0I7QUFDQSxPQUFLZSxhQUFMLEdBQXFCZixNQUFNLEtBQUssR0FBaEM7QUFDQSxPQUFLZ0IsU0FBTCxHQUFpQmhCLE1BQU0sS0FBSyxHQUE1QjtBQUNBLE9BQUtpQixRQUFMLEdBQWdCakIsTUFBTSxLQUFLLEdBQTNCO0FBQ0EsT0FBS2tCLG1CQUFMLEdBQTJCbEIsTUFBTSxLQUFLLEdBQXRDO0FBQ0QsQ0ExQkQiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIE1vZHVsZSBkZXBlbmRlbmNpZXMuXG4gKi9cblxuY29uc3QgdXRpbHMgPSByZXF1aXJlKCcuL3V0aWxzJyk7XG5cbi8qKlxuICogRXhwb3NlIGBSZXNwb25zZUJhc2VgLlxuICovXG5cbm1vZHVsZS5leHBvcnRzID0gUmVzcG9uc2VCYXNlO1xuXG4vKipcbiAqIEluaXRpYWxpemUgYSBuZXcgYFJlc3BvbnNlQmFzZWAuXG4gKlxuICogQGFwaSBwdWJsaWNcbiAqL1xuXG5mdW5jdGlvbiBSZXNwb25zZUJhc2Uob2JqKSB7XG4gIGlmIChvYmopIHJldHVybiBtaXhpbihvYmopO1xufVxuXG4vKipcbiAqIE1peGluIHRoZSBwcm90b3R5cGUgcHJvcGVydGllcy5cbiAqXG4gKiBAcGFyYW0ge09iamVjdH0gb2JqXG4gKiBAcmV0dXJuIHtPYmplY3R9XG4gKiBAYXBpIHByaXZhdGVcbiAqL1xuXG5mdW5jdGlvbiBtaXhpbihvYmopIHtcbiAgZm9yIChjb25zdCBrZXkgaW4gUmVzcG9uc2VCYXNlLnByb3RvdHlwZSkge1xuICAgIGlmIChPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwoUmVzcG9uc2VCYXNlLnByb3RvdHlwZSwga2V5KSlcbiAgICAgIG9ialtrZXldID0gUmVzcG9uc2VCYXNlLnByb3RvdHlwZVtrZXldO1xuICB9XG5cbiAgcmV0dXJuIG9iajtcbn1cblxuLyoqXG4gKiBHZXQgY2FzZS1pbnNlbnNpdGl2ZSBgZmllbGRgIHZhbHVlLlxuICpcbiAqIEBwYXJhbSB7U3RyaW5nfSBmaWVsZFxuICogQHJldHVybiB7U3RyaW5nfVxuICogQGFwaSBwdWJsaWNcbiAqL1xuXG5SZXNwb25zZUJhc2UucHJvdG90eXBlLmdldCA9IGZ1bmN0aW9uKGZpZWxkKSB7XG4gIHJldHVybiB0aGlzLmhlYWRlcltmaWVsZC50b0xvd2VyQ2FzZSgpXTtcbn07XG5cbi8qKlxuICogU2V0IGhlYWRlciByZWxhdGVkIHByb3BlcnRpZXM6XG4gKlxuICogICAtIGAudHlwZWAgdGhlIGNvbnRlbnQgdHlwZSB3aXRob3V0IHBhcmFtc1xuICpcbiAqIEEgcmVzcG9uc2Ugb2YgXCJDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9dXRmLThcIlxuICogd2lsbCBwcm92aWRlIHlvdSB3aXRoIGEgYC50eXBlYCBvZiBcInRleHQvcGxhaW5cIi5cbiAqXG4gKiBAcGFyYW0ge09iamVjdH0gaGVhZGVyXG4gKiBAYXBpIHByaXZhdGVcbiAqL1xuXG5SZXNwb25zZUJhc2UucHJvdG90eXBlLl9zZXRIZWFkZXJQcm9wZXJ0aWVzID0gZnVuY3Rpb24oaGVhZGVyKSB7XG4gIC8vIFRPRE86IG1vYXIhXG4gIC8vIFRPRE86IG1ha2UgdGhpcyBhIHV0aWxcblxuICAvLyBjb250ZW50LXR5cGVcbiAgY29uc3QgY3QgPSBoZWFkZXJbJ2NvbnRlbnQtdHlwZSddIHx8ICcnO1xuICB0aGlzLnR5cGUgPSB1dGlscy50eXBlKGN0KTtcblxuICAvLyBwYXJhbXNcbiAgY29uc3QgcGFyYW1zID0gdXRpbHMucGFyYW1zKGN0KTtcbiAgZm9yIChjb25zdCBrZXkgaW4gcGFyYW1zKSB7XG4gICAgaWYgKE9iamVjdC5wcm90b3R5cGUuaGFzT3duUHJvcGVydHkuY2FsbChwYXJhbXMsIGtleSkpXG4gICAgICB0aGlzW2tleV0gPSBwYXJhbXNba2V5XTtcbiAgfVxuXG4gIHRoaXMubGlua3MgPSB7fTtcblxuICAvLyBsaW5rc1xuICB0cnkge1xuICAgIGlmIChoZWFkZXIubGluaykge1xuICAgICAgdGhpcy5saW5rcyA9IHV0aWxzLnBhcnNlTGlua3MoaGVhZGVyLmxpbmspO1xuICAgIH1cbiAgfSBjYXRjaCB7XG4gICAgLy8gaWdub3JlXG4gIH1cbn07XG5cbi8qKlxuICogU2V0IGZsYWdzIHN1Y2ggYXMgYC5va2AgYmFzZWQgb24gYHN0YXR1c2AuXG4gKlxuICogRm9yIGV4YW1wbGUgYSAyeHggcmVzcG9uc2Ugd2lsbCBnaXZlIHlvdSBhIGAub2tgIG9mIF9fdHJ1ZV9fXG4gKiB3aGVyZWFzIDV4eCB3aWxsIGJlIF9fZmFsc2VfXyBhbmQgYC5lcnJvcmAgd2lsbCBiZSBfX3RydWVfXy4gVGhlXG4gKiBgLmNsaWVudEVycm9yYCBhbmQgYC5zZXJ2ZXJFcnJvcmAgYXJlIGFsc28gYXZhaWxhYmxlIHRvIGJlIG1vcmVcbiAqIHNwZWNpZmljLCBhbmQgYC5zdGF0dXNUeXBlYCBpcyB0aGUgY2xhc3Mgb2YgZXJyb3IgcmFuZ2luZyBmcm9tIDEuLjVcbiAqIHNvbWV0aW1lcyB1c2VmdWwgZm9yIG1hcHBpbmcgcmVzcG9uZCBjb2xvcnMgZXRjLlxuICpcbiAqIFwic3VnYXJcIiBwcm9wZXJ0aWVzIGFyZSBhbHNvIGRlZmluZWQgZm9yIGNvbW1vbiBjYXNlcy4gQ3VycmVudGx5IHByb3ZpZGluZzpcbiAqXG4gKiAgIC0gLm5vQ29udGVudFxuICogICAtIC5iYWRSZXF1ZXN0XG4gKiAgIC0gLnVuYXV0aG9yaXplZFxuICogICAtIC5ub3RBY2NlcHRhYmxlXG4gKiAgIC0gLm5vdEZvdW5kXG4gKlxuICogQHBhcmFtIHtOdW1iZXJ9IHN0YXR1c1xuICogQGFwaSBwcml2YXRlXG4gKi9cblxuUmVzcG9uc2VCYXNlLnByb3RvdHlwZS5fc2V0U3RhdHVzUHJvcGVydGllcyA9IGZ1bmN0aW9uKHN0YXR1cykge1xuICBjb25zdCB0eXBlID0gKHN0YXR1cyAvIDEwMCkgfCAwO1xuXG4gIC8vIHN0YXR1cyAvIGNsYXNzXG4gIHRoaXMuc3RhdHVzQ29kZSA9IHN0YXR1cztcbiAgdGhpcy5zdGF0dXMgPSB0aGlzLnN0YXR1c0NvZGU7XG4gIHRoaXMuc3RhdHVzVHlwZSA9IHR5cGU7XG5cbiAgLy8gYmFzaWNzXG4gIHRoaXMuaW5mbyA9IHR5cGUgPT09IDE7XG4gIHRoaXMub2sgPSB0eXBlID09PSAyO1xuICB0aGlzLnJlZGlyZWN0ID0gdHlwZSA9PT0gMztcbiAgdGhpcy5jbGllbnRFcnJvciA9IHR5cGUgPT09IDQ7XG4gIHRoaXMuc2VydmVyRXJyb3IgPSB0eXBlID09PSA1O1xuICB0aGlzLmVycm9yID0gdHlwZSA9PT0gNCB8fCB0eXBlID09PSA1ID8gdGhpcy50b0Vycm9yKCkgOiBmYWxzZTtcblxuICAvLyBzdWdhclxuICB0aGlzLmNyZWF0ZWQgPSBzdGF0dXMgPT09IDIwMTtcbiAgdGhpcy5hY2NlcHRlZCA9IHN0YXR1cyA9PT0gMjAyO1xuICB0aGlzLm5vQ29udGVudCA9IHN0YXR1cyA9PT0gMjA0O1xuICB0aGlzLmJhZFJlcXVlc3QgPSBzdGF0dXMgPT09IDQwMDtcbiAgdGhpcy51bmF1dGhvcml6ZWQgPSBzdGF0dXMgPT09IDQwMTtcbiAgdGhpcy5ub3RBY2NlcHRhYmxlID0gc3RhdHVzID09PSA0MDY7XG4gIHRoaXMuZm9yYmlkZGVuID0gc3RhdHVzID09PSA0MDM7XG4gIHRoaXMubm90Rm91bmQgPSBzdGF0dXMgPT09IDQwNDtcbiAgdGhpcy51bnByb2Nlc3NhYmxlRW50aXR5ID0gc3RhdHVzID09PSA0MjI7XG59O1xuIl19 \ No newline at end of file diff --git a/node_modules/superagent/lib/utils.js b/node_modules/superagent/lib/utils.js new file mode 100644 index 000000000..21e6a9e77 --- /dev/null +++ b/node_modules/superagent/lib/utils.js @@ -0,0 +1,71 @@ +"use strict"; + +/** + * Return the mime type for the given `str`. + * + * @param {String} str + * @return {String} + * @api private + */ +exports.type = function (str) { + return str.split(/ *; */).shift(); +}; +/** + * Return header field parameters. + * + * @param {String} str + * @return {Object} + * @api private + */ + + +exports.params = function (str) { + return str.split(/ *; */).reduce(function (obj, str) { + var parts = str.split(/ *= */); + var key = parts.shift(); + var val = parts.shift(); + if (key && val) obj[key] = val; + return obj; + }, {}); +}; +/** + * Parse Link header fields. + * + * @param {String} str + * @return {Object} + * @api private + */ + + +exports.parseLinks = function (str) { + return str.split(/ *, */).reduce(function (obj, str) { + var parts = str.split(/ *; */); + var url = parts[0].slice(1, -1); + var rel = parts[1].split(/ *= */)[1].slice(1, -1); + obj[rel] = url; + return obj; + }, {}); +}; +/** + * Strip content related fields from `header`. + * + * @param {Object} header + * @return {Object} header + * @api private + */ + + +exports.cleanHeader = function (header, changesOrigin) { + delete header['content-type']; + delete header['content-length']; + delete header['transfer-encoding']; + delete header.host; // secuirty + + if (changesOrigin) { + delete header.authorization; + delete header.cookie; + } + + return header; +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uL3NyYy91dGlscy5qcyJdLCJuYW1lcyI6WyJleHBvcnRzIiwidHlwZSIsInN0ciIsInNwbGl0Iiwic2hpZnQiLCJwYXJhbXMiLCJyZWR1Y2UiLCJvYmoiLCJwYXJ0cyIsImtleSIsInZhbCIsInBhcnNlTGlua3MiLCJ1cmwiLCJzbGljZSIsInJlbCIsImNsZWFuSGVhZGVyIiwiaGVhZGVyIiwiY2hhbmdlc09yaWdpbiIsImhvc3QiLCJhdXRob3JpemF0aW9uIiwiY29va2llIl0sIm1hcHBpbmdzIjoiOztBQUFBOzs7Ozs7O0FBUUFBLE9BQU8sQ0FBQ0MsSUFBUixHQUFlLFVBQUFDLEdBQUc7QUFBQSxTQUFJQSxHQUFHLENBQUNDLEtBQUosQ0FBVSxPQUFWLEVBQW1CQyxLQUFuQixFQUFKO0FBQUEsQ0FBbEI7QUFFQTs7Ozs7Ozs7O0FBUUFKLE9BQU8sQ0FBQ0ssTUFBUixHQUFpQixVQUFBSCxHQUFHO0FBQUEsU0FDbEJBLEdBQUcsQ0FBQ0MsS0FBSixDQUFVLE9BQVYsRUFBbUJHLE1BQW5CLENBQTBCLFVBQUNDLEdBQUQsRUFBTUwsR0FBTixFQUFjO0FBQ3RDLFFBQU1NLEtBQUssR0FBR04sR0FBRyxDQUFDQyxLQUFKLENBQVUsT0FBVixDQUFkO0FBQ0EsUUFBTU0sR0FBRyxHQUFHRCxLQUFLLENBQUNKLEtBQU4sRUFBWjtBQUNBLFFBQU1NLEdBQUcsR0FBR0YsS0FBSyxDQUFDSixLQUFOLEVBQVo7QUFFQSxRQUFJSyxHQUFHLElBQUlDLEdBQVgsRUFBZ0JILEdBQUcsQ0FBQ0UsR0FBRCxDQUFILEdBQVdDLEdBQVg7QUFDaEIsV0FBT0gsR0FBUDtBQUNELEdBUEQsRUFPRyxFQVBILENBRGtCO0FBQUEsQ0FBcEI7QUFVQTs7Ozs7Ozs7O0FBUUFQLE9BQU8sQ0FBQ1csVUFBUixHQUFxQixVQUFBVCxHQUFHO0FBQUEsU0FDdEJBLEdBQUcsQ0FBQ0MsS0FBSixDQUFVLE9BQVYsRUFBbUJHLE1BQW5CLENBQTBCLFVBQUNDLEdBQUQsRUFBTUwsR0FBTixFQUFjO0FBQ3RDLFFBQU1NLEtBQUssR0FBR04sR0FBRyxDQUFDQyxLQUFKLENBQVUsT0FBVixDQUFkO0FBQ0EsUUFBTVMsR0FBRyxHQUFHSixLQUFLLENBQUMsQ0FBRCxDQUFMLENBQVNLLEtBQVQsQ0FBZSxDQUFmLEVBQWtCLENBQUMsQ0FBbkIsQ0FBWjtBQUNBLFFBQU1DLEdBQUcsR0FBR04sS0FBSyxDQUFDLENBQUQsQ0FBTCxDQUFTTCxLQUFULENBQWUsT0FBZixFQUF3QixDQUF4QixFQUEyQlUsS0FBM0IsQ0FBaUMsQ0FBakMsRUFBb0MsQ0FBQyxDQUFyQyxDQUFaO0FBQ0FOLElBQUFBLEdBQUcsQ0FBQ08sR0FBRCxDQUFILEdBQVdGLEdBQVg7QUFDQSxXQUFPTCxHQUFQO0FBQ0QsR0FORCxFQU1HLEVBTkgsQ0FEc0I7QUFBQSxDQUF4QjtBQVNBOzs7Ozs7Ozs7QUFRQVAsT0FBTyxDQUFDZSxXQUFSLEdBQXNCLFVBQUNDLE1BQUQsRUFBU0MsYUFBVCxFQUEyQjtBQUMvQyxTQUFPRCxNQUFNLENBQUMsY0FBRCxDQUFiO0FBQ0EsU0FBT0EsTUFBTSxDQUFDLGdCQUFELENBQWI7QUFDQSxTQUFPQSxNQUFNLENBQUMsbUJBQUQsQ0FBYjtBQUNBLFNBQU9BLE1BQU0sQ0FBQ0UsSUFBZCxDQUorQyxDQUsvQzs7QUFDQSxNQUFJRCxhQUFKLEVBQW1CO0FBQ2pCLFdBQU9ELE1BQU0sQ0FBQ0csYUFBZDtBQUNBLFdBQU9ILE1BQU0sQ0FBQ0ksTUFBZDtBQUNEOztBQUVELFNBQU9KLE1BQVA7QUFDRCxDQVpEIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBSZXR1cm4gdGhlIG1pbWUgdHlwZSBmb3IgdGhlIGdpdmVuIGBzdHJgLlxuICpcbiAqIEBwYXJhbSB7U3RyaW5nfSBzdHJcbiAqIEByZXR1cm4ge1N0cmluZ31cbiAqIEBhcGkgcHJpdmF0ZVxuICovXG5cbmV4cG9ydHMudHlwZSA9IHN0ciA9PiBzdHIuc3BsaXQoLyAqOyAqLykuc2hpZnQoKTtcblxuLyoqXG4gKiBSZXR1cm4gaGVhZGVyIGZpZWxkIHBhcmFtZXRlcnMuXG4gKlxuICogQHBhcmFtIHtTdHJpbmd9IHN0clxuICogQHJldHVybiB7T2JqZWN0fVxuICogQGFwaSBwcml2YXRlXG4gKi9cblxuZXhwb3J0cy5wYXJhbXMgPSBzdHIgPT5cbiAgc3RyLnNwbGl0KC8gKjsgKi8pLnJlZHVjZSgob2JqLCBzdHIpID0+IHtcbiAgICBjb25zdCBwYXJ0cyA9IHN0ci5zcGxpdCgvICo9ICovKTtcbiAgICBjb25zdCBrZXkgPSBwYXJ0cy5zaGlmdCgpO1xuICAgIGNvbnN0IHZhbCA9IHBhcnRzLnNoaWZ0KCk7XG5cbiAgICBpZiAoa2V5ICYmIHZhbCkgb2JqW2tleV0gPSB2YWw7XG4gICAgcmV0dXJuIG9iajtcbiAgfSwge30pO1xuXG4vKipcbiAqIFBhcnNlIExpbmsgaGVhZGVyIGZpZWxkcy5cbiAqXG4gKiBAcGFyYW0ge1N0cmluZ30gc3RyXG4gKiBAcmV0dXJuIHtPYmplY3R9XG4gKiBAYXBpIHByaXZhdGVcbiAqL1xuXG5leHBvcnRzLnBhcnNlTGlua3MgPSBzdHIgPT5cbiAgc3RyLnNwbGl0KC8gKiwgKi8pLnJlZHVjZSgob2JqLCBzdHIpID0+IHtcbiAgICBjb25zdCBwYXJ0cyA9IHN0ci5zcGxpdCgvICo7ICovKTtcbiAgICBjb25zdCB1cmwgPSBwYXJ0c1swXS5zbGljZSgxLCAtMSk7XG4gICAgY29uc3QgcmVsID0gcGFydHNbMV0uc3BsaXQoLyAqPSAqLylbMV0uc2xpY2UoMSwgLTEpO1xuICAgIG9ialtyZWxdID0gdXJsO1xuICAgIHJldHVybiBvYmo7XG4gIH0sIHt9KTtcblxuLyoqXG4gKiBTdHJpcCBjb250ZW50IHJlbGF0ZWQgZmllbGRzIGZyb20gYGhlYWRlcmAuXG4gKlxuICogQHBhcmFtIHtPYmplY3R9IGhlYWRlclxuICogQHJldHVybiB7T2JqZWN0fSBoZWFkZXJcbiAqIEBhcGkgcHJpdmF0ZVxuICovXG5cbmV4cG9ydHMuY2xlYW5IZWFkZXIgPSAoaGVhZGVyLCBjaGFuZ2VzT3JpZ2luKSA9PiB7XG4gIGRlbGV0ZSBoZWFkZXJbJ2NvbnRlbnQtdHlwZSddO1xuICBkZWxldGUgaGVhZGVyWydjb250ZW50LWxlbmd0aCddO1xuICBkZWxldGUgaGVhZGVyWyd0cmFuc2Zlci1lbmNvZGluZyddO1xuICBkZWxldGUgaGVhZGVyLmhvc3Q7XG4gIC8vIHNlY3VpcnR5XG4gIGlmIChjaGFuZ2VzT3JpZ2luKSB7XG4gICAgZGVsZXRlIGhlYWRlci5hdXRob3JpemF0aW9uO1xuICAgIGRlbGV0ZSBoZWFkZXIuY29va2llO1xuICB9XG5cbiAgcmV0dXJuIGhlYWRlcjtcbn07XG4iXX0= \ No newline at end of file diff --git a/node_modules/superagent/node_modules/.bin/semver b/node_modules/superagent/node_modules/.bin/semver new file mode 120000 index 000000000..5aaadf42c --- /dev/null +++ b/node_modules/superagent/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver.js \ No newline at end of file diff --git a/node_modules/superagent/node_modules/form-data/License b/node_modules/superagent/node_modules/form-data/License new file mode 100644 index 000000000..c7ff12a2f --- /dev/null +++ b/node_modules/superagent/node_modules/form-data/License @@ -0,0 +1,19 @@ +Copyright (c) 2012 Felix Geisendörfer (felix@debuggable.com) and contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. diff --git a/node_modules/superagent/node_modules/form-data/README.md.bak b/node_modules/superagent/node_modules/form-data/README.md.bak new file mode 100644 index 000000000..f06d86cb3 --- /dev/null +++ b/node_modules/superagent/node_modules/form-data/README.md.bak @@ -0,0 +1,356 @@ +# Form-Data [![NPM Module](https://img.shields.io/npm/v/form-data.svg)](https://www.npmjs.com/package/form-data) [![Join the chat at https://gitter.im/form-data/form-data](http://form-data.github.io/images/gitterbadge.svg)](https://gitter.im/form-data/form-data) + +A library to create readable ```"multipart/form-data"``` streams. Can be used to submit forms and file uploads to other web applications. + +The API of this library is inspired by the [XMLHttpRequest-2 FormData Interface][xhr2-fd]. + +[xhr2-fd]: http://dev.w3.org/2006/webapi/XMLHttpRequest-2/Overview.html#the-formdata-interface + +[![Linux Build](https://img.shields.io/travis/form-data/form-data/v3.0.1.svg?label=linux:6.x-12.x)](https://travis-ci.org/form-data/form-data) +[![MacOS Build](https://img.shields.io/travis/form-data/form-data/v3.0.1.svg?label=macos:6.x-12.x)](https://travis-ci.org/form-data/form-data) +[![Windows Build](https://img.shields.io/travis/form-data/form-data/v3.0.1.svg?label=windows:6.x-12.x)](https://travis-ci.org/form-data/form-data) + +[![Coverage Status](https://img.shields.io/coveralls/form-data/form-data/v3.0.1.svg?label=code+coverage)](https://coveralls.io/github/form-data/form-data?branch=master) +[![Dependency Status](https://img.shields.io/david/form-data/form-data.svg)](https://david-dm.org/form-data/form-data) + +## Install + +``` +npm install --save form-data +``` + +## Usage + +In this example we are constructing a form with 3 fields that contain a string, +a buffer and a file stream. + +``` javascript +var FormData = require('form-data'); +var fs = require('fs'); + +var form = new FormData(); +form.append('my_field', 'my value'); +form.append('my_buffer', new Buffer(10)); +form.append('my_file', fs.createReadStream('/foo/bar.jpg')); +``` + +Also you can use http-response stream: + +``` javascript +var FormData = require('form-data'); +var http = require('http'); + +var form = new FormData(); + +http.request('http://nodejs.org/images/logo.png', function(response) { + form.append('my_field', 'my value'); + form.append('my_buffer', new Buffer(10)); + form.append('my_logo', response); +}); +``` + +Or @mikeal's [request](https://github.com/request/request) stream: + +``` javascript +var FormData = require('form-data'); +var request = require('request'); + +var form = new FormData(); + +form.append('my_field', 'my value'); +form.append('my_buffer', new Buffer(10)); +form.append('my_logo', request('http://nodejs.org/images/logo.png')); +``` + +In order to submit this form to a web application, call ```submit(url, [callback])``` method: + +``` javascript +form.submit('http://example.org/', function(err, res) { + // res – response object (http.IncomingMessage) // + res.resume(); +}); + +``` + +For more advanced request manipulations ```submit()``` method returns ```http.ClientRequest``` object, or you can choose from one of the alternative submission methods. + +### Custom options + +You can provide custom options, such as `maxDataSize`: + +``` javascript +var FormData = require('form-data'); + +var form = new FormData({ maxDataSize: 20971520 }); +form.append('my_field', 'my value'); +form.append('my_buffer', /* something big */); +``` + +List of available options could be found in [combined-stream](https://github.com/felixge/node-combined-stream/blob/master/lib/combined_stream.js#L7-L15) + +### Alternative submission methods + +You can use node's http client interface: + +``` javascript +var http = require('http'); + +var request = http.request({ + method: 'post', + host: 'example.org', + path: '/upload', + headers: form.getHeaders() +}); + +form.pipe(request); + +request.on('response', function(res) { + console.log(res.statusCode); +}); +``` + +Or if you would prefer the `'Content-Length'` header to be set for you: + +``` javascript +form.submit('example.org/upload', function(err, res) { + console.log(res.statusCode); +}); +``` + +To use custom headers and pre-known length in parts: + +``` javascript +var CRLF = '\r\n'; +var form = new FormData(); + +var options = { + header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF, + knownLength: 1 +}; + +form.append('my_buffer', buffer, options); + +form.submit('http://example.com/', function(err, res) { + if (err) throw err; + console.log('Done'); +}); +``` + +Form-Data can recognize and fetch all the required information from common types of streams (```fs.readStream```, ```http.response``` and ```mikeal's request```), for some other types of streams you'd need to provide "file"-related information manually: + +``` javascript +someModule.stream(function(err, stdout, stderr) { + if (err) throw err; + + var form = new FormData(); + + form.append('file', stdout, { + filename: 'unicycle.jpg', // ... or: + filepath: 'photos/toys/unicycle.jpg', + contentType: 'image/jpeg', + knownLength: 19806 + }); + + form.submit('http://example.com/', function(err, res) { + if (err) throw err; + console.log('Done'); + }); +}); +``` + +The `filepath` property overrides `filename` and may contain a relative path. This is typically used when uploading [multiple files from a directory](https://wicg.github.io/entries-api/#dom-htmlinputelement-webkitdirectory). + +For edge cases, like POST request to URL with query string or to pass HTTP auth credentials, object can be passed to `form.submit()` as first parameter: + +``` javascript +form.submit({ + host: 'example.com', + path: '/probably.php?extra=params', + auth: 'username:password' +}, function(err, res) { + console.log(res.statusCode); +}); +``` + +In case you need to also send custom HTTP headers with the POST request, you can use the `headers` key in first parameter of `form.submit()`: + +``` javascript +form.submit({ + host: 'example.com', + path: '/surelynot.php', + headers: {'x-test-header': 'test-header-value'} +}, function(err, res) { + console.log(res.statusCode); +}); +``` + +### Methods + +- [_Void_ append( **String** _field_, **Mixed** _value_ [, **Mixed** _options_] )](https://github.com/form-data/form-data#void-append-string-field-mixed-value--mixed-options-). +- [_Headers_ getHeaders( [**Headers** _userHeaders_] )](https://github.com/form-data/form-data#array-getheaders-array-userheaders-) +- [_String_ getBoundary()](https://github.com/form-data/form-data#string-getboundary) +- [_Void_ setBoundary()](https://github.com/form-data/form-data#void-setboundary) +- [_Buffer_ getBuffer()](https://github.com/form-data/form-data#buffer-getbuffer) +- [_Integer_ getLengthSync()](https://github.com/form-data/form-data#integer-getlengthsync) +- [_Integer_ getLength( **function** _callback_ )](https://github.com/form-data/form-data#integer-getlength-function-callback-) +- [_Boolean_ hasKnownLength()](https://github.com/form-data/form-data#boolean-hasknownlength) +- [_Request_ submit( _params_, **function** _callback_ )](https://github.com/form-data/form-data#request-submit-params-function-callback-) +- [_String_ toString()](https://github.com/form-data/form-data#string-tostring) + +#### _Void_ append( **String** _field_, **Mixed** _value_ [, **Mixed** _options_] ) +Append data to the form. You can submit about any format (string, integer, boolean, buffer, etc.). However, Arrays are not supported and need to be turned into strings by the user. +```javascript +var form = new FormData(); +form.append( 'my_string', 'my value' ); +form.append( 'my_integer', 1 ); +form.append( 'my_boolean', true ); +form.append( 'my_buffer', new Buffer(10) ); +form.append( 'my_array_as_json', JSON.stringify( ['bird','cute'] ) ) +``` + +You may provide a string for options, or an object. +```javascript +// Set filename by providing a string for options +form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), 'bar.jpg' ); + +// provide an object. +form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), {filename: 'bar.jpg', contentType: 'image/jpeg', knownLength: 19806} ); +``` + +#### _Headers_ getHeaders( [**Headers** _userHeaders_] ) +This method adds the correct `content-type` header to the provided array of `userHeaders`. + +#### _String_ getBoundary() +Return the boundary of the formData. By default, the boundary consists of 26 `-` followed by 24 numbers +for example: +```javascript +--------------------------515890814546601021194782 +``` + +#### _Void_ setBoundary(String _boundary_) +Set the boundary string, overriding the default behavior described above. + +_Note: The boundary must be unique and may not appear in the data._ + +#### _Buffer_ getBuffer() +Return the full formdata request package, as a Buffer. You can insert this Buffer in e.g. Axios to send multipart data. +```javascript +var form = new FormData(); +form.append( 'my_buffer', Buffer.from([0x4a,0x42,0x20,0x52,0x6f,0x63,0x6b,0x73]) ); +form.append( 'my_file', fs.readFileSync('/foo/bar.jpg') ); + +axios.post( 'https://example.com/path/to/api', + form.getBuffer(), + form.getHeaders() + ) +``` +**Note:** Because the output is of type Buffer, you can only append types that are accepted by Buffer: *string, Buffer, ArrayBuffer, Array, or Array-like Object*. A ReadStream for example will result in an error. + +#### _Integer_ getLengthSync() +Same as `getLength` but synchronous. + +_Note: getLengthSync __doesn't__ calculate streams length._ + +#### _Integer_ getLength( **function** _callback_ ) +Returns the `Content-Length` async. The callback is used to handle errors and continue once the length has been calculated +```javascript +this.getLength(function(err, length) { + if (err) { + this._error(err); + return; + } + + // add content length + request.setHeader('Content-Length', length); + + ... +}.bind(this)); +``` + +#### _Boolean_ hasKnownLength() +Checks if the length of added values is known. + +#### _Request_ submit( _params_, **function** _callback_ ) +Submit the form to a web application. +```javascript +var form = new FormData(); +form.append( 'my_string', 'Hello World' ); + +form.submit( 'http://example.com/', function(err, res) { + // res – response object (http.IncomingMessage) // + res.resume(); +} ); +``` + +#### _String_ toString() +Returns the form data as a string. Don't use this if you are sending files or buffers, use `getBuffer()` instead. + +### Integration with other libraries + +#### Request + +Form submission using [request](https://github.com/request/request): + +```javascript +var formData = { + my_field: 'my_value', + my_file: fs.createReadStream(__dirname + '/unicycle.jpg'), +}; + +request.post({url:'http://service.com/upload', formData: formData}, function(err, httpResponse, body) { + if (err) { + return console.error('upload failed:', err); + } + console.log('Upload successful! Server responded with:', body); +}); +``` + +For more details see [request readme](https://github.com/request/request#multipartform-data-multipart-form-uploads). + +#### node-fetch + +You can also submit a form using [node-fetch](https://github.com/bitinn/node-fetch): + +```javascript +var form = new FormData(); + +form.append('a', 1); + +fetch('http://example.com', { method: 'POST', body: form }) + .then(function(res) { + return res.json(); + }).then(function(json) { + console.log(json); + }); +``` + +#### axios + +In Node.js you can post a file using [axios](https://github.com/axios/axios): +```javascript +const form = new FormData(); +const stream = fs.createReadStream(PATH_TO_FILE); + +form.append('image', stream); + +// In Node.js environment you need to set boundary in the header field 'Content-Type' by calling method `getHeaders` +const formHeaders = form.getHeaders(); + +axios.post('http://example.com', form, { + headers: { + ...formHeaders, + }, +}) +.then(response => response) +.catch(error => error) +``` + +## Notes + +- ```getLengthSync()``` method DOESN'T calculate length for streams, use ```knownLength``` options as workaround. +- Starting version `2.x` FormData has dropped support for `node@0.10.x`. +- Starting version `3.x` FormData has dropped support for `node@4.x`. + +## License + +Form-Data is released under the [MIT](License) license. diff --git a/node_modules/superagent/node_modules/form-data/Readme.md b/node_modules/superagent/node_modules/form-data/Readme.md new file mode 100644 index 000000000..f06d86cb3 --- /dev/null +++ b/node_modules/superagent/node_modules/form-data/Readme.md @@ -0,0 +1,356 @@ +# Form-Data [![NPM Module](https://img.shields.io/npm/v/form-data.svg)](https://www.npmjs.com/package/form-data) [![Join the chat at https://gitter.im/form-data/form-data](http://form-data.github.io/images/gitterbadge.svg)](https://gitter.im/form-data/form-data) + +A library to create readable ```"multipart/form-data"``` streams. Can be used to submit forms and file uploads to other web applications. + +The API of this library is inspired by the [XMLHttpRequest-2 FormData Interface][xhr2-fd]. + +[xhr2-fd]: http://dev.w3.org/2006/webapi/XMLHttpRequest-2/Overview.html#the-formdata-interface + +[![Linux Build](https://img.shields.io/travis/form-data/form-data/v3.0.1.svg?label=linux:6.x-12.x)](https://travis-ci.org/form-data/form-data) +[![MacOS Build](https://img.shields.io/travis/form-data/form-data/v3.0.1.svg?label=macos:6.x-12.x)](https://travis-ci.org/form-data/form-data) +[![Windows Build](https://img.shields.io/travis/form-data/form-data/v3.0.1.svg?label=windows:6.x-12.x)](https://travis-ci.org/form-data/form-data) + +[![Coverage Status](https://img.shields.io/coveralls/form-data/form-data/v3.0.1.svg?label=code+coverage)](https://coveralls.io/github/form-data/form-data?branch=master) +[![Dependency Status](https://img.shields.io/david/form-data/form-data.svg)](https://david-dm.org/form-data/form-data) + +## Install + +``` +npm install --save form-data +``` + +## Usage + +In this example we are constructing a form with 3 fields that contain a string, +a buffer and a file stream. + +``` javascript +var FormData = require('form-data'); +var fs = require('fs'); + +var form = new FormData(); +form.append('my_field', 'my value'); +form.append('my_buffer', new Buffer(10)); +form.append('my_file', fs.createReadStream('/foo/bar.jpg')); +``` + +Also you can use http-response stream: + +``` javascript +var FormData = require('form-data'); +var http = require('http'); + +var form = new FormData(); + +http.request('http://nodejs.org/images/logo.png', function(response) { + form.append('my_field', 'my value'); + form.append('my_buffer', new Buffer(10)); + form.append('my_logo', response); +}); +``` + +Or @mikeal's [request](https://github.com/request/request) stream: + +``` javascript +var FormData = require('form-data'); +var request = require('request'); + +var form = new FormData(); + +form.append('my_field', 'my value'); +form.append('my_buffer', new Buffer(10)); +form.append('my_logo', request('http://nodejs.org/images/logo.png')); +``` + +In order to submit this form to a web application, call ```submit(url, [callback])``` method: + +``` javascript +form.submit('http://example.org/', function(err, res) { + // res – response object (http.IncomingMessage) // + res.resume(); +}); + +``` + +For more advanced request manipulations ```submit()``` method returns ```http.ClientRequest``` object, or you can choose from one of the alternative submission methods. + +### Custom options + +You can provide custom options, such as `maxDataSize`: + +``` javascript +var FormData = require('form-data'); + +var form = new FormData({ maxDataSize: 20971520 }); +form.append('my_field', 'my value'); +form.append('my_buffer', /* something big */); +``` + +List of available options could be found in [combined-stream](https://github.com/felixge/node-combined-stream/blob/master/lib/combined_stream.js#L7-L15) + +### Alternative submission methods + +You can use node's http client interface: + +``` javascript +var http = require('http'); + +var request = http.request({ + method: 'post', + host: 'example.org', + path: '/upload', + headers: form.getHeaders() +}); + +form.pipe(request); + +request.on('response', function(res) { + console.log(res.statusCode); +}); +``` + +Or if you would prefer the `'Content-Length'` header to be set for you: + +``` javascript +form.submit('example.org/upload', function(err, res) { + console.log(res.statusCode); +}); +``` + +To use custom headers and pre-known length in parts: + +``` javascript +var CRLF = '\r\n'; +var form = new FormData(); + +var options = { + header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF, + knownLength: 1 +}; + +form.append('my_buffer', buffer, options); + +form.submit('http://example.com/', function(err, res) { + if (err) throw err; + console.log('Done'); +}); +``` + +Form-Data can recognize and fetch all the required information from common types of streams (```fs.readStream```, ```http.response``` and ```mikeal's request```), for some other types of streams you'd need to provide "file"-related information manually: + +``` javascript +someModule.stream(function(err, stdout, stderr) { + if (err) throw err; + + var form = new FormData(); + + form.append('file', stdout, { + filename: 'unicycle.jpg', // ... or: + filepath: 'photos/toys/unicycle.jpg', + contentType: 'image/jpeg', + knownLength: 19806 + }); + + form.submit('http://example.com/', function(err, res) { + if (err) throw err; + console.log('Done'); + }); +}); +``` + +The `filepath` property overrides `filename` and may contain a relative path. This is typically used when uploading [multiple files from a directory](https://wicg.github.io/entries-api/#dom-htmlinputelement-webkitdirectory). + +For edge cases, like POST request to URL with query string or to pass HTTP auth credentials, object can be passed to `form.submit()` as first parameter: + +``` javascript +form.submit({ + host: 'example.com', + path: '/probably.php?extra=params', + auth: 'username:password' +}, function(err, res) { + console.log(res.statusCode); +}); +``` + +In case you need to also send custom HTTP headers with the POST request, you can use the `headers` key in first parameter of `form.submit()`: + +``` javascript +form.submit({ + host: 'example.com', + path: '/surelynot.php', + headers: {'x-test-header': 'test-header-value'} +}, function(err, res) { + console.log(res.statusCode); +}); +``` + +### Methods + +- [_Void_ append( **String** _field_, **Mixed** _value_ [, **Mixed** _options_] )](https://github.com/form-data/form-data#void-append-string-field-mixed-value--mixed-options-). +- [_Headers_ getHeaders( [**Headers** _userHeaders_] )](https://github.com/form-data/form-data#array-getheaders-array-userheaders-) +- [_String_ getBoundary()](https://github.com/form-data/form-data#string-getboundary) +- [_Void_ setBoundary()](https://github.com/form-data/form-data#void-setboundary) +- [_Buffer_ getBuffer()](https://github.com/form-data/form-data#buffer-getbuffer) +- [_Integer_ getLengthSync()](https://github.com/form-data/form-data#integer-getlengthsync) +- [_Integer_ getLength( **function** _callback_ )](https://github.com/form-data/form-data#integer-getlength-function-callback-) +- [_Boolean_ hasKnownLength()](https://github.com/form-data/form-data#boolean-hasknownlength) +- [_Request_ submit( _params_, **function** _callback_ )](https://github.com/form-data/form-data#request-submit-params-function-callback-) +- [_String_ toString()](https://github.com/form-data/form-data#string-tostring) + +#### _Void_ append( **String** _field_, **Mixed** _value_ [, **Mixed** _options_] ) +Append data to the form. You can submit about any format (string, integer, boolean, buffer, etc.). However, Arrays are not supported and need to be turned into strings by the user. +```javascript +var form = new FormData(); +form.append( 'my_string', 'my value' ); +form.append( 'my_integer', 1 ); +form.append( 'my_boolean', true ); +form.append( 'my_buffer', new Buffer(10) ); +form.append( 'my_array_as_json', JSON.stringify( ['bird','cute'] ) ) +``` + +You may provide a string for options, or an object. +```javascript +// Set filename by providing a string for options +form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), 'bar.jpg' ); + +// provide an object. +form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), {filename: 'bar.jpg', contentType: 'image/jpeg', knownLength: 19806} ); +``` + +#### _Headers_ getHeaders( [**Headers** _userHeaders_] ) +This method adds the correct `content-type` header to the provided array of `userHeaders`. + +#### _String_ getBoundary() +Return the boundary of the formData. By default, the boundary consists of 26 `-` followed by 24 numbers +for example: +```javascript +--------------------------515890814546601021194782 +``` + +#### _Void_ setBoundary(String _boundary_) +Set the boundary string, overriding the default behavior described above. + +_Note: The boundary must be unique and may not appear in the data._ + +#### _Buffer_ getBuffer() +Return the full formdata request package, as a Buffer. You can insert this Buffer in e.g. Axios to send multipart data. +```javascript +var form = new FormData(); +form.append( 'my_buffer', Buffer.from([0x4a,0x42,0x20,0x52,0x6f,0x63,0x6b,0x73]) ); +form.append( 'my_file', fs.readFileSync('/foo/bar.jpg') ); + +axios.post( 'https://example.com/path/to/api', + form.getBuffer(), + form.getHeaders() + ) +``` +**Note:** Because the output is of type Buffer, you can only append types that are accepted by Buffer: *string, Buffer, ArrayBuffer, Array, or Array-like Object*. A ReadStream for example will result in an error. + +#### _Integer_ getLengthSync() +Same as `getLength` but synchronous. + +_Note: getLengthSync __doesn't__ calculate streams length._ + +#### _Integer_ getLength( **function** _callback_ ) +Returns the `Content-Length` async. The callback is used to handle errors and continue once the length has been calculated +```javascript +this.getLength(function(err, length) { + if (err) { + this._error(err); + return; + } + + // add content length + request.setHeader('Content-Length', length); + + ... +}.bind(this)); +``` + +#### _Boolean_ hasKnownLength() +Checks if the length of added values is known. + +#### _Request_ submit( _params_, **function** _callback_ ) +Submit the form to a web application. +```javascript +var form = new FormData(); +form.append( 'my_string', 'Hello World' ); + +form.submit( 'http://example.com/', function(err, res) { + // res – response object (http.IncomingMessage) // + res.resume(); +} ); +``` + +#### _String_ toString() +Returns the form data as a string. Don't use this if you are sending files or buffers, use `getBuffer()` instead. + +### Integration with other libraries + +#### Request + +Form submission using [request](https://github.com/request/request): + +```javascript +var formData = { + my_field: 'my_value', + my_file: fs.createReadStream(__dirname + '/unicycle.jpg'), +}; + +request.post({url:'http://service.com/upload', formData: formData}, function(err, httpResponse, body) { + if (err) { + return console.error('upload failed:', err); + } + console.log('Upload successful! Server responded with:', body); +}); +``` + +For more details see [request readme](https://github.com/request/request#multipartform-data-multipart-form-uploads). + +#### node-fetch + +You can also submit a form using [node-fetch](https://github.com/bitinn/node-fetch): + +```javascript +var form = new FormData(); + +form.append('a', 1); + +fetch('http://example.com', { method: 'POST', body: form }) + .then(function(res) { + return res.json(); + }).then(function(json) { + console.log(json); + }); +``` + +#### axios + +In Node.js you can post a file using [axios](https://github.com/axios/axios): +```javascript +const form = new FormData(); +const stream = fs.createReadStream(PATH_TO_FILE); + +form.append('image', stream); + +// In Node.js environment you need to set boundary in the header field 'Content-Type' by calling method `getHeaders` +const formHeaders = form.getHeaders(); + +axios.post('http://example.com', form, { + headers: { + ...formHeaders, + }, +}) +.then(response => response) +.catch(error => error) +``` + +## Notes + +- ```getLengthSync()``` method DOESN'T calculate length for streams, use ```knownLength``` options as workaround. +- Starting version `2.x` FormData has dropped support for `node@0.10.x`. +- Starting version `3.x` FormData has dropped support for `node@4.x`. + +## License + +Form-Data is released under the [MIT](License) license. diff --git a/node_modules/superagent/node_modules/form-data/index.d.ts b/node_modules/superagent/node_modules/form-data/index.d.ts new file mode 100644 index 000000000..295e9e9bc --- /dev/null +++ b/node_modules/superagent/node_modules/form-data/index.d.ts @@ -0,0 +1,62 @@ +// Definitions by: Carlos Ballesteros Velasco +// Leon Yu +// BendingBender +// Maple Miao + +/// +import * as stream from 'stream'; +import * as http from 'http'; + +export = FormData; + +// Extracted because @types/node doesn't export interfaces. +interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + read?(this: stream.Readable, size: number): void; + destroy?(this: stream.Readable, error: Error | null, callback: (error: Error | null) => void): void; + autoDestroy?: boolean; +} + +interface Options extends ReadableOptions { + writable?: boolean; + readable?: boolean; + dataSize?: number; + maxDataSize?: number; + pauseStreams?: boolean; +} + +declare class FormData extends stream.Readable { + constructor(options?: Options); + append(key: string, value: any, options?: FormData.AppendOptions | string): void; + getHeaders(userHeaders?: FormData.Headers): FormData.Headers; + submit( + params: string | FormData.SubmitOptions, + callback?: (error: Error | null, response: http.IncomingMessage) => void + ): http.ClientRequest; + getBuffer(): Buffer; + setBoundary(boundary: string): void; + getBoundary(): string; + getLength(callback: (err: Error | null, length: number) => void): void; + getLengthSync(): number; + hasKnownLength(): boolean; +} + +declare namespace FormData { + interface Headers { + [key: string]: any; + } + + interface AppendOptions { + header?: string | Headers; + knownLength?: number; + filename?: string; + filepath?: string; + contentType?: string; + } + + interface SubmitOptions extends http.RequestOptions { + protocol?: 'https:' | 'http:'; + } +} diff --git a/node_modules/superagent/node_modules/form-data/lib/browser.js b/node_modules/superagent/node_modules/form-data/lib/browser.js new file mode 100644 index 000000000..09e7c70e6 --- /dev/null +++ b/node_modules/superagent/node_modules/form-data/lib/browser.js @@ -0,0 +1,2 @@ +/* eslint-env browser */ +module.exports = typeof self == 'object' ? self.FormData : window.FormData; diff --git a/node_modules/superagent/node_modules/form-data/lib/form_data.js b/node_modules/superagent/node_modules/form-data/lib/form_data.js new file mode 100644 index 000000000..cf836b0b6 --- /dev/null +++ b/node_modules/superagent/node_modules/form-data/lib/form_data.js @@ -0,0 +1,498 @@ +var CombinedStream = require('combined-stream'); +var util = require('util'); +var path = require('path'); +var http = require('http'); +var https = require('https'); +var parseUrl = require('url').parse; +var fs = require('fs'); +var mime = require('mime-types'); +var asynckit = require('asynckit'); +var populate = require('./populate.js'); + +// Public API +module.exports = FormData; + +// make it a Stream +util.inherits(FormData, CombinedStream); + +/** + * Create readable "multipart/form-data" streams. + * Can be used to submit forms + * and file uploads to other web applications. + * + * @constructor + * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream + */ +function FormData(options) { + if (!(this instanceof FormData)) { + return new FormData(options); + } + + this._overheadLength = 0; + this._valueLength = 0; + this._valuesToMeasure = []; + + CombinedStream.call(this); + + options = options || {}; + for (var option in options) { + this[option] = options[option]; + } +} + +FormData.LINE_BREAK = '\r\n'; +FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; + +FormData.prototype.append = function(field, value, options) { + + options = options || {}; + + // allow filename as single option + if (typeof options == 'string') { + options = {filename: options}; + } + + var append = CombinedStream.prototype.append.bind(this); + + // all that streamy business can't handle numbers + if (typeof value == 'number') { + value = '' + value; + } + + // https://github.com/felixge/node-form-data/issues/38 + if (util.isArray(value)) { + // Please convert your array into string + // the way web server expects it + this._error(new Error('Arrays are not supported.')); + return; + } + + var header = this._multiPartHeader(field, value, options); + var footer = this._multiPartFooter(); + + append(header); + append(value); + append(footer); + + // pass along options.knownLength + this._trackLength(header, value, options); +}; + +FormData.prototype._trackLength = function(header, value, options) { + var valueLength = 0; + + // used w/ getLengthSync(), when length is known. + // e.g. for streaming directly from a remote server, + // w/ a known file a size, and not wanting to wait for + // incoming file to finish to get its size. + if (options.knownLength != null) { + valueLength += +options.knownLength; + } else if (Buffer.isBuffer(value)) { + valueLength = value.length; + } else if (typeof value === 'string') { + valueLength = Buffer.byteLength(value); + } + + this._valueLength += valueLength; + + // @check why add CRLF? does this account for custom/multiple CRLFs? + this._overheadLength += + Buffer.byteLength(header) + + FormData.LINE_BREAK.length; + + // empty or either doesn't have path or not an http response + if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) )) { + return; + } + + // no need to bother with the length + if (!options.knownLength) { + this._valuesToMeasure.push(value); + } +}; + +FormData.prototype._lengthRetriever = function(value, callback) { + + if (value.hasOwnProperty('fd')) { + + // take read range into a account + // `end` = Infinity –> read file till the end + // + // TODO: Looks like there is bug in Node fs.createReadStream + // it doesn't respect `end` options without `start` options + // Fix it when node fixes it. + // https://github.com/joyent/node/issues/7819 + if (value.end != undefined && value.end != Infinity && value.start != undefined) { + + // when end specified + // no need to calculate range + // inclusive, starts with 0 + callback(null, value.end + 1 - (value.start ? value.start : 0)); + + // not that fast snoopy + } else { + // still need to fetch file size from fs + fs.stat(value.path, function(err, stat) { + + var fileSize; + + if (err) { + callback(err); + return; + } + + // update final size based on the range options + fileSize = stat.size - (value.start ? value.start : 0); + callback(null, fileSize); + }); + } + + // or http response + } else if (value.hasOwnProperty('httpVersion')) { + callback(null, +value.headers['content-length']); + + // or request stream http://github.com/mikeal/request + } else if (value.hasOwnProperty('httpModule')) { + // wait till response come back + value.on('response', function(response) { + value.pause(); + callback(null, +response.headers['content-length']); + }); + value.resume(); + + // something else + } else { + callback('Unknown stream'); + } +}; + +FormData.prototype._multiPartHeader = function(field, value, options) { + // custom header specified (as string)? + // it becomes responsible for boundary + // (e.g. to handle extra CRLFs on .NET servers) + if (typeof options.header == 'string') { + return options.header; + } + + var contentDisposition = this._getContentDisposition(value, options); + var contentType = this._getContentType(value, options); + + var contents = ''; + var headers = { + // add custom disposition as third element or keep it two elements if not + 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), + // if no content type. allow it to be empty array + 'Content-Type': [].concat(contentType || []) + }; + + // allow custom headers. + if (typeof options.header == 'object') { + populate(headers, options.header); + } + + var header; + for (var prop in headers) { + if (!headers.hasOwnProperty(prop)) continue; + header = headers[prop]; + + // skip nullish headers. + if (header == null) { + continue; + } + + // convert all headers to arrays. + if (!Array.isArray(header)) { + header = [header]; + } + + // add non-empty headers. + if (header.length) { + contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; + } + } + + return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; +}; + +FormData.prototype._getContentDisposition = function(value, options) { + + var filename + , contentDisposition + ; + + if (typeof options.filepath === 'string') { + // custom filepath for relative paths + filename = path.normalize(options.filepath).replace(/\\/g, '/'); + } else if (options.filename || value.name || value.path) { + // custom filename take precedence + // formidable and the browser add a name property + // fs- and request- streams have path property + filename = path.basename(options.filename || value.name || value.path); + } else if (value.readable && value.hasOwnProperty('httpVersion')) { + // or try http response + filename = path.basename(value.client._httpMessage.path || ''); + } + + if (filename) { + contentDisposition = 'filename="' + filename + '"'; + } + + return contentDisposition; +}; + +FormData.prototype._getContentType = function(value, options) { + + // use custom content-type above all + var contentType = options.contentType; + + // or try `name` from formidable, browser + if (!contentType && value.name) { + contentType = mime.lookup(value.name); + } + + // or try `path` from fs-, request- streams + if (!contentType && value.path) { + contentType = mime.lookup(value.path); + } + + // or if it's http-reponse + if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { + contentType = value.headers['content-type']; + } + + // or guess it from the filepath or filename + if (!contentType && (options.filepath || options.filename)) { + contentType = mime.lookup(options.filepath || options.filename); + } + + // fallback to the default content type if `value` is not simple value + if (!contentType && typeof value == 'object') { + contentType = FormData.DEFAULT_CONTENT_TYPE; + } + + return contentType; +}; + +FormData.prototype._multiPartFooter = function() { + return function(next) { + var footer = FormData.LINE_BREAK; + + var lastPart = (this._streams.length === 0); + if (lastPart) { + footer += this._lastBoundary(); + } + + next(footer); + }.bind(this); +}; + +FormData.prototype._lastBoundary = function() { + return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; +}; + +FormData.prototype.getHeaders = function(userHeaders) { + var header; + var formHeaders = { + 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() + }; + + for (header in userHeaders) { + if (userHeaders.hasOwnProperty(header)) { + formHeaders[header.toLowerCase()] = userHeaders[header]; + } + } + + return formHeaders; +}; + +FormData.prototype.setBoundary = function(boundary) { + this._boundary = boundary; +}; + +FormData.prototype.getBoundary = function() { + if (!this._boundary) { + this._generateBoundary(); + } + + return this._boundary; +}; + +FormData.prototype.getBuffer = function() { + var dataBuffer = new Buffer.alloc( 0 ); + var boundary = this.getBoundary(); + + // Create the form content. Add Line breaks to the end of data. + for (var i = 0, len = this._streams.length; i < len; i++) { + if (typeof this._streams[i] !== 'function') { + + // Add content to the buffer. + if(Buffer.isBuffer(this._streams[i])) { + dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]); + }else { + dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]); + } + + // Add break after content. + if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) { + dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] ); + } + } + } + + // Add the footer and return the Buffer object. + return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] ); +}; + +FormData.prototype._generateBoundary = function() { + // This generates a 50 character boundary similar to those used by Firefox. + // They are optimized for boyer-moore parsing. + var boundary = '--------------------------'; + for (var i = 0; i < 24; i++) { + boundary += Math.floor(Math.random() * 10).toString(16); + } + + this._boundary = boundary; +}; + +// Note: getLengthSync DOESN'T calculate streams length +// As workaround one can calculate file size manually +// and add it as knownLength option +FormData.prototype.getLengthSync = function() { + var knownLength = this._overheadLength + this._valueLength; + + // Don't get confused, there are 3 "internal" streams for each keyval pair + // so it basically checks if there is any value added to the form + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } + + // https://github.com/form-data/form-data/issues/40 + if (!this.hasKnownLength()) { + // Some async length retrievers are present + // therefore synchronous length calculation is false. + // Please use getLength(callback) to get proper length + this._error(new Error('Cannot calculate proper length in synchronous way.')); + } + + return knownLength; +}; + +// Public API to check if length of added values is known +// https://github.com/form-data/form-data/issues/196 +// https://github.com/form-data/form-data/issues/262 +FormData.prototype.hasKnownLength = function() { + var hasKnownLength = true; + + if (this._valuesToMeasure.length) { + hasKnownLength = false; + } + + return hasKnownLength; +}; + +FormData.prototype.getLength = function(cb) { + var knownLength = this._overheadLength + this._valueLength; + + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } + + if (!this._valuesToMeasure.length) { + process.nextTick(cb.bind(this, null, knownLength)); + return; + } + + asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { + if (err) { + cb(err); + return; + } + + values.forEach(function(length) { + knownLength += length; + }); + + cb(null, knownLength); + }); +}; + +FormData.prototype.submit = function(params, cb) { + var request + , options + , defaults = {method: 'post'} + ; + + // parse provided url if it's string + // or treat it as options object + if (typeof params == 'string') { + + params = parseUrl(params); + options = populate({ + port: params.port, + path: params.pathname, + host: params.hostname, + protocol: params.protocol + }, defaults); + + // use custom params + } else { + + options = populate(params, defaults); + // if no port provided use default one + if (!options.port) { + options.port = options.protocol == 'https:' ? 443 : 80; + } + } + + // put that good code in getHeaders to some use + options.headers = this.getHeaders(params.headers); + + // https if specified, fallback to http in any other case + if (options.protocol == 'https:') { + request = https.request(options); + } else { + request = http.request(options); + } + + // get content length and fire away + this.getLength(function(err, length) { + if (err) { + this._error(err); + return; + } + + // add content length + request.setHeader('Content-Length', length); + + this.pipe(request); + if (cb) { + var onResponse; + + var callback = function (error, responce) { + request.removeListener('error', callback); + request.removeListener('response', onResponse); + + return cb.call(this, error, responce); + }; + + onResponse = callback.bind(this, null); + + request.on('error', callback); + request.on('response', onResponse); + } + }.bind(this)); + + return request; +}; + +FormData.prototype._error = function(err) { + if (!this.error) { + this.error = err; + this.pause(); + this.emit('error', err); + } +}; + +FormData.prototype.toString = function () { + return '[object FormData]'; +}; diff --git a/node_modules/superagent/node_modules/form-data/lib/populate.js b/node_modules/superagent/node_modules/form-data/lib/populate.js new file mode 100644 index 000000000..4d35738dd --- /dev/null +++ b/node_modules/superagent/node_modules/form-data/lib/populate.js @@ -0,0 +1,10 @@ +// populates missing values +module.exports = function(dst, src) { + + Object.keys(src).forEach(function(prop) + { + dst[prop] = dst[prop] || src[prop]; + }); + + return dst; +}; diff --git a/node_modules/superagent/node_modules/form-data/package.json b/node_modules/superagent/node_modules/form-data/package.json new file mode 100644 index 000000000..a2fcb88d5 --- /dev/null +++ b/node_modules/superagent/node_modules/form-data/package.json @@ -0,0 +1,68 @@ +{ + "author": "Felix Geisendörfer (http://debuggable.com/)", + "name": "form-data", + "description": "A library to create readable \"multipart/form-data\" streams. Can be used to submit forms and file uploads to other web applications.", + "version": "3.0.1", + "repository": { + "type": "git", + "url": "git://github.com/form-data/form-data.git" + }, + "main": "./lib/form_data", + "browser": "./lib/browser", + "typings": "./index.d.ts", + "scripts": { + "pretest": "rimraf coverage test/tmp", + "test": "istanbul cover test/run.js", + "posttest": "istanbul report lcov text", + "lint": "eslint lib/*.js test/*.js test/integration/*.js", + "report": "istanbul report lcov text", + "ci-lint": "is-node-modern 8 && npm run lint || is-node-not-modern 8", + "ci-test": "npm run test && npm run browser && npm run report", + "predebug": "rimraf coverage test/tmp", + "debug": "verbose=1 ./test/run.js", + "browser": "browserify -t browserify-istanbul test/run-browser.js | obake --coverage", + "check": "istanbul check-coverage coverage/coverage*.json", + "files": "pkgfiles --sort=name", + "get-version": "node -e \"console.log(require('./package.json').version)\"", + "update-readme": "sed -i.bak 's/\\/master\\.svg/\\/v'$(npm --silent run get-version)'.svg/g' README.md", + "restore-readme": "mv README.md.bak README.md", + "prepublish": "in-publish && npm run update-readme || not-in-publish", + "postpublish": "npm run restore-readme" + }, + "pre-commit": [ + "lint", + "ci-test", + "check" + ], + "engines": { + "node": ">= 6" + }, + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "devDependencies": { + "@types/node": "^12.0.10", + "browserify": "^13.1.1", + "browserify-istanbul": "^2.0.0", + "coveralls": "^3.0.4", + "cross-spawn": "^6.0.5", + "eslint": "^6.0.1", + "fake": "^0.2.2", + "far": "^0.0.7", + "formidable": "^1.0.17", + "in-publish": "^2.0.0", + "is-node-modern": "^1.0.0", + "istanbul": "^0.4.5", + "obake": "^0.1.2", + "puppeteer": "^1.19.0", + "pkgfiles": "^2.3.0", + "pre-commit": "^1.1.3", + "request": "^2.88.0", + "rimraf": "^2.7.1", + "tape": "^4.6.2", + "typescript": "^3.5.2" + }, + "license": "MIT" +} diff --git a/node_modules/superagent/node_modules/qs/.editorconfig b/node_modules/superagent/node_modules/qs/.editorconfig new file mode 100644 index 000000000..2f0844450 --- /dev/null +++ b/node_modules/superagent/node_modules/qs/.editorconfig @@ -0,0 +1,43 @@ +root = true + +[*] +indent_style = space +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 160 +quote_type = single + +[test/*] +max_line_length = off + +[LICENSE.md] +indent_size = off + +[*.md] +max_line_length = off + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[LICENSE] +indent_size = 2 +max_line_length = off + +[coverage/**/*] +indent_size = off +indent_style = off +indent = off +max_line_length = off + +[.nycrc] +indent_style = tab diff --git a/node_modules/superagent/node_modules/qs/.eslintrc b/node_modules/superagent/node_modules/qs/.eslintrc new file mode 100644 index 000000000..b6927611e --- /dev/null +++ b/node_modules/superagent/node_modules/qs/.eslintrc @@ -0,0 +1,38 @@ +{ + "root": true, + + "extends": "@ljharb", + + "ignorePatterns": [ + "dist/", + ], + + "rules": { + "complexity": 0, + "consistent-return": 1, + "func-name-matching": 0, + "id-length": [2, { "min": 1, "max": 25, "properties": "never" }], + "indent": [2, 4], + "max-lines-per-function": [2, { "max": 150 }], + "max-params": [2, 18], + "max-statements": [2, 100], + "multiline-comment-style": 0, + "no-continue": 1, + "no-magic-numbers": 0, + "no-restricted-syntax": [2, "BreakStatement", "DebuggerStatement", "ForInStatement", "LabeledStatement", "WithStatement"], + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "function-paren-newline": 0, + "max-lines-per-function": 0, + "max-statements": 0, + "no-buffer-constructor": 0, + "no-extend-native": 0, + "no-throw-literal": 0, + }, + }, + ], +} diff --git a/node_modules/superagent/node_modules/qs/.github/FUNDING.yml b/node_modules/superagent/node_modules/qs/.github/FUNDING.yml new file mode 100644 index 000000000..0355f4f5f --- /dev/null +++ b/node_modules/superagent/node_modules/qs/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/qs +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/superagent/node_modules/qs/.nycrc b/node_modules/superagent/node_modules/qs/.nycrc new file mode 100644 index 000000000..1d57cabe1 --- /dev/null +++ b/node_modules/superagent/node_modules/qs/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "dist" + ] +} diff --git a/node_modules/superagent/node_modules/qs/CHANGELOG.md b/node_modules/superagent/node_modules/qs/CHANGELOG.md new file mode 100644 index 000000000..f99fa2519 --- /dev/null +++ b/node_modules/superagent/node_modules/qs/CHANGELOG.md @@ -0,0 +1,582 @@ +## **6.12.0** + +- [New] `parse`/`stringify`: add `decodeDotInKeys`/`encodeDotKeys` options (#488) +- [New] `parse`: add `duplicates` option +- [New] `parse`/`stringify`: add `allowEmptyArrays` option to allow [] in object values (#487) +- [Refactor] `parse`/`stringify`: move allowDots config logic to its own variable +- [Refactor] `stringify`: move option-handling code into `normalizeStringifyOptions` +- [readme] update readme, add logos (#484) +- [readme] `stringify`: clarify default `arrayFormat` behavior +- [readme] fix line wrapping +- [readme] remove dead badges +- [Deps] update `side-channel` +- [meta] make the dist build 50% smaller +- [meta] add `sideEffects` flag +- [meta] run build in prepack, not prepublish +- [Tests] `parse`: remove useless tests; add coverage +- [Tests] `stringify`: increase coverage +- [Tests] use `mock-property` +- [Tests] `stringify`: improve coverage +- [Dev Deps] update `@ljharb/eslint-config `, `aud`, `has-override-mistake`, `has-property-descriptors`, `mock-property`, `npmignore`, `object-inspect`, `tape` +- [Dev Deps] pin `glob`, since v10.3.8+ requires a broken `jackspeak` +- [Dev Deps] pin `jackspeak` since 2.1.2+ depends on npm aliases, which kill the install process in npm < 6 + +## **6.11.2** +- [Fix] `parse`: Fix parsing when the global Object prototype is frozen (#473) +- [Tests] add passing test cases with empty keys (#473) + +## **6.11.1** +- [Fix] `stringify`: encode comma values more consistently (#463) +- [readme] add usage of `filter` option for injecting custom serialization, i.e. of custom types (#447) +- [meta] remove extraneous code backticks (#457) +- [meta] fix changelog markdown +- [actions] update checkout action +- [actions] restrict action permissions +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `object-inspect`, `tape` + +## **6.11.0** +- [New] [Fix] `stringify`: revert 0e903c0; add `commaRoundTrip` option (#442) +- [readme] fix version badge + +## **6.10.5** +- [Fix] `stringify`: with `arrayFormat: comma`, properly include an explicit `[]` on a single-item array (#434) + +## **6.10.4** +- [Fix] `stringify`: with `arrayFormat: comma`, include an explicit `[]` on a single-item array (#441) +- [meta] use `npmignore` to autogenerate an npmignore file +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-symbol`, `object-inspect`, `tape` + +## **6.10.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [actions] reuse common workflows +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `object-inspect`, `tape` + +## **6.10.2** +- [Fix] `stringify`: actually fix cyclic references (#426) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] add note and links for coercing primitive values (#408) +- [actions] update codecov uploader +- [actions] update workflows +- [Tests] clean up stringify tests slightly +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `object-inspect`, `safe-publish-latest`, `tape` + +## **6.10.1** +- [Fix] `stringify`: avoid exception on repeated object values (#402) + +## **6.10.0** +- [New] `stringify`: throw on cycles, instead of an infinite loop (#395, #394, #393) +- [New] `parse`: add `allowSparse` option for collapsing arrays with missing indices (#312) +- [meta] fix README.md (#399) +- [meta] only run `npm run dist` in publish, not install +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-symbols`, `tape` +- [Tests] fix tests on node v0.6 +- [Tests] use `ljharb/actions/node/install` instead of `ljharb/actions/node/run` +- [Tests] Revert "[meta] ignore eclint transitive audit warning" + +## **6.9.7** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] add note and links for coercing primitive values (#408) +- [Tests] clean up stringify tests slightly +- [meta] fix README.md (#399) +- Revert "[meta] ignore eclint transitive audit warning" +- [actions] backport actions from main +- [Dev Deps] backport updates from main + +## **6.9.6** +- [Fix] restore `dist` dir; mistakenly removed in d4f6c32 + +## **6.9.5** +- [Fix] `stringify`: do not encode parens for RFC1738 +- [Fix] `stringify`: fix arrayFormat comma with empty array/objects (#350) +- [Refactor] `format`: remove `util.assign` call +- [meta] add "Allow Edits" workflow; update rebase workflow +- [actions] switch Automatic Rebase workflow to `pull_request_target` event +- [Tests] `stringify`: add tests for #378 +- [Tests] migrate tests to Github Actions +- [Tests] run `nyc` on all tests; use `tape` runner +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `browserify`, `mkdirp`, `object-inspect`, `tape`; add `aud` + +## **6.9.4** +- [Fix] `stringify`: when `arrayFormat` is `comma`, respect `serializeDate` (#364) +- [Refactor] `stringify`: reduce branching (part of #350) +- [Refactor] move `maybeMap` to `utils` +- [Dev Deps] update `browserify`, `tape` + +## **6.9.3** +- [Fix] proper comma parsing of URL-encoded commas (#361) +- [Fix] parses comma delimited array while having percent-encoded comma treated as normal text (#336) + +## **6.9.2** +- [Fix] `parse`: Fix parsing array from object with `comma` true (#359) +- [Fix] `parse`: throw a TypeError instead of an Error for bad charset (#349) +- [meta] ignore eclint transitive audit warning +- [meta] fix indentation in package.json +- [meta] add tidelift marketing copy +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `object-inspect`, `has-symbols`, `tape`, `mkdirp`, `iconv-lite` +- [actions] add automatic rebasing / merge commit blocking + +## **6.9.1** +- [Fix] `parse`: with comma true, handle field that holds an array of arrays (#335) +- [Fix] `parse`: with comma true, do not split non-string values (#334) +- [meta] add `funding` field +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` +- [Tests] use shared travis-ci config + +## **6.9.0** +- [New] `parse`/`stringify`: Pass extra key/value argument to `decoder` (#333) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `evalmd` +- [Tests] `parse`: add passing `arrayFormat` tests +- [Tests] add `posttest` using `npx aud` to run `npm audit` without a lockfile +- [Tests] up to `node` `v12.10`, `v11.15`, `v10.16`, `v8.16` +- [Tests] `Buffer.from` in node v5.0-v5.9 and v4.0-v4.4 requires a TypedArray + +## **6.8.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Tests] clean up stringify tests slightly +- [Docs] add note and links for coercing primitive values (#408) +- [meta] fix README.md (#399) +- [actions] backport actions from main +- [Dev Deps] backport updates from main +- [Refactor] `stringify`: reduce branching +- [meta] do not publish workflow files + +## **6.8.2** +- [Fix] proper comma parsing of URL-encoded commas (#361) +- [Fix] parses comma delimited array while having percent-encoded comma treated as normal text (#336) + +## **6.8.1** +- [Fix] `parse`: Fix parsing array from object with `comma` true (#359) +- [Fix] `parse`: throw a TypeError instead of an Error for bad charset (#349) +- [Fix] `parse`: with comma true, handle field that holds an array of arrays (#335) +- [fix] `parse`: with comma true, do not split non-string values (#334) +- [meta] add tidelift marketing copy +- [meta] add `funding` field +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `safe-publish-latest`, `evalmd`, `has-symbols`, `iconv-lite`, `mkdirp`, `object-inspect` +- [Tests] `parse`: add passing `arrayFormat` tests +- [Tests] use shared travis-ci configs +- [Tests] `Buffer.from` in node v5.0-v5.9 and v4.0-v4.4 requires a TypedArray +- [actions] add automatic rebasing / merge commit blocking + +## **6.8.0** +- [New] add `depth=false` to preserve the original key; [Fix] `depth=0` should preserve the original key (#326) +- [New] [Fix] stringify symbols and bigints +- [Fix] ensure node 0.12 can stringify Symbols +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Refactor] `formats`: tiny bit of cleanup. +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `browserify`, `safe-publish-latest`, `iconv-lite`, `tape` +- [Tests] add tests for `depth=0` and `depth=false` behavior, both current and intuitive/intended (#326) +- [Tests] use `eclint` instead of `editorconfig-tools` +- [docs] readme: add security note +- [meta] add github sponsorship +- [meta] add FUNDING.yml +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause + +## **6.7.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] add note and links for coercing primitive values (#408) +- [meta] fix README.md (#399) +- [meta] do not publish workflow files +- [actions] backport actions from main +- [Dev Deps] backport updates from main +- [Tests] use `nyc` for coverage +- [Tests] clean up stringify tests slightly + +## **6.7.2** +- [Fix] proper comma parsing of URL-encoded commas (#361) +- [Fix] parses comma delimited array while having percent-encoded comma treated as normal text (#336) + +## **6.7.1** +- [Fix] `parse`: Fix parsing array from object with `comma` true (#359) +- [Fix] `parse`: with comma true, handle field that holds an array of arrays (#335) +- [fix] `parse`: with comma true, do not split non-string values (#334) +- [Fix] `parse`: throw a TypeError instead of an Error for bad charset (#349) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Refactor] `formats`: tiny bit of cleanup. +- readme: add security note +- [meta] add tidelift marketing copy +- [meta] add `funding` field +- [meta] add FUNDING.yml +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `safe-publish-latest`, `evalmd`, `iconv-lite`, `mkdirp`, `object-inspect`, `browserify` +- [Tests] `parse`: add passing `arrayFormat` tests +- [Tests] use shared travis-ci configs +- [Tests] `Buffer.from` in node v5.0-v5.9 and v4.0-v4.4 requires a TypedArray +- [Tests] add tests for `depth=0` and `depth=false` behavior, both current and intuitive/intended +- [Tests] use `eclint` instead of `editorconfig-tools` +- [actions] add automatic rebasing / merge commit blocking + +## **6.7.0** +- [New] `stringify`/`parse`: add `comma` as an `arrayFormat` option (#276, #219) +- [Fix] correctly parse nested arrays (#212) +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source, also with an array source +- [Robustness] `stringify`: cache `Object.prototype.hasOwnProperty` +- [Refactor] `utils`: `isBuffer`: small tweak; add tests +- [Refactor] use cached `Array.isArray` +- [Refactor] `parse`/`stringify`: make a function to normalize the options +- [Refactor] `utils`: reduce observable [[Get]]s +- [Refactor] `stringify`/`utils`: cache `Array.isArray` +- [Tests] always use `String(x)` over `x.toString()` +- [Tests] fix Buffer tests to work in node < 4.5 and node < 5.10 +- [Tests] temporarily allow coverage to fail + +## **6.6.1** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] correctly parse nested arrays +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Robustness] `stringify`: cache `Object.prototype.hasOwnProperty` +- [Refactor] `formats`: tiny bit of cleanup. +- [Refactor] `utils`: `isBuffer`: small tweak; add tests +- [Refactor]: `stringify`/`utils`: cache `Array.isArray` +- [Refactor] `utils`: reduce observable [[Get]]s +- [Refactor] use cached `Array.isArray` +- [Refactor] `parse`/`stringify`: make a function to normalize the options +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] do not publish workflow files +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [meta] Fixes typo in CHANGELOG.md +- [actions] backport actions from main +- [Tests] fix Buffer tests to work in node < 4.5 and node < 5.10 +- [Tests] always use `String(x)` over `x.toString()` +- [Dev Deps] backport from main + +## **6.6.0** +- [New] Add support for iso-8859-1, utf8 "sentinel" and numeric entities (#268) +- [New] move two-value combine to a `utils` function (#189) +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` (#260) +- [Fix] `stringify`: do not crash in an obscure combo of `interpretNumericEntities`, a bad custom `decoder`, & `iso-8859-1` +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [Refactor] `parse`: only need to reassign the var once +- [Refactor] `parse`/`stringify`: clean up `charset` options checking; fix defaults +- [Refactor] add missing defaults +- [Refactor] `parse`: one less `concat` call +- [Refactor] `utils`: `compactQueue`: make it explicitly side-effecting +- [Dev Deps] update `browserify`, `eslint`, `@ljharb/eslint-config`, `iconv-lite`, `safe-publish-latest`, `tape` +- [Tests] up to `node` `v10.10`, `v9.11`, `v8.12`, `v6.14`, `v4.9`; pin included builds to LTS + +## **6.5.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] correctly parse nested arrays +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Refactor] `utils`: reduce observable [[Get]]s +- [Refactor] use cached `Array.isArray` +- [Refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [Refactor] `parse`: only need to reassign the var once +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] Clean up license text so it’s properly detected as BSD-3-Clause +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] always use `String(x)` over `x.toString()` +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + +## **6.5.2** +- [Fix] use `safer-buffer` instead of `Buffer` constructor +- [Refactor] utils: `module.exports` one thing, instead of mutating `exports` (#230) +- [Dev Deps] update `browserify`, `eslint`, `iconv-lite`, `safer-buffer`, `tape`, `browserify` + +## **6.5.1** +- [Fix] Fix parsing & compacting very deep objects (#224) +- [Refactor] name utils functions +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` +- [Tests] up to `node` `v8.4`; use `nvm install-latest-npm` so newer npm doesn’t break older node +- [Tests] Use precise dist for Node.js 0.6 runtime (#225) +- [Tests] make 0.6 required, now that it’s passing +- [Tests] on `node` `v8.2`; fix npm on node 0.6 + +## **6.5.0** +- [New] add `utils.assign` +- [New] pass default encoder/decoder to custom encoder/decoder functions (#206) +- [New] `parse`/`stringify`: add `ignoreQueryPrefix`/`addQueryPrefix` options, respectively (#213) +- [Fix] Handle stringifying empty objects with addQueryPrefix (#217) +- [Fix] do not mutate `options` argument (#207) +- [Refactor] `parse`: cache index to reuse in else statement (#182) +- [Docs] add various badges to readme (#208) +- [Dev Deps] update `eslint`, `browserify`, `iconv-lite`, `tape` +- [Tests] up to `node` `v8.1`, `v7.10`, `v6.11`; npm v4.6 breaks on node < v1; npm v5+ breaks on node < v4 +- [Tests] add `editorconfig-tools` + +## **6.4.1** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] use `safer-buffer` instead of `Buffer` constructor +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Refactor] use cached `Array.isArray` +- [Refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + +## **6.4.0** +- [New] `qs.stringify`: add `encodeValuesOnly` option +- [Fix] follow `allowPrototypes` option during merge (#201, #201) +- [Fix] support keys starting with brackets (#202, #200) +- [Fix] chmod a-x +- [Dev Deps] update `eslint` +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds +- [eslint] reduce warnings + +## **6.3.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Refactor] use cached `Array.isArray` +- [Refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] use `safer-buffer` instead of `Buffer` constructor +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + +## **6.3.2** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Dev Deps] update `eslint` +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.3.1** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties (thanks, @snyk!) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `browserify`, `iconv-lite`, `qs-iconv`, `tape` +- [Tests] on all node minors; improve test matrix +- [Docs] document stringify option `allowDots` (#195) +- [Docs] add empty object and array values example (#195) +- [Docs] Fix minor inconsistency/typo (#192) +- [Docs] document stringify option `sort` (#191) +- [Refactor] `stringify`: throw faster with an invalid encoder +- [Refactor] remove unnecessary escapes (#184) +- Remove contributing.md, since `qs` is no longer part of `hapi` (#183) + +## **6.3.0** +- [New] Add support for RFC 1738 (#174, #173) +- [New] `stringify`: Add `serializeDate` option to customize Date serialization (#159) +- [Fix] ensure `utils.merge` handles merging two arrays +- [Refactor] only constructors should be capitalized +- [Refactor] capitalized var names are for constructors only +- [Refactor] avoid using a sparse array +- [Robustness] `formats`: cache `String#replace` +- [Dev Deps] update `browserify`, `eslint`, `@ljharb/eslint-config`; add `safe-publish-latest` +- [Tests] up to `node` `v6.8`, `v4.6`; improve test matrix +- [Tests] flesh out arrayLimit/arrayFormat tests (#107) +- [Tests] skip Object.create tests when null objects are not available +- [Tests] Turn on eslint for test files (#175) + +## **6.2.4** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Refactor] use cached `Array.isArray` +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] use `safer-buffer` instead of `Buffer` constructor +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + +## **6.2.3** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.2.2** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties + +## **6.2.1** +- [Fix] ensure `key[]=x&key[]&key[]=y` results in 3, not 2, values +- [Refactor] Be explicit and use `Object.prototype.hasOwnProperty.call` +- [Tests] remove `parallelshell` since it does not reliably report failures +- [Tests] up to `node` `v6.3`, `v5.12` +- [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config`, `qs-iconv` + +## [**6.2.0**](https://github.com/ljharb/qs/issues?milestone=36&state=closed) +- [New] pass Buffers to the encoder/decoder directly (#161) +- [New] add "encoder" and "decoder" options, for custom param encoding/decoding (#160) +- [Fix] fix compacting of nested sparse arrays (#150) + +## **6.1.2** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.1.1** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties + +## [**6.1.0**](https://github.com/ljharb/qs/issues?milestone=35&state=closed) +- [New] allowDots option for `stringify` (#151) +- [Fix] "sort" option should work at a depth of 3 or more (#151) +- [Fix] Restore `dist` directory; will be removed in v7 (#148) + +## **6.0.4** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.0.3** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties +- [Fix] Restore `dist` directory; will be removed in v7 (#148) + +## [**6.0.2**](https://github.com/ljharb/qs/issues?milestone=33&state=closed) +- Revert ES6 requirement and restore support for node down to v0.8. + +## [**6.0.1**](https://github.com/ljharb/qs/issues?milestone=32&state=closed) +- [**#127**](https://github.com/ljharb/qs/pull/127) Fix engines definition in package.json + +## [**6.0.0**](https://github.com/ljharb/qs/issues?milestone=31&state=closed) +- [**#124**](https://github.com/ljharb/qs/issues/124) Use ES6 and drop support for node < v4 + +## **5.2.1** +- [Fix] ensure `key[]=x&key[]&key[]=y` results in 3, not 2, values + +## [**5.2.0**](https://github.com/ljharb/qs/issues?milestone=30&state=closed) +- [**#64**](https://github.com/ljharb/qs/issues/64) Add option to sort object keys in the query string + +## [**5.1.0**](https://github.com/ljharb/qs/issues?milestone=29&state=closed) +- [**#117**](https://github.com/ljharb/qs/issues/117) make URI encoding stringified results optional +- [**#106**](https://github.com/ljharb/qs/issues/106) Add flag `skipNulls` to optionally skip null values in stringify + +## [**5.0.0**](https://github.com/ljharb/qs/issues?milestone=28&state=closed) +- [**#114**](https://github.com/ljharb/qs/issues/114) default allowDots to false +- [**#100**](https://github.com/ljharb/qs/issues/100) include dist to npm + +## [**4.0.0**](https://github.com/ljharb/qs/issues?milestone=26&state=closed) +- [**#98**](https://github.com/ljharb/qs/issues/98) make returning plain objects and allowing prototype overwriting properties optional + +## [**3.1.0**](https://github.com/ljharb/qs/issues?milestone=24&state=closed) +- [**#89**](https://github.com/ljharb/qs/issues/89) Add option to disable "Transform dot notation to bracket notation" + +## [**3.0.0**](https://github.com/ljharb/qs/issues?milestone=23&state=closed) +- [**#80**](https://github.com/ljharb/qs/issues/80) qs.parse silently drops properties +- [**#77**](https://github.com/ljharb/qs/issues/77) Perf boost +- [**#60**](https://github.com/ljharb/qs/issues/60) Add explicit option to disable array parsing +- [**#74**](https://github.com/ljharb/qs/issues/74) Bad parse when turning array into object +- [**#81**](https://github.com/ljharb/qs/issues/81) Add a `filter` option +- [**#68**](https://github.com/ljharb/qs/issues/68) Fixed issue with recursion and passing strings into objects. +- [**#66**](https://github.com/ljharb/qs/issues/66) Add mixed array and object dot notation support Closes: #47 +- [**#76**](https://github.com/ljharb/qs/issues/76) RFC 3986 +- [**#85**](https://github.com/ljharb/qs/issues/85) No equal sign +- [**#84**](https://github.com/ljharb/qs/issues/84) update license attribute + +## [**2.4.1**](https://github.com/ljharb/qs/issues?milestone=20&state=closed) +- [**#73**](https://github.com/ljharb/qs/issues/73) Property 'hasOwnProperty' of object # is not a function + +## [**2.4.0**](https://github.com/ljharb/qs/issues?milestone=19&state=closed) +- [**#70**](https://github.com/ljharb/qs/issues/70) Add arrayFormat option + +## [**2.3.3**](https://github.com/ljharb/qs/issues?milestone=18&state=closed) +- [**#59**](https://github.com/ljharb/qs/issues/59) make sure array indexes are >= 0, closes #57 +- [**#58**](https://github.com/ljharb/qs/issues/58) make qs usable for browser loader + +## [**2.3.2**](https://github.com/ljharb/qs/issues?milestone=17&state=closed) +- [**#55**](https://github.com/ljharb/qs/issues/55) allow merging a string into an object + +## [**2.3.1**](https://github.com/ljharb/qs/issues?milestone=16&state=closed) +- [**#52**](https://github.com/ljharb/qs/issues/52) Return "undefined" and "false" instead of throwing "TypeError". + +## [**2.3.0**](https://github.com/ljharb/qs/issues?milestone=15&state=closed) +- [**#50**](https://github.com/ljharb/qs/issues/50) add option to omit array indices, closes #46 + +## [**2.2.5**](https://github.com/ljharb/qs/issues?milestone=14&state=closed) +- [**#39**](https://github.com/ljharb/qs/issues/39) Is there an alternative to Buffer.isBuffer? +- [**#49**](https://github.com/ljharb/qs/issues/49) refactor utils.merge, fixes #45 +- [**#41**](https://github.com/ljharb/qs/issues/41) avoid browserifying Buffer, for #39 + +## [**2.2.4**](https://github.com/ljharb/qs/issues?milestone=13&state=closed) +- [**#38**](https://github.com/ljharb/qs/issues/38) how to handle object keys beginning with a number + +## [**2.2.3**](https://github.com/ljharb/qs/issues?milestone=12&state=closed) +- [**#37**](https://github.com/ljharb/qs/issues/37) parser discards first empty value in array +- [**#36**](https://github.com/ljharb/qs/issues/36) Update to lab 4.x + +## [**2.2.2**](https://github.com/ljharb/qs/issues?milestone=11&state=closed) +- [**#33**](https://github.com/ljharb/qs/issues/33) Error when plain object in a value +- [**#34**](https://github.com/ljharb/qs/issues/34) use Object.prototype.hasOwnProperty.call instead of obj.hasOwnProperty +- [**#24**](https://github.com/ljharb/qs/issues/24) Changelog? Semver? + +## [**2.2.1**](https://github.com/ljharb/qs/issues?milestone=10&state=closed) +- [**#32**](https://github.com/ljharb/qs/issues/32) account for circular references properly, closes #31 +- [**#31**](https://github.com/ljharb/qs/issues/31) qs.parse stackoverflow on circular objects + +## [**2.2.0**](https://github.com/ljharb/qs/issues?milestone=9&state=closed) +- [**#26**](https://github.com/ljharb/qs/issues/26) Don't use Buffer global if it's not present +- [**#30**](https://github.com/ljharb/qs/issues/30) Bug when merging non-object values into arrays +- [**#29**](https://github.com/ljharb/qs/issues/29) Don't call Utils.clone at the top of Utils.merge +- [**#23**](https://github.com/ljharb/qs/issues/23) Ability to not limit parameters? + +## [**2.1.0**](https://github.com/ljharb/qs/issues?milestone=8&state=closed) +- [**#22**](https://github.com/ljharb/qs/issues/22) Enable using a RegExp as delimiter + +## [**2.0.0**](https://github.com/ljharb/qs/issues?milestone=7&state=closed) +- [**#18**](https://github.com/ljharb/qs/issues/18) Why is there arrayLimit? +- [**#20**](https://github.com/ljharb/qs/issues/20) Configurable parametersLimit +- [**#21**](https://github.com/ljharb/qs/issues/21) make all limits optional, for #18, for #20 + +## [**1.2.2**](https://github.com/ljharb/qs/issues?milestone=6&state=closed) +- [**#19**](https://github.com/ljharb/qs/issues/19) Don't overwrite null values + +## [**1.2.1**](https://github.com/ljharb/qs/issues?milestone=5&state=closed) +- [**#16**](https://github.com/ljharb/qs/issues/16) ignore non-string delimiters +- [**#15**](https://github.com/ljharb/qs/issues/15) Close code block + +## [**1.2.0**](https://github.com/ljharb/qs/issues?milestone=4&state=closed) +- [**#12**](https://github.com/ljharb/qs/issues/12) Add optional delim argument +- [**#13**](https://github.com/ljharb/qs/issues/13) fix #11: flattened keys in array are now correctly parsed + +## [**1.1.0**](https://github.com/ljharb/qs/issues?milestone=3&state=closed) +- [**#7**](https://github.com/ljharb/qs/issues/7) Empty values of a POST array disappear after being submitted +- [**#9**](https://github.com/ljharb/qs/issues/9) Should not omit equals signs (=) when value is null +- [**#6**](https://github.com/ljharb/qs/issues/6) Minor grammar fix in README + +## [**1.0.2**](https://github.com/ljharb/qs/issues?milestone=2&state=closed) +- [**#5**](https://github.com/ljharb/qs/issues/5) array holes incorrectly copied into object on large index diff --git a/node_modules/superagent/node_modules/qs/LICENSE.md b/node_modules/superagent/node_modules/qs/LICENSE.md new file mode 100644 index 000000000..fecf6b694 --- /dev/null +++ b/node_modules/superagent/node_modules/qs/LICENSE.md @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2014, Nathan LaFreniere and other [contributors](https://github.com/ljharb/qs/graphs/contributors) +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/superagent/node_modules/qs/README.md b/node_modules/superagent/node_modules/qs/README.md new file mode 100644 index 000000000..7e40d8ade --- /dev/null +++ b/node_modules/superagent/node_modules/qs/README.md @@ -0,0 +1,697 @@ +

+ qs +

+ +# qs [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +A querystring parsing and stringifying library with some added security. + +Lead Maintainer: [Jordan Harband](https://github.com/ljharb) + +The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring). + +## Usage + +```javascript +var qs = require('qs'); +var assert = require('assert'); + +var obj = qs.parse('a=c'); +assert.deepEqual(obj, { a: 'c' }); + +var str = qs.stringify(obj); +assert.equal(str, 'a=c'); +``` + +### Parsing Objects + +[](#preventEval) +```javascript +qs.parse(string, [options]); +``` + +**qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`. +For example, the string `'foo[bar]=baz'` converts to: + +```javascript +assert.deepEqual(qs.parse('foo[bar]=baz'), { + foo: { + bar: 'baz' + } +}); +``` + +When using the `plainObjects` option the parsed value is returned as a null object, created via `Object.create(null)` and as such you should be aware that prototype methods will not exist on it and a user may set those names to whatever value they like: + +```javascript +var nullObject = qs.parse('a[hasOwnProperty]=b', { plainObjects: true }); +assert.deepEqual(nullObject, { a: { hasOwnProperty: 'b' } }); +``` + +By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use `plainObjects` as mentioned above, or set `allowPrototypes` to `true` which will allow user input to overwrite those properties. +*WARNING* It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. +Always be careful with this option. + +```javascript +var protoObject = qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }); +assert.deepEqual(protoObject, { a: { hasOwnProperty: 'b' } }); +``` + +URI encoded strings work too: + +```javascript +assert.deepEqual(qs.parse('a%5Bb%5D=c'), { + a: { b: 'c' } +}); +``` + +You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`: + +```javascript +assert.deepEqual(qs.parse('foo[bar][baz]=foobarbaz'), { + foo: { + bar: { + baz: 'foobarbaz' + } + } +}); +``` + +By default, when nesting objects **qs** will only parse up to 5 children deep. +This means if you attempt to parse a string like `'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be: + +```javascript +var expected = { + a: { + b: { + c: { + d: { + e: { + f: { + '[g][h][i]': 'j' + } + } + } + } + } + } +}; +var string = 'a[b][c][d][e][f][g][h][i]=j'; +assert.deepEqual(qs.parse(string), expected); +``` + +This depth can be overridden by passing a `depth` option to `qs.parse(string, [options])`: + +```javascript +var deep = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 }); +assert.deepEqual(deep, { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } }); +``` + +The depth limit helps mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number. + +For similar reasons, by default **qs** will only parse up to 1000 parameters. This can be overridden by passing a `parameterLimit` option: + +```javascript +var limited = qs.parse('a=b&c=d', { parameterLimit: 1 }); +assert.deepEqual(limited, { a: 'b' }); +``` + +To bypass the leading question mark, use `ignoreQueryPrefix`: + +```javascript +var prefixed = qs.parse('?a=b&c=d', { ignoreQueryPrefix: true }); +assert.deepEqual(prefixed, { a: 'b', c: 'd' }); +``` + +An optional delimiter can also be passed: + +```javascript +var delimited = qs.parse('a=b;c=d', { delimiter: ';' }); +assert.deepEqual(delimited, { a: 'b', c: 'd' }); +``` + +Delimiters can be a regular expression too: + +```javascript +var regexed = qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ }); +assert.deepEqual(regexed, { a: 'b', c: 'd', e: 'f' }); +``` + +Option `allowDots` can be used to enable dot notation: + +```javascript +var withDots = qs.parse('a.b=c', { allowDots: true }); +assert.deepEqual(withDots, { a: { b: 'c' } }); +``` + +Option `decodeDotInKeys` can be used to decode dots in keys +Note: it implies `allowDots`, so `parse` will error if you set `decodeDotInKeys` to `true`, and `allowDots` to `false`. + +```javascript +var withDots = qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe', { decodeDotInKeys: true }); +assert.deepEqual(withDots, { 'name.obj': { first: 'John', last: 'Doe' }}); +``` + +Option `allowEmptyArrays` can be used to allowing empty array values in object +```javascript +var withEmptyArrays = qs.parse('foo[]&bar=baz', { allowEmptyArrays: true }); +assert.deepEqual(withEmptyArrays, { foo: [], bar: 'baz' }); +``` + +Option `duplicates` can be used to change the behavior when duplicate keys are encountered +```javascript +assert.deepEqual(qs.parse('foo=bar&foo=baz'), { foo: ['bar', 'baz'] }); +assert.deepEqual(qs.parse('foo=bar&foo=baz', { duplicates: 'combine' }), { foo: ['bar', 'baz'] }); +assert.deepEqual(qs.parse('foo=bar&foo=baz', { duplicates: 'first' }), { foo: 'bar' }); +assert.deepEqual(qs.parse('foo=bar&foo=baz', { duplicates: 'last' }), { foo: 'baz' }); +``` + +If you have to deal with legacy browsers or services, there's also support for decoding percent-encoded octets as iso-8859-1: + +```javascript +var oldCharset = qs.parse('a=%A7', { charset: 'iso-8859-1' }); +assert.deepEqual(oldCharset, { a: '§' }); +``` + +Some services add an initial `utf8=✓` value to forms so that old Internet Explorer versions are more likely to submit the form as utf-8. +Additionally, the server can check the value against wrong encodings of the checkmark character and detect that a query string or `application/x-www-form-urlencoded` body was *not* sent as utf-8, eg. if the form had an `accept-charset` parameter or the containing page had a different character set. + +**qs** supports this mechanism via the `charsetSentinel` option. +If specified, the `utf8` parameter will be omitted from the returned object. +It will be used to switch to `iso-8859-1`/`utf-8` mode depending on how the checkmark is encoded. + +**Important**: When you specify both the `charset` option and the `charsetSentinel` option, the `charset` will be overridden when the request contains a `utf8` parameter from which the actual charset can be deduced. +In that sense the `charset` will behave as the default charset rather than the authoritative charset. + +```javascript +var detectedAsUtf8 = qs.parse('utf8=%E2%9C%93&a=%C3%B8', { + charset: 'iso-8859-1', + charsetSentinel: true +}); +assert.deepEqual(detectedAsUtf8, { a: 'ø' }); + +// Browsers encode the checkmark as ✓ when submitting as iso-8859-1: +var detectedAsIso8859_1 = qs.parse('utf8=%26%2310003%3B&a=%F8', { + charset: 'utf-8', + charsetSentinel: true +}); +assert.deepEqual(detectedAsIso8859_1, { a: 'ø' }); +``` + +If you want to decode the `&#...;` syntax to the actual character, you can specify the `interpretNumericEntities` option as well: + +```javascript +var detectedAsIso8859_1 = qs.parse('a=%26%239786%3B', { + charset: 'iso-8859-1', + interpretNumericEntities: true +}); +assert.deepEqual(detectedAsIso8859_1, { a: '☺' }); +``` + +It also works when the charset has been detected in `charsetSentinel` mode. + +### Parsing Arrays + +**qs** can also parse arrays using a similar `[]` notation: + +```javascript +var withArray = qs.parse('a[]=b&a[]=c'); +assert.deepEqual(withArray, { a: ['b', 'c'] }); +``` + +You may specify an index as well: + +```javascript +var withIndexes = qs.parse('a[1]=c&a[0]=b'); +assert.deepEqual(withIndexes, { a: ['b', 'c'] }); +``` + +Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number to create an array. +When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving their order: + +```javascript +var noSparse = qs.parse('a[1]=b&a[15]=c'); +assert.deepEqual(noSparse, { a: ['b', 'c'] }); +``` + +You may also use `allowSparse` option to parse sparse arrays: + +```javascript +var sparseArray = qs.parse('a[1]=2&a[3]=5', { allowSparse: true }); +assert.deepEqual(sparseArray, { a: [, '2', , '5'] }); +``` + +Note that an empty string is also a value, and will be preserved: + +```javascript +var withEmptyString = qs.parse('a[]=&a[]=b'); +assert.deepEqual(withEmptyString, { a: ['', 'b'] }); + +var withIndexedEmptyString = qs.parse('a[0]=b&a[1]=&a[2]=c'); +assert.deepEqual(withIndexedEmptyString, { a: ['b', '', 'c'] }); +``` + +**qs** will also limit specifying indices in an array to a maximum index of `20`. +Any array members with an index of greater than `20` will instead be converted to an object with the index as the key. +This is needed to handle cases when someone sent, for example, `a[999999999]` and it will take significant time to iterate over this huge array. + +```javascript +var withMaxIndex = qs.parse('a[100]=b'); +assert.deepEqual(withMaxIndex, { a: { '100': 'b' } }); +``` + +This limit can be overridden by passing an `arrayLimit` option: + +```javascript +var withArrayLimit = qs.parse('a[1]=b', { arrayLimit: 0 }); +assert.deepEqual(withArrayLimit, { a: { '1': 'b' } }); +``` + +To disable array parsing entirely, set `parseArrays` to `false`. + +```javascript +var noParsingArrays = qs.parse('a[]=b', { parseArrays: false }); +assert.deepEqual(noParsingArrays, { a: { '0': 'b' } }); +``` + +If you mix notations, **qs** will merge the two items into an object: + +```javascript +var mixedNotation = qs.parse('a[0]=b&a[b]=c'); +assert.deepEqual(mixedNotation, { a: { '0': 'b', b: 'c' } }); +``` + +You can also create arrays of objects: + +```javascript +var arraysOfObjects = qs.parse('a[][b]=c'); +assert.deepEqual(arraysOfObjects, { a: [{ b: 'c' }] }); +``` + +Some people use comma to join array, **qs** can parse it: +```javascript +var arraysOfObjects = qs.parse('a=b,c', { comma: true }) +assert.deepEqual(arraysOfObjects, { a: ['b', 'c'] }) +``` +(_this cannot convert nested objects, such as `a={b:1},{c:d}`_) + +### Parsing primitive/scalar values (numbers, booleans, null, etc) + +By default, all values are parsed as strings. +This behavior will not change and is explained in [issue #91](https://github.com/ljharb/qs/issues/91). + +```javascript +var primitiveValues = qs.parse('a=15&b=true&c=null'); +assert.deepEqual(primitiveValues, { a: '15', b: 'true', c: 'null' }); +``` + +If you wish to auto-convert values which look like numbers, booleans, and other values into their primitive counterparts, you can use the [query-types Express JS middleware](https://github.com/xpepermint/query-types) which will auto-convert all request query parameters. + +### Stringifying + +[](#preventEval) +```javascript +qs.stringify(object, [options]); +``` + +When stringifying, **qs** by default URI encodes output. Objects are stringified as you would expect: + +```javascript +assert.equal(qs.stringify({ a: 'b' }), 'a=b'); +assert.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); +``` + +This encoding can be disabled by setting the `encode` option to `false`: + +```javascript +var unencoded = qs.stringify({ a: { b: 'c' } }, { encode: false }); +assert.equal(unencoded, 'a[b]=c'); +``` + +Encoding can be disabled for keys by setting the `encodeValuesOnly` option to `true`: +```javascript +var encodedValues = qs.stringify( + { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, + { encodeValuesOnly: true } +); +assert.equal(encodedValues,'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h'); +``` + +This encoding can also be replaced by a custom encoding method set as `encoder` option: + +```javascript +var encoded = qs.stringify({ a: { b: 'c' } }, { encoder: function (str) { + // Passed in values `a`, `b`, `c` + return // Return encoded string +}}) +``` + +_(Note: the `encoder` option does not apply if `encode` is `false`)_ + +Analogue to the `encoder` there is a `decoder` option for `parse` to override decoding of properties and values: + +```javascript +var decoded = qs.parse('x=z', { decoder: function (str) { + // Passed in values `x`, `z` + return // Return decoded string +}}) +``` + +You can encode keys and values using different logic by using the type argument provided to the encoder: + +```javascript +var encoded = qs.stringify({ a: { b: 'c' } }, { encoder: function (str, defaultEncoder, charset, type) { + if (type === 'key') { + return // Encoded key + } else if (type === 'value') { + return // Encoded value + } +}}) +``` + +The type argument is also provided to the decoder: + +```javascript +var decoded = qs.parse('x=z', { decoder: function (str, defaultDecoder, charset, type) { + if (type === 'key') { + return // Decoded key + } else if (type === 'value') { + return // Decoded value + } +}}) +``` + +Examples beyond this point will be shown as though the output is not URI encoded for clarity. +Please note that the return values in these cases *will* be URI encoded during real usage. + +When arrays are stringified, they follow the `arrayFormat` option, which defaults to `indices`: + +```javascript +qs.stringify({ a: ['b', 'c', 'd'] }); +// 'a[0]=b&a[1]=c&a[2]=d' +``` + +You may override this by setting the `indices` option to `false`, or to be more explicit, the `arrayFormat` option to `repeat`: + +```javascript +qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }); +// 'a=b&a=c&a=d' +``` + +You may use the `arrayFormat` option to specify the format of the output array: + +```javascript +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }) +// 'a[0]=b&a[1]=c' +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }) +// 'a[]=b&a[]=c' +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }) +// 'a=b&a=c' +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'comma' }) +// 'a=b,c' +``` + +Note: when using `arrayFormat` set to `'comma'`, you can also pass the `commaRoundTrip` option set to `true` or `false`, to append `[]` on single-item arrays, so that they can round trip through a parse. + +When objects are stringified, by default they use bracket notation: + +```javascript +qs.stringify({ a: { b: { c: 'd', e: 'f' } } }); +// 'a[b][c]=d&a[b][e]=f' +``` + +You may override this to use dot notation by setting the `allowDots` option to `true`: + +```javascript +qs.stringify({ a: { b: { c: 'd', e: 'f' } } }, { allowDots: true }); +// 'a.b.c=d&a.b.e=f' +``` + +You may encode the dot notation in the keys of object with option `encodeDotInKeys` by setting it to `true`: +Note: it implies `allowDots`, so `stringify` will error if you set `decodeDotInKeys` to `true`, and `allowDots` to `false`. +Caveat: when `encodeValuesOnly` is `true` as well as `encodeDotInKeys`, only dots in keys and nothing else will be encoded. +```javascript +qs.stringify({ "name.obj": { "first": "John", "last": "Doe" } }, { allowDots: true, encodeDotInKeys: true }) +// 'name%252Eobj.first=John&name%252Eobj.last=Doe' +``` + +You may allow empty array values by setting the `allowEmptyArrays` option to `true`: +```javascript +qs.stringify({ foo: [], bar: 'baz' }, { allowEmptyArrays: true }); +// 'foo[]&bar=baz' +``` + +Empty strings and null values will omit the value, but the equals sign (=) remains in place: + +```javascript +assert.equal(qs.stringify({ a: '' }), 'a='); +``` + +Key with no values (such as an empty object or array) will return nothing: + +```javascript +assert.equal(qs.stringify({ a: [] }), ''); +assert.equal(qs.stringify({ a: {} }), ''); +assert.equal(qs.stringify({ a: [{}] }), ''); +assert.equal(qs.stringify({ a: { b: []} }), ''); +assert.equal(qs.stringify({ a: { b: {}} }), ''); +``` + +Properties that are set to `undefined` will be omitted entirely: + +```javascript +assert.equal(qs.stringify({ a: null, b: undefined }), 'a='); +``` + +The query string may optionally be prepended with a question mark: + +```javascript +assert.equal(qs.stringify({ a: 'b', c: 'd' }, { addQueryPrefix: true }), '?a=b&c=d'); +``` + +The delimiter may be overridden with stringify as well: + +```javascript +assert.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d'); +``` + +If you only want to override the serialization of `Date` objects, you can provide a `serializeDate` option: + +```javascript +var date = new Date(7); +assert.equal(qs.stringify({ a: date }), 'a=1970-01-01T00:00:00.007Z'.replace(/:/g, '%3A')); +assert.equal( + qs.stringify({ a: date }, { serializeDate: function (d) { return d.getTime(); } }), + 'a=7' +); +``` + +You may use the `sort` option to affect the order of parameter keys: + +```javascript +function alphabeticalSort(a, b) { + return a.localeCompare(b); +} +assert.equal(qs.stringify({ a: 'c', z: 'y', b : 'f' }, { sort: alphabeticalSort }), 'a=c&b=f&z=y'); +``` + +Finally, you can use the `filter` option to restrict which keys will be included in the stringified output. +If you pass a function, it will be called for each key to obtain the replacement value. +Otherwise, if you pass an array, it will be used to select properties and array indices for stringification: + +```javascript +function filterFunc(prefix, value) { + if (prefix == 'b') { + // Return an `undefined` value to omit a property. + return; + } + if (prefix == 'e[f]') { + return value.getTime(); + } + if (prefix == 'e[g][0]') { + return value * 2; + } + return value; +} +qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc }); +// 'a=b&c=d&e[f]=123&e[g][0]=4' +qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] }); +// 'a=b&e=f' +qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] }); +// 'a[0]=b&a[2]=d' +``` + +You could also use `filter` to inject custom serialization for user defined types. +Consider you're working with some api that expects query strings of the format for ranges: + +``` +https://domain.com/endpoint?range=30...70 +``` + +For which you model as: + +```javascript +class Range { + constructor(from, to) { + this.from = from; + this.to = to; + } +} +``` + +You could _inject_ a custom serializer to handle values of this type: + +```javascript +qs.stringify( + { + range: new Range(30, 70), + }, + { + filter: (prefix, value) => { + if (value instanceof Range) { + return `${value.from}...${value.to}`; + } + // serialize the usual way + return value; + }, + } +); +// range=30...70 +``` + +### Handling of `null` values + +By default, `null` values are treated like empty strings: + +```javascript +var withNull = qs.stringify({ a: null, b: '' }); +assert.equal(withNull, 'a=&b='); +``` + +Parsing does not distinguish between parameters with and without equal signs. +Both are converted to empty strings. + +```javascript +var equalsInsensitive = qs.parse('a&b='); +assert.deepEqual(equalsInsensitive, { a: '', b: '' }); +``` + +To distinguish between `null` values and empty strings use the `strictNullHandling` flag. In the result string the `null` +values have no `=` sign: + +```javascript +var strictNull = qs.stringify({ a: null, b: '' }, { strictNullHandling: true }); +assert.equal(strictNull, 'a&b='); +``` + +To parse values without `=` back to `null` use the `strictNullHandling` flag: + +```javascript +var parsedStrictNull = qs.parse('a&b=', { strictNullHandling: true }); +assert.deepEqual(parsedStrictNull, { a: null, b: '' }); +``` + +To completely skip rendering keys with `null` values, use the `skipNulls` flag: + +```javascript +var nullsSkipped = qs.stringify({ a: 'b', c: null}, { skipNulls: true }); +assert.equal(nullsSkipped, 'a=b'); +``` + +If you're communicating with legacy systems, you can switch to `iso-8859-1` using the `charset` option: + +```javascript +var iso = qs.stringify({ æ: 'æ' }, { charset: 'iso-8859-1' }); +assert.equal(iso, '%E6=%E6'); +``` + +Characters that don't exist in `iso-8859-1` will be converted to numeric entities, similar to what browsers do: + +```javascript +var numeric = qs.stringify({ a: '☺' }, { charset: 'iso-8859-1' }); +assert.equal(numeric, 'a=%26%239786%3B'); +``` + +You can use the `charsetSentinel` option to announce the character by including an `utf8=✓` parameter with the proper encoding if the checkmark, similar to what Ruby on Rails and others do when submitting forms. + +```javascript +var sentinel = qs.stringify({ a: '☺' }, { charsetSentinel: true }); +assert.equal(sentinel, 'utf8=%E2%9C%93&a=%E2%98%BA'); + +var isoSentinel = qs.stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'iso-8859-1' }); +assert.equal(isoSentinel, 'utf8=%26%2310003%3B&a=%E6'); +``` + +### Dealing with special character sets + +By default the encoding and decoding of characters is done in `utf-8`, and `iso-8859-1` support is also built in via the `charset` parameter. + +If you wish to encode querystrings to a different character set (i.e. +[Shift JIS](https://en.wikipedia.org/wiki/Shift_JIS)) you can use the +[`qs-iconv`](https://github.com/martinheidegger/qs-iconv) library: + +```javascript +var encoder = require('qs-iconv/encoder')('shift_jis'); +var shiftJISEncoded = qs.stringify({ a: 'こんにちは!' }, { encoder: encoder }); +assert.equal(shiftJISEncoded, 'a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I'); +``` + +This also works for decoding of query strings: + +```javascript +var decoder = require('qs-iconv/decoder')('shift_jis'); +var obj = qs.parse('a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I', { decoder: decoder }); +assert.deepEqual(obj, { a: 'こんにちは!' }); +``` + +### RFC 3986 and RFC 1738 space encoding + +RFC3986 used as default option and encodes ' ' to *%20* which is backward compatible. +In the same time, output can be stringified as per RFC1738 with ' ' equal to '+'. + +``` +assert.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); +assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC3986' }), 'a=b%20c'); +assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC1738' }), 'a=b+c'); +``` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +## qs for enterprise + +Available as part of the Tidelift Subscription + +The maintainers of qs and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. +Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. +[Learn more.](https://tidelift.com/subscription/pkg/npm-qs?utm_source=npm-qs&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + +[package-url]: https://npmjs.org/package/qs +[npm-version-svg]: https://versionbadg.es/ljharb/qs.svg +[deps-svg]: https://david-dm.org/ljharb/qs.svg +[deps-url]: https://david-dm.org/ljharb/qs +[dev-deps-svg]: https://david-dm.org/ljharb/qs/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/qs#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/qs.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/qs.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/qs.svg +[downloads-url]: https://npm-stat.com/charts.html?package=qs +[codecov-image]: https://codecov.io/gh/ljharb/qs/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/qs/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/qs +[actions-url]: https://github.com/ljharb/qs/actions + +## Acknowledgements + +qs logo by [NUMI](https://github.com/numi-hq/open-design): + +[NUMI Logo](https://numi.tech/?ref=qs) diff --git a/node_modules/superagent/node_modules/qs/dist/qs.js b/node_modules/superagent/node_modules/qs/dist/qs.js new file mode 100644 index 000000000..7fd3dd6f9 --- /dev/null +++ b/node_modules/superagent/node_modules/qs/dist/qs.js @@ -0,0 +1,90 @@ +(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.Qs = 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-1?e.split(","):e},isoSentinel="utf8=%26%2310003%3B",charsetSentinel="utf8=%E2%9C%93",parseValues=function parseQueryStringValues(e,t){var r,a={__proto__:null},o=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,i=t.parameterLimit===1/0?void 0:t.parameterLimit,l=o.split(t.delimiter,i),s=-1,n=t.charset;if(t.charsetSentinel)for(r=0;r-1&&(c=isArray(c)?[c]:c);var f=has.call(a,p);f&&"combine"===t.duplicates?a[p]=utils.combine(a[p],c):f&&"last"!==t.duplicates||(a[p]=c)}return a},parseObject=function(e,t,r,a){for(var o=a?t:parseArrayValue(t,r),i=e.length-1;i>=0;--i){var l,s=e[i];if("[]"===s&&r.parseArrays)l=r.allowEmptyArrays&&""===o?[]:[].concat(o);else{l=r.plainObjects?Object.create(null):{};var n="["===s.charAt(0)&&"]"===s.charAt(s.length-1)?s.slice(1,-1):s,p=r.decodeDotInKeys?n.replace(/%2E/g,"."):n,c=parseInt(p,10);r.parseArrays||""!==p?!isNaN(c)&&s!==p&&String(c)===p&&c>=0&&r.parseArrays&&c<=r.arrayLimit?(l=[])[c]=o:"__proto__"!==p&&(l[p]=o):l={0:o}}o=l}return o},parseKeys=function parseQueryStringKeys(e,t,r,a){if(e){var o=r.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,i=/(\[[^[\]]*])/g,l=r.depth>0&&/(\[[^[\]]*])/.exec(o),s=l?o.slice(0,l.index):o,n=[];if(s){if(!r.plainObjects&&has.call(Object.prototype,s)&&!r.allowPrototypes)return;n.push(s)}for(var p=0;r.depth>0&&null!==(l=i.exec(o))&&p0?w.join(",")||null:void 0}];else if(isArray(f))E=f;else{var S=Object.keys(w);E=u?S.sort(u):S}var O=l?r.replace(/\./g,"%2E"):r,T=o&&isArray(w)&&1===w.length?O+"[]":O;if(a&&isArray(w)&&0===w.length)return T+"[]";for(var k=0;k0?y+d:""}; + +},{"1":1,"29":29,"5":5}],5:[function(require,module,exports){ +"use strict";var formats=require(1),has=Object.prototype.hasOwnProperty,isArray=Array.isArray,hexTable=function(){for(var e=[],r=0;r<256;++r)e.push("%"+((r<16?"0":"")+r.toString(16)).toUpperCase());return e}(),compactQueue=function compactQueue(e){for(;e.length>1;){var r=e.pop(),t=r.obj[r.prop];if(isArray(t)){for(var o=[],a=0;a=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||a===formats.RFC1738&&(40===u||41===u)?n+=c.charAt(i):u<128?n+=hexTable[u]:u<2048?n+=hexTable[192|u>>6]+hexTable[128|63&u]:u<55296||u>=57344?n+=hexTable[224|u>>12]+hexTable[128|u>>6&63]+hexTable[128|63&u]:(i+=1,u=65536+((1023&u)<<10|1023&c.charCodeAt(i)),n+=hexTable[240|u>>18]+hexTable[128|u>>12&63]+hexTable[128|u>>6&63]+hexTable[128|63&u])}return n},compact=function compact(e){for(var r=[{obj:{o:e},prop:"o"}],t=[],o=0;o-1?callBind(t):t}; + +},{"20":20,"8":8}],20:[function(require,module,exports){ +"use strict";var undefined,$Error=require(12),$EvalError=require(11),$RangeError=require(13),$ReferenceError=require(14),$SyntaxError=require(15),$TypeError=require(16),$URIError=require(17),$Function=Function,getEvalledConstructor=function(r){try{return $Function('"use strict"; return ('+r+").constructor;")()}catch(r){}},$gOPD=Object.getOwnPropertyDescriptor;if($gOPD)try{$gOPD({},"")}catch(r){$gOPD=null}var throwTypeError=function(){throw new $TypeError},ThrowTypeError=$gOPD?function(){try{return throwTypeError}catch(r){try{return $gOPD(arguments,"callee").get}catch(r){return throwTypeError}}}():throwTypeError,hasSymbols=require(24)(),hasProto=require(23)(),getProto=Object.getPrototypeOf||(hasProto?function(r){return r.__proto__}:null),needsEval={},TypedArray="undefined"!=typeof Uint8Array&&getProto?getProto(Uint8Array):undefined,INTRINSICS={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?undefined:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?undefined:ArrayBuffer,"%ArrayIteratorPrototype%":hasSymbols&&getProto?getProto([][Symbol.iterator]()):undefined,"%AsyncFromSyncIteratorPrototype%":undefined,"%AsyncFunction%":needsEval,"%AsyncGenerator%":needsEval,"%AsyncGeneratorFunction%":needsEval,"%AsyncIteratorPrototype%":needsEval,"%Atomics%":"undefined"==typeof Atomics?undefined:Atomics,"%BigInt%":"undefined"==typeof BigInt?undefined:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?undefined:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?undefined:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?undefined:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":$Error,"%eval%":eval,"%EvalError%":$EvalError,"%Float32Array%":"undefined"==typeof Float32Array?undefined:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?undefined:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?undefined:FinalizationRegistry,"%Function%":$Function,"%GeneratorFunction%":needsEval,"%Int8Array%":"undefined"==typeof Int8Array?undefined:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?undefined:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?undefined:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":hasSymbols&&getProto?getProto(getProto([][Symbol.iterator]())):undefined,"%JSON%":"object"==typeof JSON?JSON:undefined,"%Map%":"undefined"==typeof Map?undefined:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&hasSymbols&&getProto?getProto((new Map)[Symbol.iterator]()):undefined,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?undefined:Promise,"%Proxy%":"undefined"==typeof Proxy?undefined:Proxy,"%RangeError%":$RangeError,"%ReferenceError%":$ReferenceError,"%Reflect%":"undefined"==typeof Reflect?undefined:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?undefined:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&hasSymbols&&getProto?getProto((new Set)[Symbol.iterator]()):undefined,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?undefined:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":hasSymbols&&getProto?getProto(""[Symbol.iterator]()):undefined,"%Symbol%":hasSymbols?Symbol:undefined,"%SyntaxError%":$SyntaxError,"%ThrowTypeError%":ThrowTypeError,"%TypedArray%":TypedArray,"%TypeError%":$TypeError,"%Uint8Array%":"undefined"==typeof Uint8Array?undefined:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?undefined:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?undefined:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?undefined:Uint32Array,"%URIError%":$URIError,"%WeakMap%":"undefined"==typeof WeakMap?undefined:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?undefined:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?undefined:WeakSet};if(getProto)try{null.error}catch(r){var errorProto=getProto(getProto(r));INTRINSICS["%Error.prototype%"]=errorProto}var doEval=function doEval(r){var e;if("%AsyncFunction%"===r)e=getEvalledConstructor("async function () {}");else if("%GeneratorFunction%"===r)e=getEvalledConstructor("function* () {}");else if("%AsyncGeneratorFunction%"===r)e=getEvalledConstructor("async function* () {}");else if("%AsyncGenerator%"===r){var t=doEval("%AsyncGeneratorFunction%");t&&(e=t.prototype)}else if("%AsyncIteratorPrototype%"===r){var o=doEval("%AsyncGenerator%");o&&getProto&&(e=getProto(o.prototype))}return INTRINSICS[r]=e,e},LEGACY_ALIASES={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},bind=require(19),hasOwn=require(26),$concat=bind.call(Function.call,Array.prototype.concat),$spliceApply=bind.call(Function.apply,Array.prototype.splice),$replace=bind.call(Function.call,String.prototype.replace),$strSlice=bind.call(Function.call,String.prototype.slice),$exec=bind.call(Function.call,RegExp.prototype.exec),rePropName=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,reEscapeChar=/\\(\\)?/g,stringToPath=function stringToPath(r){var e=$strSlice(r,0,1),t=$strSlice(r,-1);if("%"===e&&"%"!==t)throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");if("%"===t&&"%"!==e)throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");var o=[];return $replace(r,rePropName,(function(r,e,t,n){o[o.length]=t?$replace(n,reEscapeChar,"$1"):e||r})),o},getBaseIntrinsic=function getBaseIntrinsic(r,e){var t,o=r;if(hasOwn(LEGACY_ALIASES,o)&&(o="%"+(t=LEGACY_ALIASES[o])[0]+"%"),hasOwn(INTRINSICS,o)){var n=INTRINSICS[o];if(n===needsEval&&(n=doEval(o)),void 0===n&&!e)throw new $TypeError("intrinsic "+r+" exists, but is not available. Please file an issue!");return{alias:t,name:o,value:n}}throw new $SyntaxError("intrinsic "+r+" does not exist!")};module.exports=function GetIntrinsic(r,e){if("string"!=typeof r||0===r.length)throw new $TypeError("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof e)throw new $TypeError('"allowMissing" argument must be a boolean');if(null===$exec(/^%?[^%]*%?$/,r))throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var t=stringToPath(r),o=t.length>0?t[0]:"",n=getBaseIntrinsic("%"+o+"%",e),a=n.name,y=n.value,i=!1,p=n.alias;p&&(o=p[0],$spliceApply(t,$concat([0,1],p)));for(var d=1,s=!0;d=t.length){var c=$gOPD(y,f);y=(s=!!c)&&"get"in c&&!("originalValue"in c.get)?c.get:y[f]}else s=hasOwn(y,f),y=y[f];s&&!i&&(INTRINSICS[a]=y)}}return y}; + +},{"11":11,"12":12,"13":13,"14":14,"15":15,"16":16,"17":17,"19":19,"23":23,"24":24,"26":26}],8:[function(require,module,exports){ +"use strict";var bind=require(19),GetIntrinsic=require(20),setFunctionLength=require(28),$TypeError=require(16),$apply=GetIntrinsic("%Function.prototype.apply%"),$call=GetIntrinsic("%Function.prototype.call%"),$reflectApply=GetIntrinsic("%Reflect.apply%",!0)||bind.call($call,$apply),$defineProperty=require(10),$max=GetIntrinsic("%Math.max%");module.exports=function callBind(e){if("function"!=typeof e)throw new $TypeError("a function is required");var n=$reflectApply(bind,$call,arguments);return setFunctionLength(n,1+$max(0,e.length-(arguments.length-1)),!0)};var applyBind=function applyBind(){return $reflectApply(bind,$apply,arguments)};$defineProperty?$defineProperty(module.exports,"apply",{value:applyBind}):module.exports.apply=applyBind; + +},{"10":10,"16":16,"19":19,"20":20,"28":28}],16:[function(require,module,exports){ +"use strict";module.exports=TypeError; + +},{}],19:[function(require,module,exports){ +"use strict";var implementation=require(18);module.exports=Function.prototype.bind||implementation; + +},{"18":18}],10:[function(require,module,exports){ +"use strict";var GetIntrinsic=require(20),$defineProperty=GetIntrinsic("%Object.defineProperty%",!0)||!1;if($defineProperty)try{$defineProperty({},"a",{value:1})}catch(e){$defineProperty=!1}module.exports=$defineProperty; + +},{"20":20}],28:[function(require,module,exports){ +"use strict";var GetIntrinsic=require(20),define=require(9),hasDescriptors=require(22)(),gOPD=require(21),$TypeError=require(16),$floor=GetIntrinsic("%Math.floor%");module.exports=function setFunctionLength(e,r){if("function"!=typeof e)throw new $TypeError("`fn` is not a function");if("number"!=typeof r||r<0||r>4294967295||$floor(r)!==r)throw new $TypeError("`length` must be a positive 32-bit integer");var t=arguments.length>2&&!!arguments[2],i=!0,n=!0;if("length"in e&&gOPD){var o=gOPD(e,"length");o&&!o.configurable&&(i=!1),o&&!o.writable&&(n=!1)}return(i||n||!t)&&(hasDescriptors?define(e,"length",r,!0,!0):define(e,"length",r)),e}; + +},{"16":16,"20":20,"21":21,"22":22,"9":9}],9:[function(require,module,exports){ +"use strict";var $defineProperty=require(10),$SyntaxError=require(15),$TypeError=require(16),gopd=require(21);module.exports=function defineDataProperty(e,r,o){if(!e||"object"!=typeof e&&"function"!=typeof e)throw new $TypeError("`obj` must be an object or a function`");if("string"!=typeof r&&"symbol"!=typeof r)throw new $TypeError("`property` must be a string or a symbol`");if(arguments.length>3&&"boolean"!=typeof arguments[3]&&null!==arguments[3])throw new $TypeError("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&"boolean"!=typeof arguments[4]&&null!==arguments[4])throw new $TypeError("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&"boolean"!=typeof arguments[5]&&null!==arguments[5])throw new $TypeError("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&"boolean"!=typeof arguments[6])throw new $TypeError("`loose`, if provided, must be a boolean");var n=arguments.length>3?arguments[3]:null,l=arguments.length>4?arguments[4]:null,t=arguments.length>5?arguments[5]:null,i=arguments.length>6&&arguments[6],a=!!gopd&&gopd(e,r);if($defineProperty)$defineProperty(e,r,{configurable:null===t&&a?a.configurable:!t,enumerable:null===n&&a?a.enumerable:!n,value:o,writable:null===l&&a?a.writable:!l});else{if(!i&&(n||l||t))throw new $SyntaxError("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");e[r]=o}}; + +},{"10":10,"15":15,"16":16,"21":21}],15:[function(require,module,exports){ +"use strict";module.exports=SyntaxError; + +},{}],21:[function(require,module,exports){ +"use strict";var GetIntrinsic=require(20),$gOPD=GetIntrinsic("%Object.getOwnPropertyDescriptor%",!0);if($gOPD)try{$gOPD([],"length")}catch(t){$gOPD=null}module.exports=$gOPD; + +},{"20":20}],11:[function(require,module,exports){ +"use strict";module.exports=EvalError; + +},{}],12:[function(require,module,exports){ +"use strict";module.exports=Error; + +},{}],13:[function(require,module,exports){ +"use strict";module.exports=RangeError; + +},{}],14:[function(require,module,exports){ +"use strict";module.exports=ReferenceError; + +},{}],17:[function(require,module,exports){ +"use strict";module.exports=URIError; + +},{}],18:[function(require,module,exports){ +"use strict";var ERROR_MESSAGE="Function.prototype.bind called on incompatible ",toStr=Object.prototype.toString,max=Math.max,funcType="[object Function]",concatty=function concatty(t,n){for(var r=[],o=0;o-1e3&&t<1e3||$test.call(/e/,e))return e;var r=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof t){var n=t<0?-$floor(-t):$floor(t);if(n!==t){var o=String(n),i=$slice.call(e,o.length+1);return $replace.call(o,r,"$&_")+"."+$replace.call($replace.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return $replace.call(e,r,"$&_")}var utilInspect=require(6),inspectCustom=utilInspect.custom,inspectSymbol=isSymbol(inspectCustom)?inspectCustom:null;function wrapQuotes(t,e,r){var n="double"===(r.quoteStyle||e)?'"':"'";return n+t+n}function quote(t){return $replace.call(String(t),/"/g,""")}function isArray(t){return!("[object Array]"!==toStr(t)||toStringTag&&"object"==typeof t&&toStringTag in t)}function isDate(t){return!("[object Date]"!==toStr(t)||toStringTag&&"object"==typeof t&&toStringTag in t)}function isRegExp(t){return!("[object RegExp]"!==toStr(t)||toStringTag&&"object"==typeof t&&toStringTag in t)}function isError(t){return!("[object Error]"!==toStr(t)||toStringTag&&"object"==typeof t&&toStringTag in t)}function isString(t){return!("[object String]"!==toStr(t)||toStringTag&&"object"==typeof t&&toStringTag in t)}function isNumber(t){return!("[object Number]"!==toStr(t)||toStringTag&&"object"==typeof t&&toStringTag in t)}function isBoolean(t){return!("[object Boolean]"!==toStr(t)||toStringTag&&"object"==typeof t&&toStringTag in t)}function isSymbol(t){if(hasShammedSymbols)return t&&"object"==typeof t&&t instanceof Symbol;if("symbol"==typeof t)return!0;if(!t||"object"!=typeof t||!symToString)return!1;try{return symToString.call(t),!0}catch(t){}return!1}function isBigInt(t){if(!t||"object"!=typeof t||!bigIntValueOf)return!1;try{return bigIntValueOf.call(t),!0}catch(t){}return!1}module.exports=function inspect_(t,e,r,n){var o=e||{};if(has(o,"quoteStyle")&&"single"!==o.quoteStyle&&"double"!==o.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(has(o,"maxStringLength")&&("number"==typeof o.maxStringLength?o.maxStringLength<0&&o.maxStringLength!==1/0:null!==o.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var i=!has(o,"customInspect")||o.customInspect;if("boolean"!=typeof i&&"symbol"!==i)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(has(o,"indent")&&null!==o.indent&&"\t"!==o.indent&&!(parseInt(o.indent,10)===o.indent&&o.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(has(o,"numericSeparator")&&"boolean"!=typeof o.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var a=o.numericSeparator;if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return inspectString(t,o);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var c=String(t);return a?addNumericSeparator(t,c):c}if("bigint"==typeof t){var l=String(t)+"n";return a?addNumericSeparator(t,l):l}var p=void 0===o.depth?5:o.depth;if(void 0===r&&(r=0),r>=p&&p>0&&"object"==typeof t)return isArray(t)?"[Array]":"[Object]";var u=getIndent(o,r);if(void 0===n)n=[];else if(indexOf(n,t)>=0)return"[Circular]";function inspect(t,e,i){if(e&&(n=$arrSlice.call(n)).push(e),i){var a={depth:o.depth};return has(o,"quoteStyle")&&(a.quoteStyle=o.quoteStyle),inspect_(t,a,r+1,n)}return inspect_(t,o,r+1,n)}if("function"==typeof t&&!isRegExp(t)){var s=nameOf(t),f=arrObjKeys(t,inspect);return"[Function"+(s?": "+s:" (anonymous)")+"]"+(f.length>0?" { "+$join.call(f,", ")+" }":"")}if(isSymbol(t)){var y=hasShammedSymbols?$replace.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):symToString.call(t);return"object"!=typeof t||hasShammedSymbols?y:markBoxed(y)}if(isElement(t)){for(var S="<"+$toLowerCase.call(String(t.nodeName)),g=t.attributes||[],m=0;m"}if(isArray(t)){if(0===t.length)return"[]";var b=arrObjKeys(t,inspect);return u&&!singleLineValues(b)?"["+indentedJoin(b,u)+"]":"[ "+$join.call(b,", ")+" ]"}if(isError(t)){var h=arrObjKeys(t,inspect);return"cause"in Error.prototype||!("cause"in t)||isEnumerable.call(t,"cause")?0===h.length?"["+String(t)+"]":"{ ["+String(t)+"] "+$join.call(h,", ")+" }":"{ ["+String(t)+"] "+$join.call($concat.call("[cause]: "+inspect(t.cause),h),", ")+" }"}if("object"==typeof t&&i){if(inspectSymbol&&"function"==typeof t[inspectSymbol]&&utilInspect)return utilInspect(t,{depth:p-r});if("symbol"!==i&&"function"==typeof t.inspect)return t.inspect()}if(isMap(t)){var d=[];return mapForEach&&mapForEach.call(t,(function(e,r){d.push(inspect(r,t,!0)+" => "+inspect(e,t))})),collectionOf("Map",mapSize.call(t),d,u)}if(isSet(t)){var j=[];return setForEach&&setForEach.call(t,(function(e){j.push(inspect(e,t))})),collectionOf("Set",setSize.call(t),j,u)}if(isWeakMap(t))return weakCollectionOf("WeakMap");if(isWeakSet(t))return weakCollectionOf("WeakSet");if(isWeakRef(t))return weakCollectionOf("WeakRef");if(isNumber(t))return markBoxed(inspect(Number(t)));if(isBigInt(t))return markBoxed(inspect(bigIntValueOf.call(t)));if(isBoolean(t))return markBoxed(booleanValueOf.call(t));if(isString(t))return markBoxed(inspect(String(t)));if("undefined"!=typeof window&&t===window)return"{ [object Window] }";if(t===global)return"{ [object globalThis] }";if(!isDate(t)&&!isRegExp(t)){var O=arrObjKeys(t,inspect),w=gPO?gPO(t)===Object.prototype:t instanceof Object||t.constructor===Object,$=t instanceof Object?"":"null prototype",k=!w&&toStringTag&&Object(t)===t&&toStringTag in t?$slice.call(toStr(t),8,-1):$?"Object":"",v=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(k||$?"["+$join.call($concat.call([],k||[],$||[]),": ")+"] ":"");return 0===O.length?v+"{}":u?v+"{"+indentedJoin(O,u)+"}":v+"{ "+$join.call(O,", ")+" }"}return String(t)};var hasOwn=Object.prototype.hasOwnProperty||function(t){return t in this};function has(t,e){return hasOwn.call(t,e)}function toStr(t){return objectToString.call(t)}function nameOf(t){if(t.name)return t.name;var e=$match.call(functionToString.call(t),/^function\s*([\w$]+)/);return e?e[1]:null}function indexOf(t,e){if(t.indexOf)return t.indexOf(e);for(var r=0,n=t.length;re.maxStringLength){var r=t.length-e.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return inspectString($slice.call(t,0,e.maxStringLength),e)+n}return wrapQuotes($replace.call($replace.call(t,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,lowbyte),"single",e)}function lowbyte(t){var e=t.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[e];return r?"\\"+r:"\\x"+(e<16?"0":"")+$toUpperCase.call(e.toString(16))}function markBoxed(t){return"Object("+t+")"}function weakCollectionOf(t){return t+" { ? }"}function collectionOf(t,e,r,n){return t+" ("+e+") {"+(n?indentedJoin(r,n):$join.call(r,", "))+"}"}function singleLineValues(t){for(var e=0;e=0)return!1;return!0}function getIndent(t,e){var r;if("\t"===t.indent)r="\t";else{if(!("number"==typeof t.indent&&t.indent>0))return null;r=$join.call(Array(t.indent+1)," ")}return{base:r,prev:$join.call(Array(e+1),r)}}function indentedJoin(t,e){if(0===t.length)return"";var r="\n"+e.prev+e.base;return r+$join.call(t,","+r)+"\n"+e.prev}function arrObjKeys(t,e){var r=isArray(t),n=[];if(r){n.length=t.length;for(var o=0;o -1) { + return val.split(','); + } + + return val; +}; + +// This is what browsers will submit when the ✓ character occurs in an +// application/x-www-form-urlencoded body and the encoding of the page containing +// the form is iso-8859-1, or when the submitted form has an accept-charset +// attribute of iso-8859-1. Presumably also with other charsets that do not contain +// the ✓ character, such as us-ascii. +var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓') + +// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. +var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓') + +var parseValues = function parseQueryStringValues(str, options) { + var obj = { __proto__: null }; + + var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; + var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; + var parts = cleanStr.split(options.delimiter, limit); + var skipIndex = -1; // Keep track of where the utf8 sentinel was found + var i; + + var charset = options.charset; + if (options.charsetSentinel) { + for (i = 0; i < parts.length; ++i) { + if (parts[i].indexOf('utf8=') === 0) { + if (parts[i] === charsetSentinel) { + charset = 'utf-8'; + } else if (parts[i] === isoSentinel) { + charset = 'iso-8859-1'; + } + skipIndex = i; + i = parts.length; // The eslint settings do not allow break; + } + } + } + + for (i = 0; i < parts.length; ++i) { + if (i === skipIndex) { + continue; + } + var part = parts[i]; + + var bracketEqualsPos = part.indexOf(']='); + var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; + + var key, val; + if (pos === -1) { + key = options.decoder(part, defaults.decoder, charset, 'key'); + val = options.strictNullHandling ? null : ''; + } else { + key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key'); + val = utils.maybeMap( + parseArrayValue(part.slice(pos + 1), options), + function (encodedVal) { + return options.decoder(encodedVal, defaults.decoder, charset, 'value'); + } + ); + } + + if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { + val = interpretNumericEntities(val); + } + + if (part.indexOf('[]=') > -1) { + val = isArray(val) ? [val] : val; + } + + var existing = has.call(obj, key); + if (existing && options.duplicates === 'combine') { + obj[key] = utils.combine(obj[key], val); + } else if (!existing || options.duplicates === 'last') { + obj[key] = val; + } + } + + return obj; +}; + +var parseObject = function (chain, val, options, valuesParsed) { + var leaf = valuesParsed ? val : parseArrayValue(val, options); + + for (var i = chain.length - 1; i >= 0; --i) { + var obj; + var root = chain[i]; + + if (root === '[]' && options.parseArrays) { + obj = options.allowEmptyArrays && leaf === '' ? [] : [].concat(leaf); + } else { + obj = options.plainObjects ? Object.create(null) : {}; + var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; + var decodedRoot = options.decodeDotInKeys ? cleanRoot.replace(/%2E/g, '.') : cleanRoot; + var index = parseInt(decodedRoot, 10); + if (!options.parseArrays && decodedRoot === '') { + obj = { 0: leaf }; + } else if ( + !isNaN(index) + && root !== decodedRoot + && String(index) === decodedRoot + && index >= 0 + && (options.parseArrays && index <= options.arrayLimit) + ) { + obj = []; + obj[index] = leaf; + } else if (decodedRoot !== '__proto__') { + obj[decodedRoot] = leaf; + } + } + + leaf = obj; + } + + return leaf; +}; + +var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { + if (!givenKey) { + return; + } + + // Transform dot notation to bracket notation + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; + + // The regex chunks + + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + + // Get the parent + + var segment = options.depth > 0 && brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; + + // Stash the parent if it exists + + var keys = []; + if (parent) { + // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + + keys.push(parent); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) { + i += 1; + if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { + if (!options.allowPrototypes) { + return; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return parseObject(keys, val, options, valuesParsed); +}; + +var normalizeParseOptions = function normalizeParseOptions(opts) { + if (!opts) { + return defaults; + } + + if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { + throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); + } + + if (typeof opts.decodeDotInKeys !== 'undefined' && typeof opts.decodeDotInKeys !== 'boolean') { + throw new TypeError('`decodeDotInKeys` option can only be `true` or `false`, when provided'); + } + + if (opts.decoder !== null && typeof opts.decoder !== 'undefined' && typeof opts.decoder !== 'function') { + throw new TypeError('Decoder has to be a function.'); + } + + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; + + var duplicates = typeof opts.duplicates === 'undefined' ? defaults.duplicates : opts.duplicates; + + if (duplicates !== 'combine' && duplicates !== 'first' && duplicates !== 'last') { + throw new TypeError('The duplicates option must be either combine, first, or last'); + } + + var allowDots = typeof opts.allowDots === 'undefined' ? opts.decodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + + return { + allowDots: allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, + allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse, + arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, + decodeDotInKeys: typeof opts.decodeDotInKeys === 'boolean' ? opts.decodeDotInKeys : defaults.decodeDotInKeys, + decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, + delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, + // eslint-disable-next-line no-implicit-coercion, no-extra-parens + depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth, + duplicates: duplicates, + ignoreQueryPrefix: opts.ignoreQueryPrefix === true, + interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, + parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, + parseArrays: opts.parseArrays !== false, + plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (str, opts) { + var options = normalizeParseOptions(opts); + + if (str === '' || str === null || typeof str === 'undefined') { + return options.plainObjects ? Object.create(null) : {}; + } + + var tempObj = typeof str === 'string' ? parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string'); + obj = utils.merge(obj, newObj, options); + } + + if (options.allowSparse === true) { + return obj; + } + + return utils.compact(obj); +}; diff --git a/node_modules/superagent/node_modules/qs/lib/stringify.js b/node_modules/superagent/node_modules/qs/lib/stringify.js new file mode 100644 index 000000000..9b934d69b --- /dev/null +++ b/node_modules/superagent/node_modules/qs/lib/stringify.js @@ -0,0 +1,351 @@ +'use strict'; + +var getSideChannel = require('side-channel'); +var utils = require('./utils'); +var formats = require('./formats'); +var has = Object.prototype.hasOwnProperty; + +var arrayPrefixGenerators = { + brackets: function brackets(prefix) { + return prefix + '[]'; + }, + comma: 'comma', + indices: function indices(prefix, key) { + return prefix + '[' + key + ']'; + }, + repeat: function repeat(prefix) { + return prefix; + } +}; + +var isArray = Array.isArray; +var push = Array.prototype.push; +var pushToArray = function (arr, valueOrArray) { + push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); +}; + +var toISO = Date.prototype.toISOString; + +var defaultFormat = formats['default']; +var defaults = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: 'indices', + charset: 'utf-8', + charsetSentinel: false, + delimiter: '&', + encode: true, + encodeDotInKeys: false, + encoder: utils.encode, + encodeValuesOnly: false, + format: defaultFormat, + formatter: formats.formatters[defaultFormat], + // deprecated + indices: false, + serializeDate: function serializeDate(date) { + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false +}; + +var isNonNullishPrimitive = function isNonNullishPrimitive(v) { + return typeof v === 'string' + || typeof v === 'number' + || typeof v === 'boolean' + || typeof v === 'symbol' + || typeof v === 'bigint'; +}; + +var sentinel = {}; + +var stringify = function stringify( + object, + prefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + sideChannel +) { + var obj = object; + + var tmpSc = sideChannel; + var step = 0; + var findFlag = false; + while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) { + // Where object last appeared in the ref tree + var pos = tmpSc.get(object); + step += 1; + if (typeof pos !== 'undefined') { + if (pos === step) { + throw new RangeError('Cyclic object value'); + } else { + findFlag = true; // Break while + } + } + if (typeof tmpSc.get(sentinel) === 'undefined') { + step = 0; + } + } + + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (generateArrayPrefix === 'comma' && isArray(obj)) { + obj = utils.maybeMap(obj, function (value) { + if (value instanceof Date) { + return serializeDate(value); + } + return value; + }); + } + + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix; + } + + obj = ''; + } + + if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format); + return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))]; + } + return [formatter(prefix) + '=' + formatter(String(obj))]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys; + if (generateArrayPrefix === 'comma' && isArray(obj)) { + // we need to join elements in + if (encodeValuesOnly && encoder) { + obj = utils.maybeMap(obj, encoder); + } + objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; + } else if (isArray(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + + var encodedPrefix = encodeDotInKeys ? prefix.replace(/\./g, '%2E') : prefix; + + var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encodedPrefix + '[]' : encodedPrefix; + + if (allowEmptyArrays && isArray(obj) && obj.length === 0) { + return adjustedPrefix + '[]'; + } + + for (var j = 0; j < objKeys.length; ++j) { + var key = objKeys[j]; + var value = typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key]; + + if (skipNulls && value === null) { + continue; + } + + var encodedKey = allowDots && encodeDotInKeys ? key.replace(/\./g, '%2E') : key; + var keyPrefix = isArray(obj) + ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, encodedKey) : adjustedPrefix + : adjustedPrefix + (allowDots ? '.' + encodedKey : '[' + encodedKey + ']'); + + sideChannel.set(object, step); + var valueSideChannel = getSideChannel(); + valueSideChannel.set(sentinel, sideChannel); + pushToArray(values, stringify( + value, + keyPrefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + generateArrayPrefix === 'comma' && encodeValuesOnly && isArray(obj) ? null : encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + + return values; +}; + +var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { + if (!opts) { + return defaults; + } + + if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { + throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); + } + + if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') { + throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided'); + } + + if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); + } + + var charset = opts.charset || defaults.charset; + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + + var format = formats['default']; + if (typeof opts.format !== 'undefined') { + if (!has.call(formats.formatters, opts.format)) { + throw new TypeError('Unknown format option provided.'); + } + format = opts.format; + } + var formatter = formats.formatters[format]; + + var filter = defaults.filter; + if (typeof opts.filter === 'function' || isArray(opts.filter)) { + filter = opts.filter; + } + + var arrayFormat; + if (opts.arrayFormat in arrayPrefixGenerators) { + arrayFormat = opts.arrayFormat; + } else if ('indices' in opts) { + arrayFormat = opts.indices ? 'indices' : 'repeat'; + } else { + arrayFormat = defaults.arrayFormat; + } + + if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { + throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); + } + + var allowDots = typeof opts.allowDots === 'undefined' ? opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + + return { + addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots: allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + arrayFormat: arrayFormat, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + commaRoundTrip: opts.commaRoundTrip, + delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys, + encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter: filter, + format: format, + formatter: formatter, + serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === 'function' ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (object, opts) { + var obj = object; + var options = normalizeStringifyOptions(opts); + + var objKeys; + var filter; + + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } else if (isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } + + var keys = []; + + if (typeof obj !== 'object' || obj === null) { + return ''; + } + + var generateArrayPrefix = arrayPrefixGenerators[options.arrayFormat]; + var commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + if (options.sort) { + objKeys.sort(options.sort); + } + + var sideChannel = getSideChannel(); + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (options.skipNulls && obj[key] === null) { + continue; + } + pushToArray(keys, stringify( + obj[key], + key, + generateArrayPrefix, + commaRoundTrip, + options.allowEmptyArrays, + options.strictNullHandling, + options.skipNulls, + options.encodeDotInKeys, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + + var joined = keys.join(options.delimiter); + var prefix = options.addQueryPrefix === true ? '?' : ''; + + if (options.charsetSentinel) { + if (options.charset === 'iso-8859-1') { + // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark + prefix += 'utf8=%26%2310003%3B&'; + } else { + // encodeURIComponent('✓') + prefix += 'utf8=%E2%9C%93&'; + } + } + + return joined.length > 0 ? prefix + joined : ''; +}; diff --git a/node_modules/superagent/node_modules/qs/lib/utils.js b/node_modules/superagent/node_modules/qs/lib/utils.js new file mode 100644 index 000000000..1e5453811 --- /dev/null +++ b/node_modules/superagent/node_modules/qs/lib/utils.js @@ -0,0 +1,252 @@ +'use strict'; + +var formats = require('./formats'); + +var has = Object.prototype.hasOwnProperty; +var isArray = Array.isArray; + +var hexTable = (function () { + var array = []; + for (var i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } + + return array; +}()); + +var compactQueue = function compactQueue(queue) { + while (queue.length > 1) { + var item = queue.pop(); + var obj = item.obj[item.prop]; + + if (isArray(obj)) { + var compacted = []; + + for (var j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted.push(obj[j]); + } + } + + item.obj[item.prop] = compacted; + } + } +}; + +var arrayToObject = function arrayToObject(source, options) { + var obj = options && options.plainObjects ? Object.create(null) : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } + + return obj; +}; + +var merge = function merge(target, source, options) { + /* eslint no-param-reassign: 0 */ + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (isArray(target)) { + target.push(source); + } else if (target && typeof target === 'object') { + if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) { + target[source] = true; + } + } else { + return [target, source]; + } + + return target; + } + + if (!target || typeof target !== 'object') { + return [target].concat(source); + } + + var mergeTarget = target; + if (isArray(target) && !isArray(source)) { + mergeTarget = arrayToObject(target, options); + } + + if (isArray(target) && isArray(source)) { + source.forEach(function (item, i) { + if (has.call(target, i)) { + var targetItem = target[i]; + if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { + target[i] = merge(targetItem, item, options); + } else { + target.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } + + return Object.keys(source).reduce(function (acc, key) { + var value = source[key]; + + if (has.call(acc, key)) { + acc[key] = merge(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); +}; + +var assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function (acc, key) { + acc[key] = source[key]; + return acc; + }, target); +}; + +var decode = function (str, decoder, charset) { + var strWithoutPlus = str.replace(/\+/g, ' '); + if (charset === 'iso-8859-1') { + // unescape never throws, no try...catch needed: + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + // utf-8 + try { + return decodeURIComponent(strWithoutPlus); + } catch (e) { + return strWithoutPlus; + } +}; + +var encode = function encode(str, defaultEncoder, charset, kind, format) { + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + var string = str; + if (typeof str === 'symbol') { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== 'string') { + string = String(str); + } + + if (charset === 'iso-8859-1') { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { + return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; + }); + } + + var out = ''; + for (var i = 0; i < string.length; ++i) { + var c = string.charCodeAt(i); + + if ( + c === 0x2D // - + || c === 0x2E // . + || c === 0x5F // _ + || c === 0x7E // ~ + || (c >= 0x30 && c <= 0x39) // 0-9 + || (c >= 0x41 && c <= 0x5A) // a-z + || (c >= 0x61 && c <= 0x7A) // A-Z + || (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( ) + ) { + out += string.charAt(i); + continue; + } + + if (c < 0x80) { + out = out + hexTable[c]; + continue; + } + + if (c < 0x800) { + out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + i += 1; + c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); + /* eslint operator-linebreak: [2, "before"] */ + out += hexTable[0xF0 | (c >> 18)] + + hexTable[0x80 | ((c >> 12) & 0x3F)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + } + + return out; +}; + +var compact = function compact(value) { + var queue = [{ obj: { o: value }, prop: 'o' }]; + var refs = []; + + for (var i = 0; i < queue.length; ++i) { + var item = queue[i]; + var obj = item.obj[item.prop]; + + var keys = Object.keys(obj); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + var val = obj[key]; + if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj: obj, prop: key }); + refs.push(val); + } + } + } + + compactQueue(queue); + + return value; +}; + +var isRegExp = function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + +var isBuffer = function isBuffer(obj) { + if (!obj || typeof obj !== 'object') { + return false; + } + + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +}; + +var combine = function combine(a, b) { + return [].concat(a, b); +}; + +var maybeMap = function maybeMap(val, fn) { + if (isArray(val)) { + var mapped = []; + for (var i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); + } + return mapped; + } + return fn(val); +}; + +module.exports = { + arrayToObject: arrayToObject, + assign: assign, + combine: combine, + compact: compact, + decode: decode, + encode: encode, + isBuffer: isBuffer, + isRegExp: isRegExp, + maybeMap: maybeMap, + merge: merge +}; diff --git a/node_modules/superagent/node_modules/qs/package.json b/node_modules/superagent/node_modules/qs/package.json new file mode 100644 index 000000000..4b49086a5 --- /dev/null +++ b/node_modules/superagent/node_modules/qs/package.json @@ -0,0 +1,91 @@ +{ + "name": "qs", + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "homepage": "https://github.com/ljharb/qs", + "version": "6.12.0", + "repository": { + "type": "git", + "url": "https://github.com/ljharb/qs.git" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "main": "lib/index.js", + "sideEffects": false, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "keywords": [ + "querystring", + "qs", + "query", + "url", + "parse", + "stringify" + ], + "engines": { + "node": ">=0.6" + }, + "dependencies": { + "side-channel": "^1.0.6" + }, + "devDependencies": { + "@browserify/envify": "^6.0.0", + "@browserify/uglifyify": "^6.0.0", + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.4", + "browserify": "^16.5.2", + "bundle-collapser": "^1.4.0", + "common-shakeify": "~1.0.0", + "eclint": "^2.8.1", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "glob": "=10.3.7", + "has-override-mistake": "^1.0.1", + "has-property-descriptors": "^1.0.2", + "has-symbols": "^1.0.3", + "iconv-lite": "^0.5.1", + "in-publish": "^2.0.1", + "jackspeak": "=2.1.1", + "mkdirp": "^0.5.5", + "mock-property": "^1.0.3", + "module-deps": "^6.2.3", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.1", + "qs-iconv": "^1.0.4", + "safe-publish-latest": "^2.0.0", + "safer-buffer": "^2.1.2", + "tape": "^5.7.5", + "unassertify": "^3.0.1" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated && npm run dist", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent readme && npm run --silent lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/**/*.js'", + "posttest": "aud --production", + "readme": "evalmd README.md", + "postlint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git' | grep -v dist/)", + "lint": "eslint --ext=js,mjs .", + "dist": "mkdirp dist && browserify --standalone Qs -g unassertify -g @browserify/envify -g [@browserify/uglifyify --mangle.keep_fnames --compress.keep_fnames --format.indent_level=1 --compress.arrows=false --compress.passes=4 --compress.typeofs=false] -p common-shakeify -p bundle-collapser/plugin lib/index.js > dist/qs.js" + }, + "license": "BSD-3-Clause", + "publishConfig": { + "ignore": [ + "!dist/*", + "bower.json", + "component.json", + ".github/workflows", + "logos" + ] + } +} diff --git a/node_modules/superagent/node_modules/qs/test/empty-keys-cases.js b/node_modules/superagent/node_modules/qs/test/empty-keys-cases.js new file mode 100644 index 000000000..2b1190ef5 --- /dev/null +++ b/node_modules/superagent/node_modules/qs/test/empty-keys-cases.js @@ -0,0 +1,267 @@ +'use strict'; + +module.exports = { + emptyTestCases: [ + { + input: '&', + withEmptyKeys: {}, + stringifyOutput: { + brackets: '', + indices: '', + repeat: '' + }, + noEmptyKeys: {} + }, + { + input: '&&', + withEmptyKeys: {}, + stringifyOutput: { + brackets: '', + indices: '', + repeat: '' + }, + noEmptyKeys: {} + }, + { + input: '&=', + withEmptyKeys: { '': '' }, + stringifyOutput: { + brackets: '=', + indices: '=', + repeat: '=' + }, + noEmptyKeys: {} + }, + { + input: '&=&', + withEmptyKeys: { '': '' }, + stringifyOutput: { + brackets: '=', + indices: '=', + repeat: '=' + }, + noEmptyKeys: {} + }, + { + input: '&=&=', + withEmptyKeys: { '': ['', ''] }, + stringifyOutput: { + brackets: '[]=&[]=', + indices: '[0]=&[1]=', + repeat: '=&=' + }, + noEmptyKeys: {} + }, + { + input: '&=&=&', + withEmptyKeys: { '': ['', ''] }, + stringifyOutput: { + brackets: '[]=&[]=', + indices: '[0]=&[1]=', + repeat: '=&=' + }, + noEmptyKeys: {} + }, + { + input: '=', + withEmptyKeys: { '': '' }, + noEmptyKeys: {}, + stringifyOutput: { + brackets: '=', + indices: '=', + repeat: '=' + } + }, + { + input: '=&', + withEmptyKeys: { '': '' }, + stringifyOutput: { + brackets: '=', + indices: '=', + repeat: '=' + }, + noEmptyKeys: {} + }, + { + input: '=&&&', + withEmptyKeys: { '': '' }, + stringifyOutput: { + brackets: '=', + indices: '=', + repeat: '=' + }, + noEmptyKeys: {} + }, + { + input: '=&=&=&', + withEmptyKeys: { '': ['', '', ''] }, + stringifyOutput: { + brackets: '[]=&[]=&[]=', + indices: '[0]=&[1]=&[2]=', + repeat: '=&=&=' + }, + noEmptyKeys: {} + }, + { + input: '=&a[]=b&a[1]=c', + withEmptyKeys: { '': '', a: ['b', 'c'] }, + stringifyOutput: { + brackets: '=&a[]=b&a[]=c', + indices: '=&a[0]=b&a[1]=c', + repeat: '=&a=b&a=c' + }, + noEmptyKeys: { a: ['b', 'c'] } + }, + { + input: '=a', + withEmptyKeys: { '': 'a' }, + noEmptyKeys: {}, + stringifyOutput: { + brackets: '=a', + indices: '=a', + repeat: '=a' + } + }, + { + input: 'a==a', + withEmptyKeys: { a: '=a' }, + noEmptyKeys: { a: '=a' }, + stringifyOutput: { + brackets: 'a==a', + indices: 'a==a', + repeat: 'a==a' + } + }, + { + input: '=&a[]=b', + withEmptyKeys: { '': '', a: ['b'] }, + stringifyOutput: { + brackets: '=&a[]=b', + indices: '=&a[0]=b', + repeat: '=&a=b' + }, + noEmptyKeys: { a: ['b'] } + }, + { + input: '=&a[]=b&a[]=c&a[2]=d', + withEmptyKeys: { '': '', a: ['b', 'c', 'd'] }, + stringifyOutput: { + brackets: '=&a[]=b&a[]=c&a[]=d', + indices: '=&a[0]=b&a[1]=c&a[2]=d', + repeat: '=&a=b&a=c&a=d' + }, + noEmptyKeys: { a: ['b', 'c', 'd'] } + }, + { + input: '=a&=b', + withEmptyKeys: { '': ['a', 'b'] }, + stringifyOutput: { + brackets: '[]=a&[]=b', + indices: '[0]=a&[1]=b', + repeat: '=a&=b' + }, + noEmptyKeys: {} + }, + { + input: '=a&foo=b', + withEmptyKeys: { '': 'a', foo: 'b' }, + noEmptyKeys: { foo: 'b' }, + stringifyOutput: { + brackets: '=a&foo=b', + indices: '=a&foo=b', + repeat: '=a&foo=b' + } + }, + { + input: 'a[]=b&a=c&=', + withEmptyKeys: { '': '', a: ['b', 'c'] }, + stringifyOutput: { + brackets: '=&a[]=b&a[]=c', + indices: '=&a[0]=b&a[1]=c', + repeat: '=&a=b&a=c' + }, + noEmptyKeys: { a: ['b', 'c'] } + }, + { + input: 'a[]=b&a=c&=', + withEmptyKeys: { '': '', a: ['b', 'c'] }, + stringifyOutput: { + brackets: '=&a[]=b&a[]=c', + indices: '=&a[0]=b&a[1]=c', + repeat: '=&a=b&a=c' + }, + noEmptyKeys: { a: ['b', 'c'] } + }, + { + input: 'a[0]=b&a=c&=', + withEmptyKeys: { '': '', a: ['b', 'c'] }, + stringifyOutput: { + brackets: '=&a[]=b&a[]=c', + indices: '=&a[0]=b&a[1]=c', + repeat: '=&a=b&a=c' + }, + noEmptyKeys: { a: ['b', 'c'] } + }, + { + input: 'a=b&a[]=c&=', + withEmptyKeys: { '': '', a: ['b', 'c'] }, + stringifyOutput: { + brackets: '=&a[]=b&a[]=c', + indices: '=&a[0]=b&a[1]=c', + repeat: '=&a=b&a=c' + }, + noEmptyKeys: { a: ['b', 'c'] } + }, + { + input: 'a=b&a[0]=c&=', + withEmptyKeys: { '': '', a: ['b', 'c'] }, + stringifyOutput: { + brackets: '=&a[]=b&a[]=c', + indices: '=&a[0]=b&a[1]=c', + repeat: '=&a=b&a=c' + }, + noEmptyKeys: { a: ['b', 'c'] } + }, + { + input: '[]=a&[]=b& []=1', + withEmptyKeys: { '': ['a', 'b'], ' ': ['1'] }, + stringifyOutput: { + brackets: '[]=a&[]=b& []=1', + indices: '[0]=a&[1]=b& [0]=1', + repeat: '=a&=b& =1' + }, + noEmptyKeys: { 0: 'a', 1: 'b', ' ': ['1'] } + }, + { + input: '[0]=a&[1]=b&a[0]=1&a[1]=2', + withEmptyKeys: { '': ['a', 'b'], a: ['1', '2'] }, + noEmptyKeys: { 0: 'a', 1: 'b', a: ['1', '2'] }, + stringifyOutput: { + brackets: '[]=a&[]=b&a[]=1&a[]=2', + indices: '[0]=a&[1]=b&a[0]=1&a[1]=2', + repeat: '=a&=b&a=1&a=2' + } + }, + { + input: '[deep]=a&[deep]=2', + withEmptyKeys: { '': { deep: ['a', '2'] } + }, + stringifyOutput: { + brackets: '[deep][]=a&[deep][]=2', + indices: '[deep][0]=a&[deep][1]=2', + repeat: '[deep]=a&[deep]=2' + }, + noEmptyKeys: { deep: ['a', '2'] } + }, + { + input: '%5B0%5D=a&%5B1%5D=b', + withEmptyKeys: { '': ['a', 'b'] }, + stringifyOutput: { + brackets: '[]=a&[]=b', + indices: '[0]=a&[1]=b', + repeat: '=a&=b' + }, + noEmptyKeys: { 0: 'a', 1: 'b' } + } + ] +}; diff --git a/node_modules/superagent/node_modules/qs/test/parse.js b/node_modules/superagent/node_modules/qs/test/parse.js new file mode 100644 index 000000000..aad454b51 --- /dev/null +++ b/node_modules/superagent/node_modules/qs/test/parse.js @@ -0,0 +1,1047 @@ +'use strict'; + +var test = require('tape'); +var hasPropertyDescriptors = require('has-property-descriptors')(); +var iconv = require('iconv-lite'); +var mockProperty = require('mock-property'); +var hasOverrideMistake = require('has-override-mistake')(); +var SaferBuffer = require('safer-buffer').Buffer; +var v = require('es-value-fixtures'); +var inspect = require('object-inspect'); +var emptyTestCases = require('./empty-keys-cases').emptyTestCases; + +var qs = require('../'); +var utils = require('../lib/utils'); + +test('parse()', function (t) { + t.test('parses a simple string', function (st) { + st.deepEqual(qs.parse('0=foo'), { 0: 'foo' }); + st.deepEqual(qs.parse('foo=c++'), { foo: 'c ' }); + st.deepEqual(qs.parse('a[>=]=23'), { a: { '>=': '23' } }); + st.deepEqual(qs.parse('a[<=>]==23'), { a: { '<=>': '=23' } }); + st.deepEqual(qs.parse('a[==]=23'), { a: { '==': '23' } }); + st.deepEqual(qs.parse('foo', { strictNullHandling: true }), { foo: null }); + st.deepEqual(qs.parse('foo'), { foo: '' }); + st.deepEqual(qs.parse('foo='), { foo: '' }); + st.deepEqual(qs.parse('foo=bar'), { foo: 'bar' }); + st.deepEqual(qs.parse(' foo = bar = baz '), { ' foo ': ' bar = baz ' }); + st.deepEqual(qs.parse('foo=bar=baz'), { foo: 'bar=baz' }); + st.deepEqual(qs.parse('foo=bar&bar=baz'), { foo: 'bar', bar: 'baz' }); + st.deepEqual(qs.parse('foo2=bar2&baz2='), { foo2: 'bar2', baz2: '' }); + st.deepEqual(qs.parse('foo=bar&baz', { strictNullHandling: true }), { foo: 'bar', baz: null }); + st.deepEqual(qs.parse('foo=bar&baz'), { foo: 'bar', baz: '' }); + st.deepEqual(qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World'), { + cht: 'p3', + chd: 't:60,40', + chs: '250x100', + chl: 'Hello|World' + }); + st.end(); + }); + + t.test('comma: false', function (st) { + st.deepEqual(qs.parse('a[]=b&a[]=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[0]=b&a[1]=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b,c'), { a: 'b,c' }); + st.deepEqual(qs.parse('a=b&a=c'), { a: ['b', 'c'] }); + st.end(); + }); + + t.test('comma: true', function (st) { + st.deepEqual(qs.parse('a[]=b&a[]=c', { comma: true }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { comma: true }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b,c', { comma: true }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a=c', { comma: true }), { a: ['b', 'c'] }); + st.end(); + }); + + t.test('allows enabling dot notation', function (st) { + st.deepEqual(qs.parse('a.b=c'), { 'a.b': 'c' }); + st.deepEqual(qs.parse('a.b=c', { allowDots: true }), { a: { b: 'c' } }); + + st.end(); + }); + + t.test('decode dot keys correctly', function (st) { + st.deepEqual( + qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe', { allowDots: false, decodeDotInKeys: false }), + { 'name%2Eobj.first': 'John', 'name%2Eobj.last': 'Doe' }, + 'with allowDots false and decodeDotInKeys false' + ); + st.deepEqual( + qs.parse('name.obj.first=John&name.obj.last=Doe', { allowDots: true, decodeDotInKeys: false }), + { name: { obj: { first: 'John', last: 'Doe' } } }, + 'with allowDots false and decodeDotInKeys false' + ); + st.deepEqual( + qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe', { allowDots: true, decodeDotInKeys: false }), + { 'name%2Eobj': { first: 'John', last: 'Doe' } }, + 'with allowDots true and decodeDotInKeys false' + ); + st.deepEqual( + qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe', { allowDots: true, decodeDotInKeys: true }), + { 'name.obj': { first: 'John', last: 'Doe' } }, + 'with allowDots true and decodeDotInKeys true' + ); + + st.deepEqual( + qs.parse( + 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe', + { allowDots: false, decodeDotInKeys: false } + ), + { 'name%2Eobj%2Esubobject.first%2Egodly%2Ename': 'John', 'name%2Eobj%2Esubobject.last': 'Doe' }, + 'with allowDots false and decodeDotInKeys false' + ); + st.deepEqual( + qs.parse( + 'name.obj.subobject.first.godly.name=John&name.obj.subobject.last=Doe', + { allowDots: true, decodeDotInKeys: false } + ), + { name: { obj: { subobject: { first: { godly: { name: 'John' } }, last: 'Doe' } } } }, + 'with allowDots true and decodeDotInKeys false' + ); + st.deepEqual( + qs.parse( + 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe', + { allowDots: true, decodeDotInKeys: true } + ), + { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, + 'with allowDots true and decodeDotInKeys true' + ); + + st.end(); + }); + + t.test('should decode dot in key of object, and allow enabling dot notation when decodeDotInKeys is set to true and allowDots is undefined', function (st) { + st.deepEqual( + qs.parse( + 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe', + { decodeDotInKeys: true } + ), + { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, + 'with allowDots undefined and decodeDotInKeys true' + ); + + st.end(); + }); + + t.test('should throw when decodeDotInKeys is not of type boolean', function (st) { + st['throws']( + function () { qs.parse('foo[]&bar=baz', { decodeDotInKeys: 'foobar' }); }, + TypeError + ); + + st['throws']( + function () { qs.parse('foo[]&bar=baz', { decodeDotInKeys: 0 }); }, + TypeError + ); + st['throws']( + function () { qs.parse('foo[]&bar=baz', { decodeDotInKeys: NaN }); }, + TypeError + ); + + st['throws']( + function () { qs.parse('foo[]&bar=baz', { decodeDotInKeys: null }); }, + TypeError + ); + + st.end(); + }); + + t.test('allows empty arrays in obj values', function (st) { + st.deepEqual(qs.parse('foo[]&bar=baz', { allowEmptyArrays: true }), { foo: [], bar: 'baz' }); + st.deepEqual(qs.parse('foo[]&bar=baz', { allowEmptyArrays: false }), { foo: [''], bar: 'baz' }); + + st.end(); + }); + + t.test('should throw when allowEmptyArrays is not of type boolean', function (st) { + st['throws']( + function () { qs.parse('foo[]&bar=baz', { allowEmptyArrays: 'foobar' }); }, + TypeError + ); + + st['throws']( + function () { qs.parse('foo[]&bar=baz', { allowEmptyArrays: 0 }); }, + TypeError + ); + st['throws']( + function () { qs.parse('foo[]&bar=baz', { allowEmptyArrays: NaN }); }, + TypeError + ); + + st['throws']( + function () { qs.parse('foo[]&bar=baz', { allowEmptyArrays: null }); }, + TypeError + ); + + st.end(); + }); + + t.deepEqual(qs.parse('a[b]=c'), { a: { b: 'c' } }, 'parses a single nested string'); + t.deepEqual(qs.parse('a[b][c]=d'), { a: { b: { c: 'd' } } }, 'parses a double nested string'); + t.deepEqual( + qs.parse('a[b][c][d][e][f][g][h]=i'), + { a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } }, + 'defaults to a depth of 5' + ); + + t.test('only parses one level when depth = 1', function (st) { + st.deepEqual(qs.parse('a[b][c]=d', { depth: 1 }), { a: { b: { '[c]': 'd' } } }); + st.deepEqual(qs.parse('a[b][c][d]=e', { depth: 1 }), { a: { b: { '[c][d]': 'e' } } }); + st.end(); + }); + + t.test('uses original key when depth = 0', function (st) { + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { depth: 0 }), { 'a[0]': 'b', 'a[1]': 'c' }); + st.deepEqual(qs.parse('a[0][0]=b&a[0][1]=c&a[1]=d&e=2', { depth: 0 }), { 'a[0][0]': 'b', 'a[0][1]': 'c', 'a[1]': 'd', e: '2' }); + st.end(); + }); + + t.test('uses original key when depth = false', function (st) { + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { depth: false }), { 'a[0]': 'b', 'a[1]': 'c' }); + st.deepEqual(qs.parse('a[0][0]=b&a[0][1]=c&a[1]=d&e=2', { depth: false }), { 'a[0][0]': 'b', 'a[0][1]': 'c', 'a[1]': 'd', e: '2' }); + st.end(); + }); + + t.deepEqual(qs.parse('a=b&a=c'), { a: ['b', 'c'] }, 'parses a simple array'); + + t.test('parses an explicit array', function (st) { + st.deepEqual(qs.parse('a[]=b'), { a: ['b'] }); + st.deepEqual(qs.parse('a[]=b&a[]=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a[]=c&a[]=d'), { a: ['b', 'c', 'd'] }); + st.end(); + }); + + t.test('parses a mix of simple and explicit arrays', function (st) { + st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[0]=b&a=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a[0]=c'), { a: ['b', 'c'] }); + + st.deepEqual(qs.parse('a[1]=b&a=c', { arrayLimit: 20 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a=c', { arrayLimit: 0 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] }); + + st.deepEqual(qs.parse('a=b&a[1]=c', { arrayLimit: 20 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a[]=c', { arrayLimit: 0 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] }); + + st.end(); + }); + + t.test('parses a nested array', function (st) { + st.deepEqual(qs.parse('a[b][]=c&a[b][]=d'), { a: { b: ['c', 'd'] } }); + st.deepEqual(qs.parse('a[>=]=25'), { a: { '>=': '25' } }); + st.end(); + }); + + t.test('allows to specify array indices', function (st) { + st.deepEqual(qs.parse('a[1]=c&a[0]=b&a[2]=d'), { a: ['b', 'c', 'd'] }); + st.deepEqual(qs.parse('a[1]=c&a[0]=b'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 20 }), { a: ['c'] }); + st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 0 }), { a: { 1: 'c' } }); + st.deepEqual(qs.parse('a[1]=c'), { a: ['c'] }); + st.end(); + }); + + t.test('limits specific array indices to arrayLimit', function (st) { + st.deepEqual(qs.parse('a[20]=a', { arrayLimit: 20 }), { a: ['a'] }); + st.deepEqual(qs.parse('a[21]=a', { arrayLimit: 20 }), { a: { 21: 'a' } }); + + st.deepEqual(qs.parse('a[20]=a'), { a: ['a'] }); + st.deepEqual(qs.parse('a[21]=a'), { a: { 21: 'a' } }); + st.end(); + }); + + t.deepEqual(qs.parse('a[12b]=c'), { a: { '12b': 'c' } }, 'supports keys that begin with a number'); + + t.test('supports encoded = signs', function (st) { + st.deepEqual(qs.parse('he%3Dllo=th%3Dere'), { 'he=llo': 'th=ere' }); + st.end(); + }); + + t.test('is ok with url encoded strings', function (st) { + st.deepEqual(qs.parse('a[b%20c]=d'), { a: { 'b c': 'd' } }); + st.deepEqual(qs.parse('a[b]=c%20d'), { a: { b: 'c d' } }); + st.end(); + }); + + t.test('allows brackets in the value', function (st) { + st.deepEqual(qs.parse('pets=["tobi"]'), { pets: '["tobi"]' }); + st.deepEqual(qs.parse('operators=[">=", "<="]'), { operators: '[">=", "<="]' }); + st.end(); + }); + + t.test('allows empty values', function (st) { + st.deepEqual(qs.parse(''), {}); + st.deepEqual(qs.parse(null), {}); + st.deepEqual(qs.parse(undefined), {}); + st.end(); + }); + + t.test('transforms arrays to objects', function (st) { + st.deepEqual(qs.parse('foo[0]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } }); + st.deepEqual(qs.parse('foo[bad]=baz&foo[0]=bar'), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar'), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo[]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } }); + st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo'), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } }); + st.deepEqual(qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb'), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + + st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: false }), { a: { 0: 'b', t: 'u' } }); + st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: true }), { a: { 0: 'b', t: 'u', hasOwnProperty: 'c' } }); + st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: false }), { a: { 0: 'b', x: 'y' } }); + st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: true }), { a: { 0: 'b', hasOwnProperty: 'c', x: 'y' } }); + st.end(); + }); + + t.test('transforms arrays to objects (dot notation)', function (st) { + st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: 'baz' } }); + st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad.boo=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: { boo: 'baz' } } }); + st.deepEqual(qs.parse('foo[0][0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [[{ baz: 'bar' }]], fool: { bad: 'baz' } }); + st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15'], bar: '2' }] }); + st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15', '16'], bar: '2' }] }); + st.deepEqual(qs.parse('foo.bad=baz&foo[0]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo[]=bar&foo.bad=baz', { allowDots: true }), { foo: { 0: 'bar', bad: 'baz' } }); + st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } }); + st.deepEqual(qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb', { allowDots: true }), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + st.end(); + }); + + t.test('correctly prunes undefined values when converting an array to an object', function (st) { + st.deepEqual(qs.parse('a[2]=b&a[99999999]=c'), { a: { 2: 'b', 99999999: 'c' } }); + st.end(); + }); + + t.test('supports malformed uri characters', function (st) { + st.deepEqual(qs.parse('{%:%}', { strictNullHandling: true }), { '{%:%}': null }); + st.deepEqual(qs.parse('{%:%}='), { '{%:%}': '' }); + st.deepEqual(qs.parse('foo=%:%}'), { foo: '%:%}' }); + st.end(); + }); + + t.test('doesn\'t produce empty keys', function (st) { + st.deepEqual(qs.parse('_r=1&'), { _r: '1' }); + st.end(); + }); + + t.test('cannot access Object prototype', function (st) { + qs.parse('constructor[prototype][bad]=bad'); + qs.parse('bad[constructor][prototype][bad]=bad'); + st.equal(typeof Object.prototype.bad, 'undefined'); + st.end(); + }); + + t.test('parses arrays of objects', function (st) { + st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] }); + st.deepEqual(qs.parse('a[0][b]=c'), { a: [{ b: 'c' }] }); + st.end(); + }); + + t.test('allows for empty strings in arrays', function (st) { + st.deepEqual(qs.parse('a[]=b&a[]=&a[]=c'), { a: ['b', '', 'c'] }); + + st.deepEqual( + qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true, arrayLimit: 20 }), + { a: ['b', null, 'c', ''] }, + 'with arrayLimit 20 + array indices: null then empty string works' + ); + st.deepEqual( + qs.parse('a[]=b&a[]&a[]=c&a[]=', { strictNullHandling: true, arrayLimit: 0 }), + { a: ['b', null, 'c', ''] }, + 'with arrayLimit 0 + array brackets: null then empty string works' + ); + + st.deepEqual( + qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true, arrayLimit: 20 }), + { a: ['b', '', 'c', null] }, + 'with arrayLimit 20 + array indices: empty string then null works' + ); + st.deepEqual( + qs.parse('a[]=b&a[]=&a[]=c&a[]', { strictNullHandling: true, arrayLimit: 0 }), + { a: ['b', '', 'c', null] }, + 'with arrayLimit 0 + array brackets: empty string then null works' + ); + + st.deepEqual( + qs.parse('a[]=&a[]=b&a[]=c'), + { a: ['', 'b', 'c'] }, + 'array brackets: empty strings work' + ); + st.end(); + }); + + t.test('compacts sparse arrays', function (st) { + st.deepEqual(qs.parse('a[10]=1&a[2]=2', { arrayLimit: 20 }), { a: ['2', '1'] }); + st.deepEqual(qs.parse('a[1][b][2][c]=1', { arrayLimit: 20 }), { a: [{ b: [{ c: '1' }] }] }); + st.deepEqual(qs.parse('a[1][2][3][c]=1', { arrayLimit: 20 }), { a: [[[{ c: '1' }]]] }); + st.deepEqual(qs.parse('a[1][2][3][c][1]=1', { arrayLimit: 20 }), { a: [[[{ c: ['1'] }]]] }); + st.end(); + }); + + t.test('parses sparse arrays', function (st) { + /* eslint no-sparse-arrays: 0 */ + st.deepEqual(qs.parse('a[4]=1&a[1]=2', { allowSparse: true }), { a: [, '2', , , '1'] }); + st.deepEqual(qs.parse('a[1][b][2][c]=1', { allowSparse: true }), { a: [, { b: [, , { c: '1' }] }] }); + st.deepEqual(qs.parse('a[1][2][3][c]=1', { allowSparse: true }), { a: [, [, , [, , , { c: '1' }]]] }); + st.deepEqual(qs.parse('a[1][2][3][c][1]=1', { allowSparse: true }), { a: [, [, , [, , , { c: [, '1'] }]]] }); + st.end(); + }); + + t.test('parses semi-parsed strings', function (st) { + st.deepEqual(qs.parse({ 'a[b]': 'c' }), { a: { b: 'c' } }); + st.deepEqual(qs.parse({ 'a[b]': 'c', 'a[d]': 'e' }), { a: { b: 'c', d: 'e' } }); + st.end(); + }); + + t.test('parses buffers correctly', function (st) { + var b = SaferBuffer.from('test'); + st.deepEqual(qs.parse({ a: b }), { a: b }); + st.end(); + }); + + t.test('parses jquery-param strings', function (st) { + // readable = 'filter[0][]=int1&filter[0][]==&filter[0][]=77&filter[]=and&filter[2][]=int2&filter[2][]==&filter[2][]=8' + var encoded = 'filter%5B0%5D%5B%5D=int1&filter%5B0%5D%5B%5D=%3D&filter%5B0%5D%5B%5D=77&filter%5B%5D=and&filter%5B2%5D%5B%5D=int2&filter%5B2%5D%5B%5D=%3D&filter%5B2%5D%5B%5D=8'; + var expected = { filter: [['int1', '=', '77'], 'and', ['int2', '=', '8']] }; + st.deepEqual(qs.parse(encoded), expected); + st.end(); + }); + + t.test('continues parsing when no parent is found', function (st) { + st.deepEqual(qs.parse('[]=&a=b'), { 0: '', a: 'b' }); + st.deepEqual(qs.parse('[]&a=b', { strictNullHandling: true }), { 0: null, a: 'b' }); + st.deepEqual(qs.parse('[foo]=bar'), { foo: 'bar' }); + st.end(); + }); + + t.test('does not error when parsing a very long array', function (st) { + var str = 'a[]=a'; + while (Buffer.byteLength(str) < 128 * 1024) { + str = str + '&' + str; + } + + st.doesNotThrow(function () { + qs.parse(str); + }); + + st.end(); + }); + + t.test('should not throw when a native prototype has an enumerable property', function (st) { + st.intercept(Object.prototype, 'crash', { value: '' }); + st.intercept(Array.prototype, 'crash', { value: '' }); + + st.doesNotThrow(qs.parse.bind(null, 'a=b')); + st.deepEqual(qs.parse('a=b'), { a: 'b' }); + st.doesNotThrow(qs.parse.bind(null, 'a[][b]=c')); + st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] }); + + st.end(); + }); + + t.test('parses a string with an alternative string delimiter', function (st) { + st.deepEqual(qs.parse('a=b;c=d', { delimiter: ';' }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('parses a string with an alternative RegExp delimiter', function (st) { + st.deepEqual(qs.parse('a=b; c=d', { delimiter: /[;,] */ }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('does not use non-splittable objects as delimiters', function (st) { + st.deepEqual(qs.parse('a=b&c=d', { delimiter: true }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('allows overriding parameter limit', function (st) { + st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: 1 }), { a: 'b' }); + st.end(); + }); + + t.test('allows setting the parameter limit to Infinity', function (st) { + st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: Infinity }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('allows overriding array limit', function (st) { + st.deepEqual(qs.parse('a[0]=b', { arrayLimit: -1 }), { a: { 0: 'b' } }); + st.deepEqual(qs.parse('a[0]=b', { arrayLimit: 0 }), { a: ['b'] }); + + st.deepEqual(qs.parse('a[-1]=b', { arrayLimit: -1 }), { a: { '-1': 'b' } }); + st.deepEqual(qs.parse('a[-1]=b', { arrayLimit: 0 }), { a: { '-1': 'b' } }); + + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayLimit: -1 }), { a: { 0: 'b', 1: 'c' } }); + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayLimit: 0 }), { a: { 0: 'b', 1: 'c' } }); + + st.end(); + }); + + t.test('allows disabling array parsing', function (st) { + var indices = qs.parse('a[0]=b&a[1]=c', { parseArrays: false }); + st.deepEqual(indices, { a: { 0: 'b', 1: 'c' } }); + st.equal(Array.isArray(indices.a), false, 'parseArrays:false, indices case is not an array'); + + var emptyBrackets = qs.parse('a[]=b', { parseArrays: false }); + st.deepEqual(emptyBrackets, { a: { 0: 'b' } }); + st.equal(Array.isArray(emptyBrackets.a), false, 'parseArrays:false, empty brackets case is not an array'); + + st.end(); + }); + + t.test('allows for query string prefix', function (st) { + st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' }); + st.deepEqual(qs.parse('foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' }); + st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: false }), { '?foo': 'bar' }); + + st.end(); + }); + + t.test('parses an object', function (st) { + var input = { + 'user[name]': { 'pop[bob]': 3 }, + 'user[email]': null + }; + + var expected = { + user: { + name: { 'pop[bob]': 3 }, + email: null + } + }; + + var result = qs.parse(input); + + st.deepEqual(result, expected); + st.end(); + }); + + t.test('parses string with comma as array divider', function (st) { + st.deepEqual(qs.parse('foo=bar,tee', { comma: true }), { foo: ['bar', 'tee'] }); + st.deepEqual(qs.parse('foo[bar]=coffee,tee', { comma: true }), { foo: { bar: ['coffee', 'tee'] } }); + st.deepEqual(qs.parse('foo=', { comma: true }), { foo: '' }); + st.deepEqual(qs.parse('foo', { comma: true }), { foo: '' }); + st.deepEqual(qs.parse('foo', { comma: true, strictNullHandling: true }), { foo: null }); + + // test cases inversed from from stringify tests + st.deepEqual(qs.parse('a[0]=c'), { a: ['c'] }); + st.deepEqual(qs.parse('a[]=c'), { a: ['c'] }); + st.deepEqual(qs.parse('a[]=c', { comma: true }), { a: ['c'] }); + + st.deepEqual(qs.parse('a[0]=c&a[1]=d'), { a: ['c', 'd'] }); + st.deepEqual(qs.parse('a[]=c&a[]=d'), { a: ['c', 'd'] }); + st.deepEqual(qs.parse('a=c,d', { comma: true }), { a: ['c', 'd'] }); + + st.end(); + }); + + t.test('parses values with comma as array divider', function (st) { + st.deepEqual(qs.parse({ foo: 'bar,tee' }, { comma: false }), { foo: 'bar,tee' }); + st.deepEqual(qs.parse({ foo: 'bar,tee' }, { comma: true }), { foo: ['bar', 'tee'] }); + st.end(); + }); + + t.test('use number decoder, parses string that has one number with comma option enabled', function (st) { + var decoder = function (str, defaultDecoder, charset, type) { + if (!isNaN(Number(str))) { + return parseFloat(str); + } + return defaultDecoder(str, defaultDecoder, charset, type); + }; + + st.deepEqual(qs.parse('foo=1', { comma: true, decoder: decoder }), { foo: 1 }); + st.deepEqual(qs.parse('foo=0', { comma: true, decoder: decoder }), { foo: 0 }); + + st.end(); + }); + + t.test('parses brackets holds array of arrays when having two parts of strings with comma as array divider', function (st) { + st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=4,5,6', { comma: true }), { foo: [['1', '2', '3'], ['4', '5', '6']] }); + st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=', { comma: true }), { foo: [['1', '2', '3'], ''] }); + st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=,', { comma: true }), { foo: [['1', '2', '3'], ['', '']] }); + st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=a', { comma: true }), { foo: [['1', '2', '3'], 'a'] }); + + st.end(); + }); + + t.test('parses comma delimited array while having percent-encoded comma treated as normal text', function (st) { + st.deepEqual(qs.parse('foo=a%2Cb', { comma: true }), { foo: 'a,b' }); + st.deepEqual(qs.parse('foo=a%2C%20b,d', { comma: true }), { foo: ['a, b', 'd'] }); + st.deepEqual(qs.parse('foo=a%2C%20b,c%2C%20d', { comma: true }), { foo: ['a, b', 'c, d'] }); + + st.end(); + }); + + t.test('parses an object in dot notation', function (st) { + var input = { + 'user.name': { 'pop[bob]': 3 }, + 'user.email.': null + }; + + var expected = { + user: { + name: { 'pop[bob]': 3 }, + email: null + } + }; + + var result = qs.parse(input, { allowDots: true }); + + st.deepEqual(result, expected); + st.end(); + }); + + t.test('parses an object and not child values', function (st) { + var input = { + 'user[name]': { 'pop[bob]': { test: 3 } }, + 'user[email]': null + }; + + var expected = { + user: { + name: { 'pop[bob]': { test: 3 } }, + email: null + } + }; + + var result = qs.parse(input); + + st.deepEqual(result, expected); + st.end(); + }); + + t.test('does not blow up when Buffer global is missing', function (st) { + var restore = mockProperty(global, 'Buffer', { 'delete': true }); + + var result = qs.parse('a=b&c=d'); + + restore(); + + st.deepEqual(result, { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('does not crash when parsing circular references', function (st) { + var a = {}; + a.b = a; + + var parsed; + + st.doesNotThrow(function () { + parsed = qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a }); + }); + + st.equal('foo' in parsed, true, 'parsed has "foo" property'); + st.equal('bar' in parsed.foo, true); + st.equal('baz' in parsed.foo, true); + st.equal(parsed.foo.bar, 'baz'); + st.deepEqual(parsed.foo.baz, a); + st.end(); + }); + + t.test('does not crash when parsing deep objects', function (st) { + var parsed; + var str = 'foo'; + + for (var i = 0; i < 5000; i++) { + str += '[p]'; + } + + str += '=bar'; + + st.doesNotThrow(function () { + parsed = qs.parse(str, { depth: 5000 }); + }); + + st.equal('foo' in parsed, true, 'parsed has "foo" property'); + + var depth = 0; + var ref = parsed.foo; + while ((ref = ref.p)) { + depth += 1; + } + + st.equal(depth, 5000, 'parsed is 5000 properties deep'); + + st.end(); + }); + + t.test('parses null objects correctly', { skip: !Object.create }, function (st) { + var a = Object.create(null); + a.b = 'c'; + + st.deepEqual(qs.parse(a), { b: 'c' }); + var result = qs.parse({ a: a }); + st.equal('a' in result, true, 'result has "a" property'); + st.deepEqual(result.a, a); + st.end(); + }); + + t.test('parses dates correctly', function (st) { + var now = new Date(); + st.deepEqual(qs.parse({ a: now }), { a: now }); + st.end(); + }); + + t.test('parses regular expressions correctly', function (st) { + var re = /^test$/; + st.deepEqual(qs.parse({ a: re }), { a: re }); + st.end(); + }); + + t.test('does not allow overwriting prototype properties', function (st) { + st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: false }), {}); + st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: false }), {}); + + st.deepEqual( + qs.parse('toString', { allowPrototypes: false }), + {}, + 'bare "toString" results in {}' + ); + + st.end(); + }); + + t.test('can allow overwriting prototype properties', function (st) { + st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }), { a: { hasOwnProperty: 'b' } }); + st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: true }), { hasOwnProperty: 'b' }); + + st.deepEqual( + qs.parse('toString', { allowPrototypes: true }), + { toString: '' }, + 'bare "toString" results in { toString: "" }' + ); + + st.end(); + }); + + t.test('does not crash when the global Object prototype is frozen', { skip: !hasPropertyDescriptors || !hasOverrideMistake }, function (st) { + // We can't actually freeze the global Object prototype as that will interfere with other tests, and once an object is frozen, it + // can't be unfrozen. Instead, we add a new non-writable property to simulate this. + st.teardown(mockProperty(Object.prototype, 'frozenProp', { value: 'foo', nonWritable: true, nonEnumerable: true })); + + st['throws']( + function () { + var obj = {}; + obj.frozenProp = 'bar'; + }, + // node < 6 has a different error message + /^TypeError: Cannot assign to read only property 'frozenProp' of (?:object '#'|#)/, + 'regular assignment of an inherited non-writable property throws' + ); + + var parsed; + st.doesNotThrow( + function () { + parsed = qs.parse('frozenProp', { allowPrototypes: false }); + }, + 'parsing a nonwritable Object.prototype property does not throw' + ); + + st.deepEqual(parsed, {}, 'bare "frozenProp" results in {}'); + + st.end(); + }); + + t.test('params starting with a closing bracket', function (st) { + st.deepEqual(qs.parse(']=toString'), { ']': 'toString' }); + st.deepEqual(qs.parse(']]=toString'), { ']]': 'toString' }); + st.deepEqual(qs.parse(']hello]=toString'), { ']hello]': 'toString' }); + st.end(); + }); + + t.test('params starting with a starting bracket', function (st) { + st.deepEqual(qs.parse('[=toString'), { '[': 'toString' }); + st.deepEqual(qs.parse('[[=toString'), { '[[': 'toString' }); + st.deepEqual(qs.parse('[hello[=toString'), { '[hello[': 'toString' }); + st.end(); + }); + + t.test('add keys to objects', function (st) { + st.deepEqual( + qs.parse('a[b]=c&a=d'), + { a: { b: 'c', d: true } }, + 'can add keys to objects' + ); + + st.deepEqual( + qs.parse('a[b]=c&a=toString'), + { a: { b: 'c' } }, + 'can not overwrite prototype' + ); + + st.deepEqual( + qs.parse('a[b]=c&a=toString', { allowPrototypes: true }), + { a: { b: 'c', toString: true } }, + 'can overwrite prototype with allowPrototypes true' + ); + + st.deepEqual( + qs.parse('a[b]=c&a=toString', { plainObjects: true }), + { __proto__: null, a: { __proto__: null, b: 'c', toString: true } }, + 'can overwrite prototype with plainObjects true' + ); + + st.end(); + }); + + t.test('dunder proto is ignored', function (st) { + var payload = 'categories[__proto__]=login&categories[__proto__]&categories[length]=42'; + var result = qs.parse(payload, { allowPrototypes: true }); + + st.deepEqual( + result, + { + categories: { + length: '42' + } + }, + 'silent [[Prototype]] payload' + ); + + var plainResult = qs.parse(payload, { allowPrototypes: true, plainObjects: true }); + + st.deepEqual( + plainResult, + { + __proto__: null, + categories: { + __proto__: null, + length: '42' + } + }, + 'silent [[Prototype]] payload: plain objects' + ); + + var query = qs.parse('categories[__proto__]=cats&categories[__proto__]=dogs&categories[some][json]=toInject', { allowPrototypes: true }); + + st.notOk(Array.isArray(query.categories), 'is not an array'); + st.notOk(query.categories instanceof Array, 'is not instanceof an array'); + st.deepEqual(query.categories, { some: { json: 'toInject' } }); + st.equal(JSON.stringify(query.categories), '{"some":{"json":"toInject"}}', 'stringifies as a non-array'); + + st.deepEqual( + qs.parse('foo[__proto__][hidden]=value&foo[bar]=stuffs', { allowPrototypes: true }), + { + foo: { + bar: 'stuffs' + } + }, + 'hidden values' + ); + + st.deepEqual( + qs.parse('foo[__proto__][hidden]=value&foo[bar]=stuffs', { allowPrototypes: true, plainObjects: true }), + { + __proto__: null, + foo: { + __proto__: null, + bar: 'stuffs' + } + }, + 'hidden values: plain objects' + ); + + st.end(); + }); + + t.test('can return null objects', { skip: !Object.create }, function (st) { + var expected = Object.create(null); + expected.a = Object.create(null); + expected.a.b = 'c'; + expected.a.hasOwnProperty = 'd'; + st.deepEqual(qs.parse('a[b]=c&a[hasOwnProperty]=d', { plainObjects: true }), expected); + st.deepEqual(qs.parse(null, { plainObjects: true }), Object.create(null)); + var expectedArray = Object.create(null); + expectedArray.a = Object.create(null); + expectedArray.a[0] = 'b'; + expectedArray.a.c = 'd'; + st.deepEqual(qs.parse('a[]=b&a[c]=d', { plainObjects: true }), expectedArray); + st.end(); + }); + + t.test('can parse with custom encoding', function (st) { + st.deepEqual(qs.parse('%8c%a7=%91%e5%8d%e3%95%7b', { + decoder: function (str) { + var reg = /%([0-9A-F]{2})/ig; + var result = []; + var parts = reg.exec(str); + while (parts) { + result.push(parseInt(parts[1], 16)); + parts = reg.exec(str); + } + return String(iconv.decode(SaferBuffer.from(result), 'shift_jis')); + } + }), { 県: '大阪府' }); + st.end(); + }); + + t.test('receives the default decoder as a second argument', function (st) { + st.plan(1); + qs.parse('a', { + decoder: function (str, defaultDecoder) { + st.equal(defaultDecoder, utils.decode); + } + }); + st.end(); + }); + + t.test('throws error with wrong decoder', function (st) { + st['throws'](function () { + qs.parse({}, { decoder: 'string' }); + }, new TypeError('Decoder has to be a function.')); + st.end(); + }); + + t.test('does not mutate the options argument', function (st) { + var options = {}; + qs.parse('a[b]=true', options); + st.deepEqual(options, {}); + st.end(); + }); + + t.test('throws if an invalid charset is specified', function (st) { + st['throws'](function () { + qs.parse('a=b', { charset: 'foobar' }); + }, new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined')); + st.end(); + }); + + t.test('parses an iso-8859-1 string if asked to', function (st) { + st.deepEqual(qs.parse('%A2=%BD', { charset: 'iso-8859-1' }), { '¢': '½' }); + st.end(); + }); + + var urlEncodedCheckmarkInUtf8 = '%E2%9C%93'; + var urlEncodedOSlashInUtf8 = '%C3%B8'; + var urlEncodedNumCheckmark = '%26%2310003%3B'; + var urlEncodedNumSmiley = '%26%239786%3B'; + + t.test('prefers an utf-8 charset specified by the utf8 sentinel to a default charset of iso-8859-1', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedCheckmarkInUtf8 + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'iso-8859-1' }), { ø: 'ø' }); + st.end(); + }); + + t.test('prefers an iso-8859-1 charset specified by the utf8 sentinel to a default charset of utf-8', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedNumCheckmark + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'utf-8' }), { 'ø': 'ø' }); + st.end(); + }); + + t.test('does not require the utf8 sentinel to be defined before the parameters whose decoding it affects', function (st) { + st.deepEqual(qs.parse('a=' + urlEncodedOSlashInUtf8 + '&utf8=' + urlEncodedNumCheckmark, { charsetSentinel: true, charset: 'utf-8' }), { a: 'ø' }); + st.end(); + }); + + t.test('should ignore an utf8 sentinel with an unknown value', function (st) { + st.deepEqual(qs.parse('utf8=foo&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'utf-8' }), { ø: 'ø' }); + st.end(); + }); + + t.test('uses the utf8 sentinel to switch to utf-8 when no default charset is given', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedCheckmarkInUtf8 + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true }), { ø: 'ø' }); + st.end(); + }); + + t.test('uses the utf8 sentinel to switch to iso-8859-1 when no default charset is given', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedNumCheckmark + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true }), { 'ø': 'ø' }); + st.end(); + }); + + t.test('interprets numeric entities in iso-8859-1 when `interpretNumericEntities`', function (st) { + st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'iso-8859-1', interpretNumericEntities: true }), { foo: '☺' }); + st.end(); + }); + + t.test('handles a custom decoder returning `null`, in the `iso-8859-1` charset, when `interpretNumericEntities`', function (st) { + st.deepEqual(qs.parse('foo=&bar=' + urlEncodedNumSmiley, { + charset: 'iso-8859-1', + decoder: function (str, defaultDecoder, charset) { + return str ? defaultDecoder(str, defaultDecoder, charset) : null; + }, + interpretNumericEntities: true + }), { foo: null, bar: '☺' }); + st.end(); + }); + + t.test('does not interpret numeric entities in iso-8859-1 when `interpretNumericEntities` is absent', function (st) { + st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'iso-8859-1' }), { foo: '☺' }); + st.end(); + }); + + t.test('does not interpret numeric entities when the charset is utf-8, even when `interpretNumericEntities`', function (st) { + st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'utf-8', interpretNumericEntities: true }), { foo: '☺' }); + st.end(); + }); + + t.test('does not interpret %uXXXX syntax in iso-8859-1 mode', function (st) { + st.deepEqual(qs.parse('%u263A=%u263A', { charset: 'iso-8859-1' }), { '%u263A': '%u263A' }); + st.end(); + }); + + t.test('allows for decoding keys and values differently', function (st) { + var decoder = function (str, defaultDecoder, charset, type) { + if (type === 'key') { + return defaultDecoder(str, defaultDecoder, charset, type).toLowerCase(); + } + if (type === 'value') { + return defaultDecoder(str, defaultDecoder, charset, type).toUpperCase(); + } + throw 'this should never happen! type: ' + type; + }; + + st.deepEqual(qs.parse('KeY=vAlUe', { decoder: decoder }), { key: 'VALUE' }); + st.end(); + }); + + t.end(); +}); + +test('parses empty keys', function (t) { + emptyTestCases.forEach(function (testCase) { + t.test('skips empty string key with ' + testCase.input, function (st) { + st.deepEqual(qs.parse(testCase.input), testCase.noEmptyKeys); + + st.end(); + }); + }); +}); + +test('`duplicates` option', function (t) { + v.nonStrings.concat('not a valid option').forEach(function (invalidOption) { + if (typeof invalidOption !== 'undefined') { + t['throws']( + function () { qs.parse('', { duplicates: invalidOption }); }, + TypeError, + 'throws on invalid option: ' + inspect(invalidOption) + ); + } + }); + + t.deepEqual( + qs.parse('foo=bar&foo=baz'), + { foo: ['bar', 'baz'] }, + 'duplicates: default, combine' + ); + + t.deepEqual( + qs.parse('foo=bar&foo=baz', { duplicates: 'combine' }), + { foo: ['bar', 'baz'] }, + 'duplicates: combine' + ); + + t.deepEqual( + qs.parse('foo=bar&foo=baz', { duplicates: 'first' }), + { foo: 'bar' }, + 'duplicates: first' + ); + + t.deepEqual( + qs.parse('foo=bar&foo=baz', { duplicates: 'last' }), + { foo: 'baz' }, + 'duplicates: last' + ); + + t.end(); +}); diff --git a/node_modules/superagent/node_modules/qs/test/stringify.js b/node_modules/superagent/node_modules/qs/test/stringify.js new file mode 100644 index 000000000..ea3d0abdd --- /dev/null +++ b/node_modules/superagent/node_modules/qs/test/stringify.js @@ -0,0 +1,1255 @@ +'use strict'; + +var test = require('tape'); +var qs = require('../'); +var utils = require('../lib/utils'); +var iconv = require('iconv-lite'); +var SaferBuffer = require('safer-buffer').Buffer; +var hasSymbols = require('has-symbols'); +var mockProperty = require('mock-property'); +var emptyTestCases = require('./empty-keys-cases').emptyTestCases; +var hasBigInt = typeof BigInt === 'function'; + +test('stringify()', function (t) { + t.test('stringifies a querystring object', function (st) { + st.equal(qs.stringify({ a: 'b' }), 'a=b'); + st.equal(qs.stringify({ a: 1 }), 'a=1'); + st.equal(qs.stringify({ a: 1, b: 2 }), 'a=1&b=2'); + st.equal(qs.stringify({ a: 'A_Z' }), 'a=A_Z'); + st.equal(qs.stringify({ a: '€' }), 'a=%E2%82%AC'); + st.equal(qs.stringify({ a: '' }), 'a=%EE%80%80'); + st.equal(qs.stringify({ a: 'א' }), 'a=%D7%90'); + st.equal(qs.stringify({ a: '𐐷' }), 'a=%F0%90%90%B7'); + st.end(); + }); + + t.test('stringifies falsy values', function (st) { + st.equal(qs.stringify(undefined), ''); + st.equal(qs.stringify(null), ''); + st.equal(qs.stringify(null, { strictNullHandling: true }), ''); + st.equal(qs.stringify(false), ''); + st.equal(qs.stringify(0), ''); + st.end(); + }); + + t.test('stringifies symbols', { skip: !hasSymbols() }, function (st) { + st.equal(qs.stringify(Symbol.iterator), ''); + st.equal(qs.stringify([Symbol.iterator]), '0=Symbol%28Symbol.iterator%29'); + st.equal(qs.stringify({ a: Symbol.iterator }), 'a=Symbol%28Symbol.iterator%29'); + st.equal( + qs.stringify({ a: [Symbol.iterator] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), + 'a[]=Symbol%28Symbol.iterator%29' + ); + st.end(); + }); + + t.test('stringifies bigints', { skip: !hasBigInt }, function (st) { + var three = BigInt(3); + var encodeWithN = function (value, defaultEncoder, charset) { + var result = defaultEncoder(value, defaultEncoder, charset); + return typeof value === 'bigint' ? result + 'n' : result; + }; + st.equal(qs.stringify(three), ''); + st.equal(qs.stringify([three]), '0=3'); + st.equal(qs.stringify([three], { encoder: encodeWithN }), '0=3n'); + st.equal(qs.stringify({ a: three }), 'a=3'); + st.equal(qs.stringify({ a: three }, { encoder: encodeWithN }), 'a=3n'); + st.equal( + qs.stringify({ a: [three] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), + 'a[]=3' + ); + st.equal( + qs.stringify({ a: [three] }, { encodeValuesOnly: true, encoder: encodeWithN, arrayFormat: 'brackets' }), + 'a[]=3n' + ); + st.end(); + }); + + t.test('encodes dot in key of object when encodeDotInKeys and allowDots is provided', function (st) { + st.equal( + qs.stringify( + { 'name.obj': { first: 'John', last: 'Doe' } }, + { allowDots: false, encodeDotInKeys: false } + ), + 'name.obj%5Bfirst%5D=John&name.obj%5Blast%5D=Doe', + 'with allowDots false and encodeDotInKeys false' + ); + st.equal( + qs.stringify( + { 'name.obj': { first: 'John', last: 'Doe' } }, + { allowDots: true, encodeDotInKeys: false } + ), + 'name.obj.first=John&name.obj.last=Doe', + 'with allowDots true and encodeDotInKeys false' + ); + st.equal( + qs.stringify( + { 'name.obj': { first: 'John', last: 'Doe' } }, + { allowDots: false, encodeDotInKeys: true } + ), + 'name%252Eobj%5Bfirst%5D=John&name%252Eobj%5Blast%5D=Doe', + 'with allowDots false and encodeDotInKeys true' + ); + st.equal( + qs.stringify( + { 'name.obj': { first: 'John', last: 'Doe' } }, + { allowDots: true, encodeDotInKeys: true } + ), + 'name%252Eobj.first=John&name%252Eobj.last=Doe', + 'with allowDots true and encodeDotInKeys true' + ); + + st.equal( + qs.stringify( + { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, + { allowDots: false, encodeDotInKeys: false } + ), + 'name.obj.subobject%5Bfirst.godly.name%5D=John&name.obj.subobject%5Blast%5D=Doe', + 'with allowDots false and encodeDotInKeys false' + ); + st.equal( + qs.stringify( + { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, + { allowDots: true, encodeDotInKeys: false } + ), + 'name.obj.subobject.first.godly.name=John&name.obj.subobject.last=Doe', + 'with allowDots false and encodeDotInKeys false' + ); + st.equal( + qs.stringify( + { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, + { allowDots: false, encodeDotInKeys: true } + ), + 'name%252Eobj%252Esubobject%5Bfirst.godly.name%5D=John&name%252Eobj%252Esubobject%5Blast%5D=Doe', + 'with allowDots false and encodeDotInKeys true' + ); + st.equal( + qs.stringify( + { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, + { allowDots: true, encodeDotInKeys: true } + ), + 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe', + 'with allowDots true and encodeDotInKeys true' + ); + + st.end(); + }); + + t.test('should encode dot in key of object, and automatically set allowDots to `true` when encodeDotInKeys is true and allowDots in undefined', function (st) { + st.equal( + qs.stringify( + { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, + { encodeDotInKeys: true } + ), + 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe', + 'with allowDots undefined and encodeDotInKeys true' + ); + st.end(); + }); + + t.test('should encode dot in key of object when encodeDotInKeys and allowDots is provided, and nothing else when encodeValuesOnly is provided', function (st) { + st.equal( + qs.stringify({ 'name.obj': { first: 'John', last: 'Doe' } }, { + encodeDotInKeys: true, allowDots: true, encodeValuesOnly: true + }), + 'name%2Eobj.first=John&name%2Eobj.last=Doe' + ); + + st.equal( + qs.stringify({ 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } }, { allowDots: true, encodeDotInKeys: true, encodeValuesOnly: true }), + 'name%2Eobj%2Esubobject.first%2Egodly%2Ename=John&name%2Eobj%2Esubobject.last=Doe' + ); + + st.end(); + }); + + t.test('should throw when encodeDotInKeys is not of type boolean', function (st) { + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { encodeDotInKeys: 'foobar' }); }, + TypeError + ); + + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { encodeDotInKeys: 0 }); }, + TypeError + ); + + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { encodeDotInKeys: NaN }); }, + TypeError + ); + + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { encodeDotInKeys: null }); }, + TypeError + ); + + st.end(); + }); + + t.test('adds query prefix', function (st) { + st.equal(qs.stringify({ a: 'b' }, { addQueryPrefix: true }), '?a=b'); + st.end(); + }); + + t.test('with query prefix, outputs blank string given an empty object', function (st) { + st.equal(qs.stringify({}, { addQueryPrefix: true }), ''); + st.end(); + }); + + t.test('stringifies nested falsy values', function (st) { + st.equal(qs.stringify({ a: { b: { c: null } } }), 'a%5Bb%5D%5Bc%5D='); + st.equal(qs.stringify({ a: { b: { c: null } } }, { strictNullHandling: true }), 'a%5Bb%5D%5Bc%5D'); + st.equal(qs.stringify({ a: { b: { c: false } } }), 'a%5Bb%5D%5Bc%5D=false'); + st.end(); + }); + + t.test('stringifies a nested object', function (st) { + st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); + st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }), 'a%5Bb%5D%5Bc%5D%5Bd%5D=e'); + st.end(); + }); + + t.test('`allowDots` option: stringifies a nested object with dots notation', function (st) { + st.equal(qs.stringify({ a: { b: 'c' } }, { allowDots: true }), 'a.b=c'); + st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }, { allowDots: true }), 'a.b.c.d=e'); + st.end(); + }); + + t.test('stringifies an array value', function (st) { + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'indices' }), + 'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d', + 'indices => indices' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'brackets' }), + 'a%5B%5D=b&a%5B%5D=c&a%5B%5D=d', + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'comma' }), + 'a=b%2Cc%2Cd', + 'comma => comma' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'comma', commaRoundTrip: true }), + 'a=b%2Cc%2Cd', + 'comma round trip => comma' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }), + 'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d', + 'default => indices' + ); + st.end(); + }); + + t.test('`skipNulls` option', function (st) { + st.equal( + qs.stringify({ a: 'b', c: null }, { skipNulls: true }), + 'a=b', + 'omits nulls when asked' + ); + + st.equal( + qs.stringify({ a: { b: 'c', d: null } }, { skipNulls: true }), + 'a%5Bb%5D=c', + 'omits nested nulls when asked' + ); + + st.end(); + }); + + t.test('omits array indices when asked', function (st) { + st.equal(qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }), 'a=b&a=c&a=d'); + + st.end(); + }); + + t.test('omits object key/value pair when value is empty array', function (st) { + st.equal(qs.stringify({ a: [], b: 'zz' }), 'b=zz'); + + st.end(); + }); + + t.test('should not omit object key/value pair when value is empty array and when asked', function (st) { + st.equal(qs.stringify({ a: [], b: 'zz' }), 'b=zz'); + st.equal(qs.stringify({ a: [], b: 'zz' }, { allowEmptyArrays: false }), 'b=zz'); + st.equal(qs.stringify({ a: [], b: 'zz' }, { allowEmptyArrays: true }), 'a[]&b=zz'); + + st.end(); + }); + + t.test('should throw when allowEmptyArrays is not of type boolean', function (st) { + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { allowEmptyArrays: 'foobar' }); }, + TypeError + ); + + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { allowEmptyArrays: 0 }); }, + TypeError + ); + + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { allowEmptyArrays: NaN }); }, + TypeError + ); + + st['throws']( + function () { qs.stringify({ a: [], b: 'zz' }, { allowEmptyArrays: null }); }, + TypeError + ); + + st.end(); + }); + + t.test('stringifies an array value with one item vs multiple items', function (st) { + st.test('non-array item', function (s2t) { + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a=c'); + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a=c'); + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c'); + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true }), 'a=c'); + + s2t.end(); + }); + + st.test('array with a single item', function (s2t) { + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[0]=c'); + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=c'); + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c'); + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'comma', commaRoundTrip: true }), 'a[]=c'); // so it parses back as an array + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true }), 'a[0]=c'); + + s2t.end(); + }); + + st.test('array with multiple items', function (s2t) { + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[0]=c&a[1]=d'); + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=c&a[]=d'); + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c,d'); + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'comma', commaRoundTrip: true }), 'a=c,d'); + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true }), 'a[0]=c&a[1]=d'); + + s2t.end(); + }); + + st.test('array with multiple items with a comma inside', function (s2t) { + s2t.equal(qs.stringify({ a: ['c,d', 'e'] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c%2Cd,e'); + s2t.equal(qs.stringify({ a: ['c,d', 'e'] }, { arrayFormat: 'comma' }), 'a=c%2Cd%2Ce'); + + s2t.equal(qs.stringify({ a: ['c,d', 'e'] }, { encodeValuesOnly: true, arrayFormat: 'comma', commaRoundTrip: true }), 'a=c%2Cd,e'); + s2t.equal(qs.stringify({ a: ['c,d', 'e'] }, { arrayFormat: 'comma', commaRoundTrip: true }), 'a=c%2Cd%2Ce'); + + s2t.end(); + }); + + st.end(); + }); + + t.test('stringifies a nested array value', function (st) { + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[b][0]=c&a[b][1]=d'); + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[b][]=c&a[b][]=d'); + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a[b]=c,d'); + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true }), 'a[b][0]=c&a[b][1]=d'); + st.end(); + }); + + t.test('stringifies comma and empty array values', function (st) { + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'indices' }), 'a[0]=,&a[1]=&a[2]=c,d%'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'brackets' }), 'a[]=,&a[]=&a[]=c,d%'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'comma' }), 'a=,,,c,d%'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'repeat' }), 'a=,&a=&a=c,d%'); + + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[0]=%2C&a[1]=&a[2]=c%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=%2C&a[]=&a[]=c%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=%2C,,c%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: true, arrayFormat: 'repeat' }), 'a=%2C&a=&a=c%2Cd%25'); + + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'indices' }), 'a%5B0%5D=%2C&a%5B1%5D=&a%5B2%5D=c%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'brackets' }), 'a%5B%5D=%2C&a%5B%5D=&a%5B%5D=c%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'comma' }), 'a=%2C%2C%2Cc%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'repeat' }), 'a=%2C&a=&a=c%2Cd%25'); + + st.end(); + }); + + t.test('stringifies comma and empty non-array values', function (st) { + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'indices' }), 'a=,&b=&c=c,d%'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'brackets' }), 'a=,&b=&c=c,d%'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'comma' }), 'a=,&b=&c=c,d%'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'repeat' }), 'a=,&b=&c=c,d%'); + + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: true, arrayFormat: 'indices' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: true, arrayFormat: 'repeat' }), 'a=%2C&b=&c=c%2Cd%25'); + + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: false, arrayFormat: 'indices' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: false, arrayFormat: 'brackets' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: false, arrayFormat: 'comma' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: false, arrayFormat: 'repeat' }), 'a=%2C&b=&c=c%2Cd%25'); + + st.end(); + }); + + t.test('stringifies a nested array value with dots notation', function (st) { + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encodeValuesOnly: true, arrayFormat: 'indices' } + ), + 'a.b[0]=c&a.b[1]=d', + 'indices: stringifies with dots + indices' + ); + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encodeValuesOnly: true, arrayFormat: 'brackets' } + ), + 'a.b[]=c&a.b[]=d', + 'brackets: stringifies with dots + brackets' + ); + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encodeValuesOnly: true, arrayFormat: 'comma' } + ), + 'a.b=c,d', + 'comma: stringifies with dots + comma' + ); + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encodeValuesOnly: true } + ), + 'a.b[0]=c&a.b[1]=d', + 'default: stringifies with dots + indices' + ); + st.end(); + }); + + t.test('stringifies an object inside an array', function (st) { + st.equal( + qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'indices', encodeValuesOnly: true }), + 'a[0][b]=c', + 'indices => indices' + ); + st.equal( + qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'repeat', encodeValuesOnly: true }), + 'a[b]=c', + 'repeat => repeat' + ); + st.equal( + qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'brackets', encodeValuesOnly: true }), + 'a[][b]=c', + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: [{ b: 'c' }] }, { encodeValuesOnly: true }), + 'a[0][b]=c', + 'default => indices' + ); + + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'indices', encodeValuesOnly: true }), + 'a[0][b][c][0]=1', + 'indices => indices' + ); + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'repeat', encodeValuesOnly: true }), + 'a[b][c]=1', + 'repeat => repeat' + ); + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'brackets', encodeValuesOnly: true }), + 'a[][b][c][]=1', + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }, { encodeValuesOnly: true }), + 'a[0][b][c][0]=1', + 'default => indices' + ); + + st.end(); + }); + + t.test('stringifies an array with mixed objects and primitives', function (st) { + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), + 'a[0][b]=1&a[1]=2&a[2]=3', + 'indices => indices' + ); + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), + 'a[][b]=1&a[]=2&a[]=3', + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), + '???', + 'brackets => brackets', + { skip: 'TODO: figure out what this should do' } + ); + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true }), + 'a[0][b]=1&a[1]=2&a[2]=3', + 'default => indices' + ); + + st.end(); + }); + + t.test('stringifies an object inside an array with dots notation', function (st) { + st.equal( + qs.stringify( + { a: [{ b: 'c' }] }, + { allowDots: true, encode: false, arrayFormat: 'indices' } + ), + 'a[0].b=c', + 'indices => indices' + ); + st.equal( + qs.stringify( + { a: [{ b: 'c' }] }, + { allowDots: true, encode: false, arrayFormat: 'brackets' } + ), + 'a[].b=c', + 'brackets => brackets' + ); + st.equal( + qs.stringify( + { a: [{ b: 'c' }] }, + { allowDots: true, encode: false } + ), + 'a[0].b=c', + 'default => indices' + ); + + st.equal( + qs.stringify( + { a: [{ b: { c: [1] } }] }, + { allowDots: true, encode: false, arrayFormat: 'indices' } + ), + 'a[0].b.c[0]=1', + 'indices => indices' + ); + st.equal( + qs.stringify( + { a: [{ b: { c: [1] } }] }, + { allowDots: true, encode: false, arrayFormat: 'brackets' } + ), + 'a[].b.c[]=1', + 'brackets => brackets' + ); + st.equal( + qs.stringify( + { a: [{ b: { c: [1] } }] }, + { allowDots: true, encode: false } + ), + 'a[0].b.c[0]=1', + 'default => indices' + ); + + st.end(); + }); + + t.test('does not omit object keys when indices = false', function (st) { + st.equal(qs.stringify({ a: [{ b: 'c' }] }, { indices: false }), 'a%5Bb%5D=c'); + st.end(); + }); + + t.test('uses indices notation for arrays when indices=true', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { indices: true }), 'a%5B0%5D=b&a%5B1%5D=c'); + st.end(); + }); + + t.test('uses indices notation for arrays when no arrayFormat is specified', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }), 'a%5B0%5D=b&a%5B1%5D=c'); + st.end(); + }); + + t.test('uses indices notation for arrays when arrayFormat=indices', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }), 'a%5B0%5D=b&a%5B1%5D=c'); + st.end(); + }); + + t.test('uses repeat notation for arrays when arrayFormat=repeat', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }), 'a=b&a=c'); + st.end(); + }); + + t.test('uses brackets notation for arrays when arrayFormat=brackets', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }), 'a%5B%5D=b&a%5B%5D=c'); + st.end(); + }); + + t.test('stringifies a complicated object', function (st) { + st.equal(qs.stringify({ a: { b: 'c', d: 'e' } }), 'a%5Bb%5D=c&a%5Bd%5D=e'); + st.end(); + }); + + t.test('stringifies an empty value', function (st) { + st.equal(qs.stringify({ a: '' }), 'a='); + st.equal(qs.stringify({ a: null }, { strictNullHandling: true }), 'a'); + + st.equal(qs.stringify({ a: '', b: '' }), 'a=&b='); + st.equal(qs.stringify({ a: null, b: '' }, { strictNullHandling: true }), 'a&b='); + + st.equal(qs.stringify({ a: { b: '' } }), 'a%5Bb%5D='); + st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: true }), 'a%5Bb%5D'); + st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: false }), 'a%5Bb%5D='); + + st.end(); + }); + + t.test('stringifies an empty array in different arrayFormat', function (st) { + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false }), 'b[0]=&c=c'); + // arrayFormat default + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices' }), 'b[0]=&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets' }), 'b[]=&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat' }), 'b=&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma' }), 'b=&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', commaRoundTrip: true }), 'b[]=&c=c'); + // with strictNullHandling + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices', strictNullHandling: true }), 'b[0]&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets', strictNullHandling: true }), 'b[]&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat', strictNullHandling: true }), 'b&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', strictNullHandling: true }), 'b&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', strictNullHandling: true, commaRoundTrip: true }), 'b[]&c=c'); + // with skipNulls + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices', skipNulls: true }), 'c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets', skipNulls: true }), 'c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat', skipNulls: true }), 'c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', skipNulls: true }), 'c=c'); + + st.end(); + }); + + t.test('stringifies a null object', { skip: !Object.create }, function (st) { + var obj = Object.create(null); + obj.a = 'b'; + st.equal(qs.stringify(obj), 'a=b'); + st.end(); + }); + + t.test('returns an empty string for invalid input', function (st) { + st.equal(qs.stringify(undefined), ''); + st.equal(qs.stringify(false), ''); + st.equal(qs.stringify(null), ''); + st.equal(qs.stringify(''), ''); + st.end(); + }); + + t.test('stringifies an object with a null object as a child', { skip: !Object.create }, function (st) { + var obj = { a: Object.create(null) }; + + obj.a.b = 'c'; + st.equal(qs.stringify(obj), 'a%5Bb%5D=c'); + st.end(); + }); + + t.test('drops keys with a value of undefined', function (st) { + st.equal(qs.stringify({ a: undefined }), ''); + + st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: true }), 'a%5Bc%5D'); + st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: false }), 'a%5Bc%5D='); + st.equal(qs.stringify({ a: { b: undefined, c: '' } }), 'a%5Bc%5D='); + st.end(); + }); + + t.test('url encodes values', function (st) { + st.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); + st.end(); + }); + + t.test('stringifies a date', function (st) { + var now = new Date(); + var str = 'a=' + encodeURIComponent(now.toISOString()); + st.equal(qs.stringify({ a: now }), str); + st.end(); + }); + + t.test('stringifies the weird object from qs', function (st) { + st.equal(qs.stringify({ 'my weird field': '~q1!2"\'w$5&7/z8)?' }), 'my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F'); + st.end(); + }); + + t.test('skips properties that are part of the object prototype', function (st) { + st.intercept(Object.prototype, 'crash', { value: 'test' }); + + st.equal(qs.stringify({ a: 'b' }), 'a=b'); + st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); + + st.end(); + }); + + t.test('stringifies boolean values', function (st) { + st.equal(qs.stringify({ a: true }), 'a=true'); + st.equal(qs.stringify({ a: { b: true } }), 'a%5Bb%5D=true'); + st.equal(qs.stringify({ b: false }), 'b=false'); + st.equal(qs.stringify({ b: { c: false } }), 'b%5Bc%5D=false'); + st.end(); + }); + + t.test('stringifies buffer values', function (st) { + st.equal(qs.stringify({ a: SaferBuffer.from('test') }), 'a=test'); + st.equal(qs.stringify({ a: { b: SaferBuffer.from('test') } }), 'a%5Bb%5D=test'); + st.end(); + }); + + t.test('stringifies an object using an alternative delimiter', function (st) { + st.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d'); + st.end(); + }); + + t.test('does not blow up when Buffer global is missing', function (st) { + var restore = mockProperty(global, 'Buffer', { 'delete': true }); + + var result = qs.stringify({ a: 'b', c: 'd' }); + + restore(); + + st.equal(result, 'a=b&c=d'); + st.end(); + }); + + t.test('does not crash when parsing circular references', function (st) { + var a = {}; + a.b = a; + + st['throws']( + function () { qs.stringify({ 'foo[bar]': 'baz', 'foo[baz]': a }); }, + /RangeError: Cyclic object value/, + 'cyclic values throw' + ); + + var circular = { + a: 'value' + }; + circular.a = circular; + st['throws']( + function () { qs.stringify(circular); }, + /RangeError: Cyclic object value/, + 'cyclic values throw' + ); + + var arr = ['a']; + st.doesNotThrow( + function () { qs.stringify({ x: arr, y: arr }); }, + 'non-cyclic values do not throw' + ); + + st.end(); + }); + + t.test('non-circular duplicated references can still work', function (st) { + var hourOfDay = { + 'function': 'hour_of_day' + }; + + var p1 = { + 'function': 'gte', + arguments: [hourOfDay, 0] + }; + var p2 = { + 'function': 'lte', + arguments: [hourOfDay, 23] + }; + + st.equal( + qs.stringify({ filters: { $and: [p1, p2] } }, { encodeValuesOnly: true, arrayFormat: 'indices' }), + 'filters[$and][0][function]=gte&filters[$and][0][arguments][0][function]=hour_of_day&filters[$and][0][arguments][1]=0&filters[$and][1][function]=lte&filters[$and][1][arguments][0][function]=hour_of_day&filters[$and][1][arguments][1]=23' + ); + st.equal( + qs.stringify({ filters: { $and: [p1, p2] } }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), + 'filters[$and][][function]=gte&filters[$and][][arguments][][function]=hour_of_day&filters[$and][][arguments][]=0&filters[$and][][function]=lte&filters[$and][][arguments][][function]=hour_of_day&filters[$and][][arguments][]=23' + ); + st.equal( + qs.stringify({ filters: { $and: [p1, p2] } }, { encodeValuesOnly: true, arrayFormat: 'repeat' }), + 'filters[$and][function]=gte&filters[$and][arguments][function]=hour_of_day&filters[$and][arguments]=0&filters[$and][function]=lte&filters[$and][arguments][function]=hour_of_day&filters[$and][arguments]=23' + ); + + st.end(); + }); + + t.test('selects properties when filter=array', function (st) { + st.equal(qs.stringify({ a: 'b' }, { filter: ['a'] }), 'a=b'); + st.equal(qs.stringify({ a: 1 }, { filter: [] }), ''); + + st.equal( + qs.stringify( + { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, + { filter: ['a', 'b', 0, 2], arrayFormat: 'indices' } + ), + 'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3', + 'indices => indices' + ); + st.equal( + qs.stringify( + { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, + { filter: ['a', 'b', 0, 2], arrayFormat: 'brackets' } + ), + 'a%5Bb%5D%5B%5D=1&a%5Bb%5D%5B%5D=3', + 'brackets => brackets' + ); + st.equal( + qs.stringify( + { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, + { filter: ['a', 'b', 0, 2] } + ), + 'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3', + 'default => indices' + ); + + st.end(); + }); + + t.test('supports custom representations when filter=function', function (st) { + var calls = 0; + var obj = { a: 'b', c: 'd', e: { f: new Date(1257894000000) } }; + var filterFunc = function (prefix, value) { + calls += 1; + if (calls === 1) { + st.equal(prefix, '', 'prefix is empty'); + st.equal(value, obj); + } else if (prefix === 'c') { + return void 0; + } else if (value instanceof Date) { + st.equal(prefix, 'e[f]'); + return value.getTime(); + } + return value; + }; + + st.equal(qs.stringify(obj, { filter: filterFunc }), 'a=b&e%5Bf%5D=1257894000000'); + st.equal(calls, 5); + st.end(); + }); + + t.test('can disable uri encoding', function (st) { + st.equal(qs.stringify({ a: 'b' }, { encode: false }), 'a=b'); + st.equal(qs.stringify({ a: { b: 'c' } }, { encode: false }), 'a[b]=c'); + st.equal(qs.stringify({ a: 'b', c: null }, { strictNullHandling: true, encode: false }), 'a=b&c'); + st.end(); + }); + + t.test('can sort the keys', function (st) { + var sort = function (a, b) { + return a.localeCompare(b); + }; + st.equal(qs.stringify({ a: 'c', z: 'y', b: 'f' }, { sort: sort }), 'a=c&b=f&z=y'); + st.equal(qs.stringify({ a: 'c', z: { j: 'a', i: 'b' }, b: 'f' }, { sort: sort }), 'a=c&b=f&z%5Bi%5D=b&z%5Bj%5D=a'); + st.end(); + }); + + t.test('can sort the keys at depth 3 or more too', function (st) { + var sort = function (a, b) { + return a.localeCompare(b); + }; + st.equal( + qs.stringify( + { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' }, + { sort: sort, encode: false } + ), + 'a=a&b=b&z[zi][zia]=zia&z[zi][zib]=zib&z[zj][zja]=zja&z[zj][zjb]=zjb' + ); + st.equal( + qs.stringify( + { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' }, + { sort: null, encode: false } + ), + 'a=a&z[zj][zjb]=zjb&z[zj][zja]=zja&z[zi][zib]=zib&z[zi][zia]=zia&b=b' + ); + st.end(); + }); + + t.test('can stringify with custom encoding', function (st) { + st.equal(qs.stringify({ 県: '大阪府', '': '' }, { + encoder: function (str) { + if (str.length === 0) { + return ''; + } + var buf = iconv.encode(str, 'shiftjis'); + var result = []; + for (var i = 0; i < buf.length; ++i) { + result.push(buf.readUInt8(i).toString(16)); + } + return '%' + result.join('%'); + } + }), '%8c%a7=%91%e5%8d%e3%95%7b&='); + st.end(); + }); + + t.test('receives the default encoder as a second argument', function (st) { + st.plan(8); + + qs.stringify({ a: 1, b: new Date(), c: true, d: [1] }, { + encoder: function (str) { + st.match(typeof str, /^(?:string|number|boolean)$/); + return ''; + } + }); + + st.end(); + }); + + t.test('receives the default encoder as a second argument', function (st) { + st.plan(2); + + qs.stringify({ a: 1 }, { + encoder: function (str, defaultEncoder) { + st.equal(defaultEncoder, utils.encode); + } + }); + + st.end(); + }); + + t.test('throws error with wrong encoder', function (st) { + st['throws'](function () { + qs.stringify({}, { encoder: 'string' }); + }, new TypeError('Encoder has to be a function.')); + st.end(); + }); + + t.test('can use custom encoder for a buffer object', { skip: typeof Buffer === 'undefined' }, function (st) { + st.equal(qs.stringify({ a: SaferBuffer.from([1]) }, { + encoder: function (buffer) { + if (typeof buffer === 'string') { + return buffer; + } + return String.fromCharCode(buffer.readUInt8(0) + 97); + } + }), 'a=b'); + + st.equal(qs.stringify({ a: SaferBuffer.from('a b') }, { + encoder: function (buffer) { + return buffer; + } + }), 'a=a b'); + st.end(); + }); + + t.test('serializeDate option', function (st) { + var date = new Date(); + st.equal( + qs.stringify({ a: date }), + 'a=' + date.toISOString().replace(/:/g, '%3A'), + 'default is toISOString' + ); + + var mutatedDate = new Date(); + mutatedDate.toISOString = function () { + throw new SyntaxError(); + }; + st['throws'](function () { + mutatedDate.toISOString(); + }, SyntaxError); + st.equal( + qs.stringify({ a: mutatedDate }), + 'a=' + Date.prototype.toISOString.call(mutatedDate).replace(/:/g, '%3A'), + 'toISOString works even when method is not locally present' + ); + + var specificDate = new Date(6); + st.equal( + qs.stringify( + { a: specificDate }, + { serializeDate: function (d) { return d.getTime() * 7; } } + ), + 'a=42', + 'custom serializeDate function called' + ); + + st.equal( + qs.stringify( + { a: [date] }, + { + serializeDate: function (d) { return d.getTime(); }, + arrayFormat: 'comma' + } + ), + 'a=' + date.getTime(), + 'works with arrayFormat comma' + ); + st.equal( + qs.stringify( + { a: [date] }, + { + serializeDate: function (d) { return d.getTime(); }, + arrayFormat: 'comma', + commaRoundTrip: true + } + ), + 'a%5B%5D=' + date.getTime(), + 'works with arrayFormat comma' + ); + + st.end(); + }); + + t.test('RFC 1738 serialization', function (st) { + st.equal(qs.stringify({ a: 'b c' }, { format: qs.formats.RFC1738 }), 'a=b+c'); + st.equal(qs.stringify({ 'a b': 'c d' }, { format: qs.formats.RFC1738 }), 'a+b=c+d'); + st.equal(qs.stringify({ 'a b': SaferBuffer.from('a b') }, { format: qs.formats.RFC1738 }), 'a+b=a+b'); + + st.equal(qs.stringify({ 'foo(ref)': 'bar' }, { format: qs.formats.RFC1738 }), 'foo(ref)=bar'); + + st.end(); + }); + + t.test('RFC 3986 spaces serialization', function (st) { + st.equal(qs.stringify({ a: 'b c' }, { format: qs.formats.RFC3986 }), 'a=b%20c'); + st.equal(qs.stringify({ 'a b': 'c d' }, { format: qs.formats.RFC3986 }), 'a%20b=c%20d'); + st.equal(qs.stringify({ 'a b': SaferBuffer.from('a b') }, { format: qs.formats.RFC3986 }), 'a%20b=a%20b'); + + st.end(); + }); + + t.test('Backward compatibility to RFC 3986', function (st) { + st.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); + st.equal(qs.stringify({ 'a b': SaferBuffer.from('a b') }), 'a%20b=a%20b'); + + st.end(); + }); + + t.test('Edge cases and unknown formats', function (st) { + ['UFO1234', false, 1234, null, {}, []].forEach(function (format) { + st['throws']( + function () { + qs.stringify({ a: 'b c' }, { format: format }); + }, + new TypeError('Unknown format option provided.') + ); + }); + st.end(); + }); + + t.test('encodeValuesOnly', function (st) { + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, + { encodeValuesOnly: true, arrayFormat: 'indices' } + ), + 'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h', + 'encodeValuesOnly + indices' + ); + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, + { encodeValuesOnly: true, arrayFormat: 'brackets' } + ), + 'a=b&c[]=d&c[]=e%3Df&f[][]=g&f[][]=h', + 'encodeValuesOnly + brackets' + ); + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, + { encodeValuesOnly: true, arrayFormat: 'repeat' } + ), + 'a=b&c=d&c=e%3Df&f=g&f=h', + 'encodeValuesOnly + repeat' + ); + + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e'], f: [['g'], ['h']] }, + { arrayFormat: 'indices' } + ), + 'a=b&c%5B0%5D=d&c%5B1%5D=e&f%5B0%5D%5B0%5D=g&f%5B1%5D%5B0%5D=h', + 'no encodeValuesOnly + indices' + ); + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e'], f: [['g'], ['h']] }, + { arrayFormat: 'brackets' } + ), + 'a=b&c%5B%5D=d&c%5B%5D=e&f%5B%5D%5B%5D=g&f%5B%5D%5B%5D=h', + 'no encodeValuesOnly + brackets' + ); + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e'], f: [['g'], ['h']] }, + { arrayFormat: 'repeat' } + ), + 'a=b&c=d&c=e&f=g&f=h', + 'no encodeValuesOnly + repeat' + ); + + st.end(); + }); + + t.test('encodeValuesOnly - strictNullHandling', function (st) { + st.equal( + qs.stringify( + { a: { b: null } }, + { encodeValuesOnly: true, strictNullHandling: true } + ), + 'a[b]' + ); + st.end(); + }); + + t.test('throws if an invalid charset is specified', function (st) { + st['throws'](function () { + qs.stringify({ a: 'b' }, { charset: 'foobar' }); + }, new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined')); + st.end(); + }); + + t.test('respects a charset of iso-8859-1', function (st) { + st.equal(qs.stringify({ æ: 'æ' }, { charset: 'iso-8859-1' }), '%E6=%E6'); + st.end(); + }); + + t.test('encodes unrepresentable chars as numeric entities in iso-8859-1 mode', function (st) { + st.equal(qs.stringify({ a: '☺' }, { charset: 'iso-8859-1' }), 'a=%26%239786%3B'); + st.end(); + }); + + t.test('respects an explicit charset of utf-8 (the default)', function (st) { + st.equal(qs.stringify({ a: 'æ' }, { charset: 'utf-8' }), 'a=%C3%A6'); + st.end(); + }); + + t.test('`charsetSentinel` option', function (st) { + st.equal( + qs.stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'utf-8' }), + 'utf8=%E2%9C%93&a=%C3%A6', + 'adds the right sentinel when instructed to and the charset is utf-8' + ); + + st.equal( + qs.stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'iso-8859-1' }), + 'utf8=%26%2310003%3B&a=%E6', + 'adds the right sentinel when instructed to and the charset is iso-8859-1' + ); + + st.end(); + }); + + t.test('does not mutate the options argument', function (st) { + var options = {}; + qs.stringify({}, options); + st.deepEqual(options, {}); + st.end(); + }); + + t.test('strictNullHandling works with custom filter', function (st) { + var filter = function (prefix, value) { + return value; + }; + + var options = { strictNullHandling: true, filter: filter }; + st.equal(qs.stringify({ key: null }, options), 'key'); + st.end(); + }); + + t.test('strictNullHandling works with null serializeDate', function (st) { + var serializeDate = function () { + return null; + }; + var options = { strictNullHandling: true, serializeDate: serializeDate }; + var date = new Date(); + st.equal(qs.stringify({ key: date }, options), 'key'); + st.end(); + }); + + t.test('allows for encoding keys and values differently', function (st) { + var encoder = function (str, defaultEncoder, charset, type) { + if (type === 'key') { + return defaultEncoder(str, defaultEncoder, charset, type).toLowerCase(); + } + if (type === 'value') { + return defaultEncoder(str, defaultEncoder, charset, type).toUpperCase(); + } + throw 'this should never happen! type: ' + type; + }; + + st.deepEqual(qs.stringify({ KeY: 'vAlUe' }, { encoder: encoder }), 'key=VALUE'); + st.end(); + }); + + t.test('objects inside arrays', function (st) { + var obj = { a: { b: { c: 'd', e: 'f' } } }; + var withArray = { a: { b: [{ c: 'd', e: 'f' }] } }; + + st.equal(qs.stringify(obj, { encode: false }), 'a[b][c]=d&a[b][e]=f', 'no array, no arrayFormat'); + st.equal(qs.stringify(obj, { encode: false, arrayFormat: 'brackets' }), 'a[b][c]=d&a[b][e]=f', 'no array, bracket'); + st.equal(qs.stringify(obj, { encode: false, arrayFormat: 'indices' }), 'a[b][c]=d&a[b][e]=f', 'no array, indices'); + st.equal(qs.stringify(obj, { encode: false, arrayFormat: 'repeat' }), 'a[b][c]=d&a[b][e]=f', 'no array, repeat'); + st.equal(qs.stringify(obj, { encode: false, arrayFormat: 'comma' }), 'a[b][c]=d&a[b][e]=f', 'no array, comma'); + + st.equal(qs.stringify(withArray, { encode: false }), 'a[b][0][c]=d&a[b][0][e]=f', 'array, no arrayFormat'); + st.equal(qs.stringify(withArray, { encode: false, arrayFormat: 'brackets' }), 'a[b][][c]=d&a[b][][e]=f', 'array, bracket'); + st.equal(qs.stringify(withArray, { encode: false, arrayFormat: 'indices' }), 'a[b][0][c]=d&a[b][0][e]=f', 'array, indices'); + st.equal(qs.stringify(withArray, { encode: false, arrayFormat: 'repeat' }), 'a[b][c]=d&a[b][e]=f', 'array, repeat'); + st.equal( + qs.stringify(withArray, { encode: false, arrayFormat: 'comma' }), + '???', + 'array, comma', + { skip: 'TODO: figure out what this should do' } + ); + + st.end(); + }); + + t.test('stringifies sparse arrays', function (st) { + /* eslint no-sparse-arrays: 0 */ + st.equal(qs.stringify({ a: [, '2', , , '1'] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[1]=2&a[4]=1'); + st.equal(qs.stringify({ a: [, '2', , , '1'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=2&a[]=1'); + st.equal(qs.stringify({ a: [, '2', , , '1'] }, { encodeValuesOnly: true, arrayFormat: 'repeat' }), 'a=2&a=1'); + + st.equal(qs.stringify({ a: [, { b: [, , { c: '1' }] }] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[1][b][2][c]=1'); + st.equal(qs.stringify({ a: [, { b: [, , { c: '1' }] }] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[][b][][c]=1'); + st.equal(qs.stringify({ a: [, { b: [, , { c: '1' }] }] }, { encodeValuesOnly: true, arrayFormat: 'repeat' }), 'a[b][c]=1'); + + st.equal(qs.stringify({ a: [, [, , [, , , { c: '1' }]]] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[1][2][3][c]=1'); + st.equal(qs.stringify({ a: [, [, , [, , , { c: '1' }]]] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[][][][c]=1'); + st.equal(qs.stringify({ a: [, [, , [, , , { c: '1' }]]] }, { encodeValuesOnly: true, arrayFormat: 'repeat' }), 'a[c]=1'); + + st.equal(qs.stringify({ a: [, [, , [, , , { c: [, '1'] }]]] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[1][2][3][c][1]=1'); + st.equal(qs.stringify({ a: [, [, , [, , , { c: [, '1'] }]]] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[][][][c][]=1'); + st.equal(qs.stringify({ a: [, [, , [, , , { c: [, '1'] }]]] }, { encodeValuesOnly: true, arrayFormat: 'repeat' }), 'a[c]=1'); + + st.end(); + }); + + t.end(); +}); + +test('stringifies empty keys', function (t) { + emptyTestCases.forEach(function (testCase) { + t.test('stringifies an object with empty string key with ' + testCase.input, function (st) { + st.deepEqual( + qs.stringify(testCase.withEmptyKeys, { encode: false, arrayFormat: 'indices' }), + testCase.stringifyOutput.indices, + 'test case: ' + testCase.input + ', indices' + ); + st.deepEqual( + qs.stringify(testCase.withEmptyKeys, { encode: false, arrayFormat: 'brackets' }), + testCase.stringifyOutput.brackets, + 'test case: ' + testCase.input + ', brackets' + ); + st.deepEqual( + qs.stringify(testCase.withEmptyKeys, { encode: false, arrayFormat: 'repeat' }), + testCase.stringifyOutput.repeat, + 'test case: ' + testCase.input + ', repeat' + ); + + st.end(); + }); + }); + + t.test('edge case with object/arrays', function (st) { + st.deepEqual(qs.stringify({ '': { '': [2, 3] } }, { encode: false }), '[][0]=2&[][1]=3'); + st.deepEqual(qs.stringify({ '': { '': [2, 3], a: 2 } }, { encode: false }), '[][0]=2&[][1]=3&[a]=2'); + st.deepEqual(qs.stringify({ '': { '': [2, 3] } }, { encode: false, arrayFormat: 'indices' }), '[][0]=2&[][1]=3'); + st.deepEqual(qs.stringify({ '': { '': [2, 3], a: 2 } }, { encode: false, arrayFormat: 'indices' }), '[][0]=2&[][1]=3&[a]=2'); + + st.end(); + }); +}); diff --git a/node_modules/superagent/node_modules/qs/test/utils.js b/node_modules/superagent/node_modules/qs/test/utils.js new file mode 100644 index 000000000..aa84dfdc6 --- /dev/null +++ b/node_modules/superagent/node_modules/qs/test/utils.js @@ -0,0 +1,136 @@ +'use strict'; + +var test = require('tape'); +var inspect = require('object-inspect'); +var SaferBuffer = require('safer-buffer').Buffer; +var forEach = require('for-each'); +var utils = require('../lib/utils'); + +test('merge()', function (t) { + t.deepEqual(utils.merge(null, true), [null, true], 'merges true into null'); + + t.deepEqual(utils.merge(null, [42]), [null, 42], 'merges null into an array'); + + t.deepEqual(utils.merge({ a: 'b' }, { a: 'c' }), { a: ['b', 'c'] }, 'merges two objects with the same key'); + + var oneMerged = utils.merge({ foo: 'bar' }, { foo: { first: '123' } }); + t.deepEqual(oneMerged, { foo: ['bar', { first: '123' }] }, 'merges a standalone and an object into an array'); + + var twoMerged = utils.merge({ foo: ['bar', { first: '123' }] }, { foo: { second: '456' } }); + t.deepEqual(twoMerged, { foo: { 0: 'bar', 1: { first: '123' }, second: '456' } }, 'merges a standalone and two objects into an array'); + + var sandwiched = utils.merge({ foo: ['bar', { first: '123', second: '456' }] }, { foo: 'baz' }); + t.deepEqual(sandwiched, { foo: ['bar', { first: '123', second: '456' }, 'baz'] }, 'merges an object sandwiched by two standalones into an array'); + + var nestedArrays = utils.merge({ foo: ['baz'] }, { foo: ['bar', 'xyzzy'] }); + t.deepEqual(nestedArrays, { foo: ['baz', 'bar', 'xyzzy'] }); + + var noOptionsNonObjectSource = utils.merge({ foo: 'baz' }, 'bar'); + t.deepEqual(noOptionsNonObjectSource, { foo: 'baz', bar: true }); + + t.test( + 'avoids invoking array setters unnecessarily', + { skip: typeof Object.defineProperty !== 'function' }, + function (st) { + var setCount = 0; + var getCount = 0; + var observed = []; + Object.defineProperty(observed, 0, { + get: function () { + getCount += 1; + return { bar: 'baz' }; + }, + set: function () { setCount += 1; } + }); + utils.merge(observed, [null]); + st.equal(setCount, 0); + st.equal(getCount, 1); + observed[0] = observed[0]; // eslint-disable-line no-self-assign + st.equal(setCount, 1); + st.equal(getCount, 2); + st.end(); + } + ); + + t.end(); +}); + +test('assign()', function (t) { + var target = { a: 1, b: 2 }; + var source = { b: 3, c: 4 }; + var result = utils.assign(target, source); + + t.equal(result, target, 'returns the target'); + t.deepEqual(target, { a: 1, b: 3, c: 4 }, 'target and source are merged'); + t.deepEqual(source, { b: 3, c: 4 }, 'source is untouched'); + + t.end(); +}); + +test('combine()', function (t) { + t.test('both arrays', function (st) { + var a = [1]; + var b = [2]; + var combined = utils.combine(a, b); + + st.deepEqual(a, [1], 'a is not mutated'); + st.deepEqual(b, [2], 'b is not mutated'); + st.notEqual(a, combined, 'a !== combined'); + st.notEqual(b, combined, 'b !== combined'); + st.deepEqual(combined, [1, 2], 'combined is a + b'); + + st.end(); + }); + + t.test('one array, one non-array', function (st) { + var aN = 1; + var a = [aN]; + var bN = 2; + var b = [bN]; + + var combinedAnB = utils.combine(aN, b); + st.deepEqual(b, [bN], 'b is not mutated'); + st.notEqual(aN, combinedAnB, 'aN + b !== aN'); + st.notEqual(a, combinedAnB, 'aN + b !== a'); + st.notEqual(bN, combinedAnB, 'aN + b !== bN'); + st.notEqual(b, combinedAnB, 'aN + b !== b'); + st.deepEqual([1, 2], combinedAnB, 'first argument is array-wrapped when not an array'); + + var combinedABn = utils.combine(a, bN); + st.deepEqual(a, [aN], 'a is not mutated'); + st.notEqual(aN, combinedABn, 'a + bN !== aN'); + st.notEqual(a, combinedABn, 'a + bN !== a'); + st.notEqual(bN, combinedABn, 'a + bN !== bN'); + st.notEqual(b, combinedABn, 'a + bN !== b'); + st.deepEqual([1, 2], combinedABn, 'second argument is array-wrapped when not an array'); + + st.end(); + }); + + t.test('neither is an array', function (st) { + var combined = utils.combine(1, 2); + st.notEqual(1, combined, '1 + 2 !== 1'); + st.notEqual(2, combined, '1 + 2 !== 2'); + st.deepEqual([1, 2], combined, 'both arguments are array-wrapped when not an array'); + + st.end(); + }); + + t.end(); +}); + +test('isBuffer()', function (t) { + forEach([null, undefined, true, false, '', 'abc', 42, 0, NaN, {}, [], function () {}, /a/g], function (x) { + t.equal(utils.isBuffer(x), false, inspect(x) + ' is not a buffer'); + }); + + var fakeBuffer = { constructor: Buffer }; + t.equal(utils.isBuffer(fakeBuffer), false, 'fake buffer is not a buffer'); + + var saferBuffer = SaferBuffer.from('abc'); + t.equal(utils.isBuffer(saferBuffer), true, 'SaferBuffer instance is a buffer'); + + var buffer = Buffer.from && Buffer.alloc ? Buffer.from('abc') : new Buffer('abc'); + t.equal(utils.isBuffer(buffer), true, 'real Buffer instance is a buffer'); + t.end(); +}); diff --git a/node_modules/superagent/node_modules/semver/LICENSE b/node_modules/superagent/node_modules/semver/LICENSE new file mode 100644 index 000000000..19129e315 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/superagent/node_modules/semver/README.md b/node_modules/superagent/node_modules/semver/README.md new file mode 100644 index 000000000..a9d3a2780 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/README.md @@ -0,0 +1,641 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Install + +```bash +npm install semver +```` + +## Usage + +As a node module: + +```js +const semver = require('semver') + +semver.valid('1.2.3') // '1.2.3' +semver.valid('a.b.c') // null +semver.clean(' =v1.2.3 ') // '1.2.3' +semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true +semver.gt('1.2.3', '9.8.7') // false +semver.lt('1.2.3', '9.8.7') // true +semver.minVersion('>=1.0.0') // '1.0.0' +semver.valid(semver.coerce('v2')) // '2.0.0' +semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' +``` + +You can also just load the module for the function that you care about, if +you'd like to minimize your footprint. + +```js +// load the whole API at once in a single object +const semver = require('semver') + +// or just load the bits you need +// all of them listed here, just pick and choose what you want + +// classes +const SemVer = require('semver/classes/semver') +const Comparator = require('semver/classes/comparator') +const Range = require('semver/classes/range') + +// functions for working with versions +const semverParse = require('semver/functions/parse') +const semverValid = require('semver/functions/valid') +const semverClean = require('semver/functions/clean') +const semverInc = require('semver/functions/inc') +const semverDiff = require('semver/functions/diff') +const semverMajor = require('semver/functions/major') +const semverMinor = require('semver/functions/minor') +const semverPatch = require('semver/functions/patch') +const semverPrerelease = require('semver/functions/prerelease') +const semverCompare = require('semver/functions/compare') +const semverRcompare = require('semver/functions/rcompare') +const semverCompareLoose = require('semver/functions/compare-loose') +const semverCompareBuild = require('semver/functions/compare-build') +const semverSort = require('semver/functions/sort') +const semverRsort = require('semver/functions/rsort') + +// low-level comparators between versions +const semverGt = require('semver/functions/gt') +const semverLt = require('semver/functions/lt') +const semverEq = require('semver/functions/eq') +const semverNeq = require('semver/functions/neq') +const semverGte = require('semver/functions/gte') +const semverLte = require('semver/functions/lte') +const semverCmp = require('semver/functions/cmp') +const semverCoerce = require('semver/functions/coerce') + +// working with ranges +const semverSatisfies = require('semver/functions/satisfies') +const semverMaxSatisfying = require('semver/ranges/max-satisfying') +const semverMinSatisfying = require('semver/ranges/min-satisfying') +const semverToComparators = require('semver/ranges/to-comparators') +const semverMinVersion = require('semver/ranges/min-version') +const semverValidRange = require('semver/ranges/valid') +const semverOutside = require('semver/ranges/outside') +const semverGtr = require('semver/ranges/gtr') +const semverLtr = require('semver/ranges/ltr') +const semverIntersects = require('semver/ranges/intersects') +const simplifyRange = require('semver/ranges/simplify') +const rangeSubset = require('semver/ranges/subset') +``` + +As a command-line utility: + +``` +$ semver -h + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-n <0|1> + This is the base to be used for the prerelease identifier. + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them. +``` + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. + +## Ranges + +A `version range` is a set of `comparators` which specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional, but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. The comparator `>1` is equivalent to `>=2.0.0` and +would match the versions `2.0.0` and `3.1.0`, but not the versions +`1.0.1` or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. The +version `3.4.5` *would* satisfy the range, because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose for this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range matching +semantics. + +Second, a user who has opted into using a prerelease version has +clearly indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +Note that this behavior can be suppressed (treating all prerelease +versions as if they were normal versions, for the purpose of range +matching) by setting the `includePrerelease` flag on the options +object to any +[functions](https://github.com/npm/node-semver#functions) that do +range matching. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta') +// '1.2.4-beta.0' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```bash +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +#### Prerelease Identifier Base + +The method `.inc` takes an optional parameter 'identifierBase' string +that will let you let your prerelease number as zero-based or one-based. +Set to `false` to omit the prerelease number altogether. +If you do not specify this parameter, it will default to zero-based. + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta', '1') +// '1.2.4-beta.1' +``` + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta', false) +// '1.2.4-beta' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta -n 1 +1.2.4-beta.1 +``` + +```bash +$ semver 1.2.3 -i prerelease --preid beta -n false +1.2.4-beta +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0-0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any non-prerelease version satisfies, unless + `includePrerelease` is specified, in which case any version at all + satisfies) +* `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0-0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero element in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0-0` +* `^0.2.3` := `>=0.2.3 <0.3.0-0` +* `^0.0.3` := `>=0.0.3 <0.0.4-0` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0-0` +* `^0.0.x` := `>=0.0.0 <0.1.0-0` +* `^0.0` := `>=0.0.0 <0.1.0-0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0-0` +* `^0.x` := `>=0.0.0 <1.0.0-0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `options` object argument. All +options in this object are `false` by default. The options supported +are: + +- `loose` Be more forgiving about not-quite-valid semver strings. + (Any resulting output will always be 100% strict compliant, of + course.) For backwards compatibility reasons, if the `options` + argument is a boolean value instead of an object, it is interpreted + to be the `loose` param. +- `includePrerelease` Set to suppress the [default + behavior](https://github.com/npm/node-semver#prerelease-tags) of + excluding prerelease tagged versions from ranges unless they are + explicitly opted into. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, release)`: Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, or `prerelease`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, the `prerelease` will work the + same as `prepatch`. It increments the patch version, then makes a + prerelease. If the input version is already a prerelease it simply + increments it. +* `prerelease(v)`: Returns an array of prerelease components, or null + if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. +* `intersects(r1, r2, loose)`: Return true if the two supplied ranges + or comparators intersect. +* `parse(v)`: Attempt to parse a string as a semantic version, returning either + a `SemVer` object or `null`. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the exact same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions + are equal. Sorts in ascending order if passed to `Array.sort()`. + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `diff(v1, v2)`: Returns difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + +### Comparators + +* `intersects(comparator)`: Return true if the comparators intersect + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `minSatisfying(versions, range)`: Return the lowest version in the list + that satisfies the range, or `null` if none of them do. +* `minVersion(range)`: Return the lowest version that can possibly match + the given range. +* `gtr(version, range)`: Return `true` if version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) +* `intersects(range)`: Return true if any of the ranges comparators intersect +* `simplifyRange(versions, range)`: Return a "simplified" range that + matches the same items in `versions` list as the range specified. Note + that it does *not* guarantee that it would match the same versions in all + cases, only for the set of versions provided. This is useful when + generating ranges by joining together multiple versions with `||` + programmatically, to provide the user with something a bit more + ergonomic. If the provided range is shorter in string-length than the + generated range, then that is returned. +* `subset(subRange, superRange)`: Return `true` if the `subRange` range is + entirely contained by the `superRange` range. + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so the version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. + +### Coercion + +* `coerce(version, options)`: Coerces a string to semver if possible + +This aims to provide a very forgiving translation of a non-semver string to +semver. It looks for the first digit in a string, and consumes all +remaining characters which satisfy at least a partial semver (e.g., `1`, +`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer +versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All +surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes +`3.4.0`). Only text which lacks digits will fail coercion (`version one` +is not valid). The maximum length for any semver component considered for +coercion is 16 characters; longer components will be ignored +(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any +semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value +components are invalid (`9999999999999999.4.7.4` is likely invalid). + +If the `options.rtl` flag is set, then `coerce` will return the right-most +coercible tuple that does not share an ending index with a longer coercible +tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not +`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of +any other overlapping SemVer tuple. + +If the `options.includePrerelease` flag is set, then the `coerce` result will contain +prerelease and build parts of a version. For example, `1.2.3.4-rc.1+rev.2` +will preserve prerelease `rc.1` and build `rev.2` in the result. + +### Clean + +* `clean(version)`: Clean a string to be a valid semver if possible + +This will return a cleaned and trimmed semver version. If the provided +version is not valid a null will be returned. This does not work for +ranges. + +ex. +* `s.clean(' = v 2.1.5foo')`: `null` +* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean(' = v 2.1.5-foo')`: `null` +* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean('=v2.1.5')`: `'2.1.5'` +* `s.clean(' =v2.1.5')`: `'2.1.5'` +* `s.clean(' 2.1.5 ')`: `'2.1.5'` +* `s.clean('~1.0.0')`: `null` + +## Constants + +As a convenience, helper constants are exported to provide information about what `node-semver` supports: + +### `RELEASE_TYPES` + +- major +- premajor +- minor +- preminor +- patch +- prepatch +- prerelease + +``` +const semver = require('semver'); + +if (semver.RELEASE_TYPES.includes(arbitraryUserInput)) { + console.log('This is a valid release type!'); +} else { + console.warn('This is NOT a valid release type!'); +} +``` + +### `SEMVER_SPEC_VERSION` + +2.0.0 + +``` +const semver = require('semver'); + +console.log('We are currently using the semver specification version:', semver.SEMVER_SPEC_VERSION); +``` + +## Exported Modules + + + +You may pull in just the part of this semver utility that you need, if you +are sensitive to packing and tree-shaking concerns. The main +`require('semver')` export uses getter functions to lazily load the parts +of the API that are used. + +The following modules are available: + +* `require('semver')` +* `require('semver/classes')` +* `require('semver/classes/comparator')` +* `require('semver/classes/range')` +* `require('semver/classes/semver')` +* `require('semver/functions/clean')` +* `require('semver/functions/cmp')` +* `require('semver/functions/coerce')` +* `require('semver/functions/compare')` +* `require('semver/functions/compare-build')` +* `require('semver/functions/compare-loose')` +* `require('semver/functions/diff')` +* `require('semver/functions/eq')` +* `require('semver/functions/gt')` +* `require('semver/functions/gte')` +* `require('semver/functions/inc')` +* `require('semver/functions/lt')` +* `require('semver/functions/lte')` +* `require('semver/functions/major')` +* `require('semver/functions/minor')` +* `require('semver/functions/neq')` +* `require('semver/functions/parse')` +* `require('semver/functions/patch')` +* `require('semver/functions/prerelease')` +* `require('semver/functions/rcompare')` +* `require('semver/functions/rsort')` +* `require('semver/functions/satisfies')` +* `require('semver/functions/sort')` +* `require('semver/functions/valid')` +* `require('semver/ranges/gtr')` +* `require('semver/ranges/intersects')` +* `require('semver/ranges/ltr')` +* `require('semver/ranges/max-satisfying')` +* `require('semver/ranges/min-satisfying')` +* `require('semver/ranges/min-version')` +* `require('semver/ranges/outside')` +* `require('semver/ranges/to-comparators')` +* `require('semver/ranges/valid')` + diff --git a/node_modules/superagent/node_modules/semver/bin/semver.js b/node_modules/superagent/node_modules/semver/bin/semver.js new file mode 100755 index 000000000..242b7ade7 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/bin/semver.js @@ -0,0 +1,197 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +const argv = process.argv.slice(2) + +let versions = [] + +const range = [] + +let inc = null + +const version = require('../package.json').version + +let loose = false + +let includePrerelease = false + +let coerce = false + +let rtl = false + +let identifier + +let identifierBase + +const semver = require('../') +const parseOptions = require('../internal/parse-options') + +let reverse = false + +let options = {} + +const main = () => { + if (!argv.length) { + return help() + } + while (argv.length) { + let a = argv.shift() + const indexOfEqualSign = a.indexOf('=') + if (indexOfEqualSign !== -1) { + const value = a.slice(indexOfEqualSign + 1) + a = a.slice(0, indexOfEqualSign) + argv.unshift(value) + } + switch (a) { + case '-rv': case '-rev': case '--rev': case '--reverse': + reverse = true + break + case '-l': case '--loose': + loose = true + break + case '-p': case '--include-prerelease': + includePrerelease = true + break + case '-v': case '--version': + versions.push(argv.shift()) + break + case '-i': case '--inc': case '--increment': + switch (argv[0]) { + case 'major': case 'minor': case 'patch': case 'prerelease': + case 'premajor': case 'preminor': case 'prepatch': + inc = argv.shift() + break + default: + inc = 'patch' + break + } + break + case '--preid': + identifier = argv.shift() + break + case '-r': case '--range': + range.push(argv.shift()) + break + case '-n': + identifierBase = argv.shift() + if (identifierBase === 'false') { + identifierBase = false + } + break + case '-c': case '--coerce': + coerce = true + break + case '--rtl': + rtl = true + break + case '--ltr': + rtl = false + break + case '-h': case '--help': case '-?': + return help() + default: + versions.push(a) + break + } + } + + options = parseOptions({ loose, includePrerelease, rtl }) + + versions = versions.map((v) => { + return coerce ? (semver.coerce(v, options) || { version: v }).version : v + }).filter((v) => { + return semver.valid(v) + }) + if (!versions.length) { + return fail() + } + if (inc && (versions.length !== 1 || range.length)) { + return failInc() + } + + for (let i = 0, l = range.length; i < l; i++) { + versions = versions.filter((v) => { + return semver.satisfies(v, range[i], options) + }) + if (!versions.length) { + return fail() + } + } + return success(versions) +} + +const failInc = () => { + console.error('--inc can only be used on a single version with no range') + fail() +} + +const fail = () => process.exit(1) + +const success = () => { + const compare = reverse ? 'rcompare' : 'compare' + versions.sort((a, b) => { + return semver[compare](a, b, options) + }).map((v) => { + return semver.clean(v, options) + }).map((v) => { + return inc ? semver.inc(v, inc, options, identifier, identifierBase) : v + }).forEach((v, i, _) => { + console.log(v) + }) +} + +const help = () => console.log( +`SemVer ${version} + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +-n + Base number to be used for the prerelease identifier. + Can be either 0 or 1, or false to omit the number altogether. + Defaults to 0. + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them.`) + +main() diff --git a/node_modules/superagent/node_modules/semver/classes/comparator.js b/node_modules/superagent/node_modules/semver/classes/comparator.js new file mode 100644 index 000000000..3d39c0eef --- /dev/null +++ b/node_modules/superagent/node_modules/semver/classes/comparator.js @@ -0,0 +1,141 @@ +const ANY = Symbol('SemVer ANY') +// hoisted class for cyclic dependency +class Comparator { + static get ANY () { + return ANY + } + + constructor (comp, options) { + options = parseOptions(options) + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + comp = comp.trim().split(/\s+/).join(' ') + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) + } + + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + const m = comp.match(r) + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) + } + + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } + } + + toString () { + return this.value + } + + test (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY || version === ANY) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range(this.value, options).test(comp.semver) + } + + options = parseOptions(options) + + // Special cases where nothing can possibly be lower + if (options.includePrerelease && + (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { + return false + } + if (!options.includePrerelease && + (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { + return false + } + + // Same direction increasing (> or >=) + if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { + return true + } + // Same direction decreasing (< or <=) + if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { + return true + } + // same SemVer and both sides are inclusive (<= or >=) + if ( + (this.semver.version === comp.semver.version) && + this.operator.includes('=') && comp.operator.includes('=')) { + return true + } + // opposite directions less than + if (cmp(this.semver, '<', comp.semver, options) && + this.operator.startsWith('>') && comp.operator.startsWith('<')) { + return true + } + // opposite directions greater than + if (cmp(this.semver, '>', comp.semver, options) && + this.operator.startsWith('<') && comp.operator.startsWith('>')) { + return true + } + return false + } +} + +module.exports = Comparator + +const parseOptions = require('../internal/parse-options') +const { safeRe: re, t } = require('../internal/re') +const cmp = require('../functions/cmp') +const debug = require('../internal/debug') +const SemVer = require('./semver') +const Range = require('./range') diff --git a/node_modules/superagent/node_modules/semver/classes/index.js b/node_modules/superagent/node_modules/semver/classes/index.js new file mode 100644 index 000000000..5e3f5c9b1 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/classes/index.js @@ -0,0 +1,5 @@ +module.exports = { + SemVer: require('./semver.js'), + Range: require('./range.js'), + Comparator: require('./comparator.js'), +} diff --git a/node_modules/superagent/node_modules/semver/classes/range.js b/node_modules/superagent/node_modules/semver/classes/range.js new file mode 100644 index 000000000..7e7c41410 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/classes/range.js @@ -0,0 +1,539 @@ +// hoisted class for cyclic dependency +class Range { + constructor (range, options) { + options = parseOptions(options) + + if (range instanceof Range) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + // just put it in the set and return + this.raw = range.value + this.set = [[range]] + this.format() + return this + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First reduce all whitespace as much as possible so we do not have to rely + // on potentially slow regexes like \s*. This is then stored and used for + // future error messages as well. + this.raw = range + .trim() + .split(/\s+/) + .join(' ') + + // First, split on || + this.set = this.raw + .split('||') + // map the range to a 2d array of comparators + .map(r => this.parseRange(r.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length) + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${this.raw}`) + } + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0] + this.set = this.set.filter(c => !isNullSet(c[0])) + if (this.set.length === 0) { + this.set = [first] + } else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c] + break + } + } + } + } + + this.format() + } + + format () { + this.range = this.set + .map((comps) => comps.join(' ').trim()) + .join('||') + .trim() + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = + (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | + (this.options.loose && FLAG_LOOSE) + const memoKey = memoOpts + ':' + range + const cached = cache.get(memoKey) + if (cached) { + return cached + } + + const loose = this.options.loose + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) + debug('hyphen replace', range) + + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) + debug('tilde trim', range) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) + debug('caret trim', range) + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + let rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + + if (loose) { + // in loose mode, throw out any that are not valid comparators + rangeList = rangeList.filter(comp => { + debug('loose invalid filter', comp, this.options) + return !!comp.match(re[t.COMPARATORLOOSE]) + }) + } + debug('range list', rangeList) + + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + const rangeMap = new Map() + const comparators = rangeList.map(comp => new Comparator(comp, this.options)) + for (const comp of comparators) { + if (isNullSet(comp)) { + return [comp] + } + rangeMap.set(comp.value, comp) + } + if (rangeMap.size > 1 && rangeMap.has('')) { + rangeMap.delete('') + } + + const result = [...rangeMap.values()] + cache.set(memoKey, result) + return result + } + + intersects (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } + + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + } +} + +module.exports = Range + +const LRU = require('lru-cache') +const cache = new LRU({ max: 1000 }) + +const parseOptions = require('../internal/parse-options') +const Comparator = require('./comparator') +const debug = require('../internal/debug') +const SemVer = require('./semver') +const { + safeRe: re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace, +} = require('../internal/re') +const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants') + +const isNullSet = c => c.value === '<0.0.0-0' +const isAny = c => c.value === '' + +// take a set of comparators and determine whether there +// exists a version which can satisfy it +const isSatisfiable = (comparators, options) => { + let result = true + const remainingComparators = comparators.slice() + let testComparator = remainingComparators.pop() + + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }) + + testComparator = remainingComparators.pop() + } + + return result +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +const parseComparator = (comp, options) => { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +const isX = id => !id || id.toLowerCase() === 'x' || id === '*' + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 +// ~0.0.1 --> >=0.0.1 <0.1.0-0 +const replaceTildes = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceTilde(c, options)) + .join(' ') +} + +const replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, (_, M, m, p, pr) => { + debug('tilde', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0` + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` + } else if (pr) { + debug('replaceTilde pr', pr) + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0` + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 +// ^1.2.3 --> >=1.2.3 <2.0.0-0 +// ^1.2.0 --> >=1.2.0 <2.0.0-0 +// ^0.0.1 --> >=0.0.1 <0.0.2-0 +// ^0.1.0 --> >=0.1.0 <0.2.0-0 +const replaceCarets = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceCaret(c, options)) + .join(' ') +} + +const replaceCaret = (comp, options) => { + debug('caret', comp, options) + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + const z = options.includePrerelease ? '-0' : '' + return comp.replace(r, (_, M, m, p, pr) => { + debug('caret', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0` + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0` + } + } + + debug('caret return', ret) + return ret + }) +} + +const replaceXRanges = (comp, options) => { + debug('replaceXRanges', comp, options) + return comp + .split(/\s+/) + .map((c) => replaceXRange(c, options)) + .join(' ') +} + +const replaceXRange = (comp, options) => { + comp = comp.trim() + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + const xM = isX(M) + const xm = xM || isX(m) + const xp = xm || isX(p) + const anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + if (gtlt === '<') { + pr = '-0' + } + + ret = `${gtlt + M}.${m}.${p}${pr}` + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0` + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +const replaceStars = (comp, options) => { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp + .trim() + .replace(re[t.STAR], '') +} + +const replaceGTE0 = (comp, options) => { + debug('replaceGTE0', comp, options) + return comp + .trim() + .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') +} + +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 +const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}` + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` + } else if (fpr) { + from = `>=${from}` + } else { + from = `>=${from}${incPr ? '-0' : ''}` + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0` + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0` + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}` + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0` + } else { + to = `<=${to}` + } + + return `${from} ${to}`.trim() +} + +const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === Comparator.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} diff --git a/node_modules/superagent/node_modules/semver/classes/semver.js b/node_modules/superagent/node_modules/semver/classes/semver.js new file mode 100644 index 000000000..84e84590e --- /dev/null +++ b/node_modules/superagent/node_modules/semver/classes/semver.js @@ -0,0 +1,302 @@ +const debug = require('../internal/debug') +const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants') +const { safeRe: re, t } = require('../internal/re') + +const parseOptions = require('../internal/parse-options') +const { compareIdentifiers } = require('../internal/identifiers') +class SemVer { + constructor (version, options) { + options = parseOptions(options) + + if (version instanceof SemVer) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease + + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() + } + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}` + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}` + } + return this.version + } + + toString () { + return this.version + } + + compare (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer(other, this.options) + } + + if (other.version === this.version) { + return 0 + } + + return this.compareMain(other) || this.comparePre(other) + } + + compareMain (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } + + comparePre (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + let i = 0 + do { + const a = this.prerelease[i] + const b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + let i = 0 + do { + const a = this.build[i] + const b = other.build[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier, identifierBase) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier, identifierBase) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier, identifierBase) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier, identifierBase) + this.inc('pre', identifier, identifierBase) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier, identifierBase) + } + this.inc('pre', identifier, identifierBase) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': { + const base = Number(identifierBase) ? 1 : 0 + + if (!identifier && identifierBase === false) { + throw new Error('invalid increment argument: identifier is empty') + } + + if (this.prerelease.length === 0) { + this.prerelease = [base] + } else { + let i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + if (identifier === this.prerelease.join('.') && identifierBase === false) { + throw new Error('invalid increment argument: identifier already exists') + } + this.prerelease.push(base) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + let prerelease = [identifier, base] + if (identifierBase === false) { + prerelease = [identifier] + } + if (compareIdentifiers(this.prerelease[0], identifier) === 0) { + if (isNaN(this.prerelease[1])) { + this.prerelease = prerelease + } + } else { + this.prerelease = prerelease + } + } + break + } + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.raw = this.format() + if (this.build.length) { + this.raw += `+${this.build.join('.')}` + } + return this + } +} + +module.exports = SemVer diff --git a/node_modules/superagent/node_modules/semver/functions/clean.js b/node_modules/superagent/node_modules/semver/functions/clean.js new file mode 100644 index 000000000..811fe6b82 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/clean.js @@ -0,0 +1,6 @@ +const parse = require('./parse') +const clean = (version, options) => { + const s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} +module.exports = clean diff --git a/node_modules/superagent/node_modules/semver/functions/cmp.js b/node_modules/superagent/node_modules/semver/functions/cmp.js new file mode 100644 index 000000000..401190947 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/cmp.js @@ -0,0 +1,52 @@ +const eq = require('./eq') +const neq = require('./neq') +const gt = require('./gt') +const gte = require('./gte') +const lt = require('./lt') +const lte = require('./lte') + +const cmp = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a === b + + case '!==': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } +} +module.exports = cmp diff --git a/node_modules/superagent/node_modules/semver/functions/coerce.js b/node_modules/superagent/node_modules/semver/functions/coerce.js new file mode 100644 index 000000000..b378dcea4 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/coerce.js @@ -0,0 +1,60 @@ +const SemVer = require('../classes/semver') +const parse = require('./parse') +const { safeRe: re, t } = require('../internal/re') + +const coerce = (version, options) => { + if (version instanceof SemVer) { + return version + } + + if (typeof version === 'number') { + version = String(version) + } + + if (typeof version !== 'string') { + return null + } + + options = options || {} + + let match = null + if (!options.rtl) { + match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] + let next + while ((next = coerceRtlRegex.exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length + } + // leave it in a clean state + coerceRtlRegex.lastIndex = -1 + } + + if (match === null) { + return null + } + + const major = match[2] + const minor = match[3] || '0' + const patch = match[4] || '0' + const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' + const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' + + return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) +} +module.exports = coerce diff --git a/node_modules/superagent/node_modules/semver/functions/compare-build.js b/node_modules/superagent/node_modules/semver/functions/compare-build.js new file mode 100644 index 000000000..9eb881bef --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/compare-build.js @@ -0,0 +1,7 @@ +const SemVer = require('../classes/semver') +const compareBuild = (a, b, loose) => { + const versionA = new SemVer(a, loose) + const versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) +} +module.exports = compareBuild diff --git a/node_modules/superagent/node_modules/semver/functions/compare-loose.js b/node_modules/superagent/node_modules/semver/functions/compare-loose.js new file mode 100644 index 000000000..4881fbe00 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/compare-loose.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const compareLoose = (a, b) => compare(a, b, true) +module.exports = compareLoose diff --git a/node_modules/superagent/node_modules/semver/functions/compare.js b/node_modules/superagent/node_modules/semver/functions/compare.js new file mode 100644 index 000000000..748b7afa5 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/compare.js @@ -0,0 +1,5 @@ +const SemVer = require('../classes/semver') +const compare = (a, b, loose) => + new SemVer(a, loose).compare(new SemVer(b, loose)) + +module.exports = compare diff --git a/node_modules/superagent/node_modules/semver/functions/diff.js b/node_modules/superagent/node_modules/semver/functions/diff.js new file mode 100644 index 000000000..fc224e302 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/diff.js @@ -0,0 +1,65 @@ +const parse = require('./parse.js') + +const diff = (version1, version2) => { + const v1 = parse(version1, null, true) + const v2 = parse(version2, null, true) + const comparison = v1.compare(v2) + + if (comparison === 0) { + return null + } + + const v1Higher = comparison > 0 + const highVersion = v1Higher ? v1 : v2 + const lowVersion = v1Higher ? v2 : v1 + const highHasPre = !!highVersion.prerelease.length + const lowHasPre = !!lowVersion.prerelease.length + + if (lowHasPre && !highHasPre) { + // Going from prerelease -> no prerelease requires some special casing + + // If the low version has only a major, then it will always be a major + // Some examples: + // 1.0.0-1 -> 1.0.0 + // 1.0.0-1 -> 1.1.1 + // 1.0.0-1 -> 2.0.0 + if (!lowVersion.patch && !lowVersion.minor) { + return 'major' + } + + // Otherwise it can be determined by checking the high version + + if (highVersion.patch) { + // anything higher than a patch bump would result in the wrong version + return 'patch' + } + + if (highVersion.minor) { + // anything higher than a minor bump would result in the wrong version + return 'minor' + } + + // bumping major/minor/patch all have same result + return 'major' + } + + // add the `pre` prefix if we are going to a prerelease version + const prefix = highHasPre ? 'pre' : '' + + if (v1.major !== v2.major) { + return prefix + 'major' + } + + if (v1.minor !== v2.minor) { + return prefix + 'minor' + } + + if (v1.patch !== v2.patch) { + return prefix + 'patch' + } + + // high and low are preleases + return 'prerelease' +} + +module.exports = diff diff --git a/node_modules/superagent/node_modules/semver/functions/eq.js b/node_modules/superagent/node_modules/semver/functions/eq.js new file mode 100644 index 000000000..271fed976 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/eq.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const eq = (a, b, loose) => compare(a, b, loose) === 0 +module.exports = eq diff --git a/node_modules/superagent/node_modules/semver/functions/gt.js b/node_modules/superagent/node_modules/semver/functions/gt.js new file mode 100644 index 000000000..d9b2156d8 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/gt.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const gt = (a, b, loose) => compare(a, b, loose) > 0 +module.exports = gt diff --git a/node_modules/superagent/node_modules/semver/functions/gte.js b/node_modules/superagent/node_modules/semver/functions/gte.js new file mode 100644 index 000000000..5aeaa6347 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/gte.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const gte = (a, b, loose) => compare(a, b, loose) >= 0 +module.exports = gte diff --git a/node_modules/superagent/node_modules/semver/functions/inc.js b/node_modules/superagent/node_modules/semver/functions/inc.js new file mode 100644 index 000000000..7670b1bea --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/inc.js @@ -0,0 +1,19 @@ +const SemVer = require('../classes/semver') + +const inc = (version, release, options, identifier, identifierBase) => { + if (typeof (options) === 'string') { + identifierBase = identifier + identifier = options + options = undefined + } + + try { + return new SemVer( + version instanceof SemVer ? version.version : version, + options + ).inc(release, identifier, identifierBase).version + } catch (er) { + return null + } +} +module.exports = inc diff --git a/node_modules/superagent/node_modules/semver/functions/lt.js b/node_modules/superagent/node_modules/semver/functions/lt.js new file mode 100644 index 000000000..b440ab7d4 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/lt.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const lt = (a, b, loose) => compare(a, b, loose) < 0 +module.exports = lt diff --git a/node_modules/superagent/node_modules/semver/functions/lte.js b/node_modules/superagent/node_modules/semver/functions/lte.js new file mode 100644 index 000000000..6dcc95650 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/lte.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const lte = (a, b, loose) => compare(a, b, loose) <= 0 +module.exports = lte diff --git a/node_modules/superagent/node_modules/semver/functions/major.js b/node_modules/superagent/node_modules/semver/functions/major.js new file mode 100644 index 000000000..4283165e9 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/major.js @@ -0,0 +1,3 @@ +const SemVer = require('../classes/semver') +const major = (a, loose) => new SemVer(a, loose).major +module.exports = major diff --git a/node_modules/superagent/node_modules/semver/functions/minor.js b/node_modules/superagent/node_modules/semver/functions/minor.js new file mode 100644 index 000000000..57b3455f8 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/minor.js @@ -0,0 +1,3 @@ +const SemVer = require('../classes/semver') +const minor = (a, loose) => new SemVer(a, loose).minor +module.exports = minor diff --git a/node_modules/superagent/node_modules/semver/functions/neq.js b/node_modules/superagent/node_modules/semver/functions/neq.js new file mode 100644 index 000000000..f944c0157 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/neq.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const neq = (a, b, loose) => compare(a, b, loose) !== 0 +module.exports = neq diff --git a/node_modules/superagent/node_modules/semver/functions/parse.js b/node_modules/superagent/node_modules/semver/functions/parse.js new file mode 100644 index 000000000..459b3b173 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/parse.js @@ -0,0 +1,16 @@ +const SemVer = require('../classes/semver') +const parse = (version, options, throwErrors = false) => { + if (version instanceof SemVer) { + return version + } + try { + return new SemVer(version, options) + } catch (er) { + if (!throwErrors) { + return null + } + throw er + } +} + +module.exports = parse diff --git a/node_modules/superagent/node_modules/semver/functions/patch.js b/node_modules/superagent/node_modules/semver/functions/patch.js new file mode 100644 index 000000000..63afca252 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/patch.js @@ -0,0 +1,3 @@ +const SemVer = require('../classes/semver') +const patch = (a, loose) => new SemVer(a, loose).patch +module.exports = patch diff --git a/node_modules/superagent/node_modules/semver/functions/prerelease.js b/node_modules/superagent/node_modules/semver/functions/prerelease.js new file mode 100644 index 000000000..06aa13248 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/prerelease.js @@ -0,0 +1,6 @@ +const parse = require('./parse') +const prerelease = (version, options) => { + const parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} +module.exports = prerelease diff --git a/node_modules/superagent/node_modules/semver/functions/rcompare.js b/node_modules/superagent/node_modules/semver/functions/rcompare.js new file mode 100644 index 000000000..0ac509e79 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/rcompare.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const rcompare = (a, b, loose) => compare(b, a, loose) +module.exports = rcompare diff --git a/node_modules/superagent/node_modules/semver/functions/rsort.js b/node_modules/superagent/node_modules/semver/functions/rsort.js new file mode 100644 index 000000000..82404c5cf --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/rsort.js @@ -0,0 +1,3 @@ +const compareBuild = require('./compare-build') +const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) +module.exports = rsort diff --git a/node_modules/superagent/node_modules/semver/functions/satisfies.js b/node_modules/superagent/node_modules/semver/functions/satisfies.js new file mode 100644 index 000000000..50af1c199 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/satisfies.js @@ -0,0 +1,10 @@ +const Range = require('../classes/range') +const satisfies = (version, range, options) => { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} +module.exports = satisfies diff --git a/node_modules/superagent/node_modules/semver/functions/sort.js b/node_modules/superagent/node_modules/semver/functions/sort.js new file mode 100644 index 000000000..4d10917ab --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/sort.js @@ -0,0 +1,3 @@ +const compareBuild = require('./compare-build') +const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) +module.exports = sort diff --git a/node_modules/superagent/node_modules/semver/functions/valid.js b/node_modules/superagent/node_modules/semver/functions/valid.js new file mode 100644 index 000000000..f27bae107 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/functions/valid.js @@ -0,0 +1,6 @@ +const parse = require('./parse') +const valid = (version, options) => { + const v = parse(version, options) + return v ? v.version : null +} +module.exports = valid diff --git a/node_modules/superagent/node_modules/semver/index.js b/node_modules/superagent/node_modules/semver/index.js new file mode 100644 index 000000000..86d42ac16 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/index.js @@ -0,0 +1,89 @@ +// just pre-load all the stuff that index.js lazily exports +const internalRe = require('./internal/re') +const constants = require('./internal/constants') +const SemVer = require('./classes/semver') +const identifiers = require('./internal/identifiers') +const parse = require('./functions/parse') +const valid = require('./functions/valid') +const clean = require('./functions/clean') +const inc = require('./functions/inc') +const diff = require('./functions/diff') +const major = require('./functions/major') +const minor = require('./functions/minor') +const patch = require('./functions/patch') +const prerelease = require('./functions/prerelease') +const compare = require('./functions/compare') +const rcompare = require('./functions/rcompare') +const compareLoose = require('./functions/compare-loose') +const compareBuild = require('./functions/compare-build') +const sort = require('./functions/sort') +const rsort = require('./functions/rsort') +const gt = require('./functions/gt') +const lt = require('./functions/lt') +const eq = require('./functions/eq') +const neq = require('./functions/neq') +const gte = require('./functions/gte') +const lte = require('./functions/lte') +const cmp = require('./functions/cmp') +const coerce = require('./functions/coerce') +const Comparator = require('./classes/comparator') +const Range = require('./classes/range') +const satisfies = require('./functions/satisfies') +const toComparators = require('./ranges/to-comparators') +const maxSatisfying = require('./ranges/max-satisfying') +const minSatisfying = require('./ranges/min-satisfying') +const minVersion = require('./ranges/min-version') +const validRange = require('./ranges/valid') +const outside = require('./ranges/outside') +const gtr = require('./ranges/gtr') +const ltr = require('./ranges/ltr') +const intersects = require('./ranges/intersects') +const simplifyRange = require('./ranges/simplify') +const subset = require('./ranges/subset') +module.exports = { + parse, + valid, + clean, + inc, + diff, + major, + minor, + patch, + prerelease, + compare, + rcompare, + compareLoose, + compareBuild, + sort, + rsort, + gt, + lt, + eq, + neq, + gte, + lte, + cmp, + coerce, + Comparator, + Range, + satisfies, + toComparators, + maxSatisfying, + minSatisfying, + minVersion, + validRange, + outside, + gtr, + ltr, + intersects, + simplifyRange, + subset, + SemVer, + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + RELEASE_TYPES: constants.RELEASE_TYPES, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, +} diff --git a/node_modules/superagent/node_modules/semver/internal/constants.js b/node_modules/superagent/node_modules/semver/internal/constants.js new file mode 100644 index 000000000..94be1c570 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/internal/constants.js @@ -0,0 +1,35 @@ +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +const SEMVER_SPEC_VERSION = '2.0.0' + +const MAX_LENGTH = 256 +const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || +/* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +const MAX_SAFE_COMPONENT_LENGTH = 16 + +// Max safe length for a build identifier. The max length minus 6 characters for +// the shortest version with a build 0.0.0+BUILD. +const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 + +const RELEASE_TYPES = [ + 'major', + 'premajor', + 'minor', + 'preminor', + 'patch', + 'prepatch', + 'prerelease', +] + +module.exports = { + MAX_LENGTH, + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_SAFE_INTEGER, + RELEASE_TYPES, + SEMVER_SPEC_VERSION, + FLAG_INCLUDE_PRERELEASE: 0b001, + FLAG_LOOSE: 0b010, +} diff --git a/node_modules/superagent/node_modules/semver/internal/debug.js b/node_modules/superagent/node_modules/semver/internal/debug.js new file mode 100644 index 000000000..1c00e1369 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/internal/debug.js @@ -0,0 +1,9 @@ +const debug = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) +) ? (...args) => console.error('SEMVER', ...args) + : () => {} + +module.exports = debug diff --git a/node_modules/superagent/node_modules/semver/internal/identifiers.js b/node_modules/superagent/node_modules/semver/internal/identifiers.js new file mode 100644 index 000000000..e612d0a3d --- /dev/null +++ b/node_modules/superagent/node_modules/semver/internal/identifiers.js @@ -0,0 +1,23 @@ +const numeric = /^[0-9]+$/ +const compareIdentifiers = (a, b) => { + const anum = numeric.test(a) + const bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) + +module.exports = { + compareIdentifiers, + rcompareIdentifiers, +} diff --git a/node_modules/superagent/node_modules/semver/internal/parse-options.js b/node_modules/superagent/node_modules/semver/internal/parse-options.js new file mode 100644 index 000000000..10d64ce06 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/internal/parse-options.js @@ -0,0 +1,15 @@ +// parse out just the options we care about +const looseOption = Object.freeze({ loose: true }) +const emptyOpts = Object.freeze({ }) +const parseOptions = options => { + if (!options) { + return emptyOpts + } + + if (typeof options !== 'object') { + return looseOption + } + + return options +} +module.exports = parseOptions diff --git a/node_modules/superagent/node_modules/semver/internal/re.js b/node_modules/superagent/node_modules/semver/internal/re.js new file mode 100644 index 000000000..fd8920e7b --- /dev/null +++ b/node_modules/superagent/node_modules/semver/internal/re.js @@ -0,0 +1,217 @@ +const { + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_LENGTH, +} = require('./constants') +const debug = require('./debug') +exports = module.exports = {} + +// The actual regexps go on exports.re +const re = exports.re = [] +const safeRe = exports.safeRe = [] +const src = exports.src = [] +const t = exports.t = {} +let R = 0 + +const LETTERDASHNUMBER = '[a-zA-Z0-9-]' + +// Replace some greedy regex tokens to prevent regex dos issues. These regex are +// used internally via the safeRe object since all inputs in this library get +// normalized first to trim and collapse all extra whitespace. The original +// regexes are exported for userland consumption and lower level usage. A +// future breaking change could export the safer regex only with a note that +// all input should have extra whitespace removed. +const safeRegexReplacements = [ + ['\\s', 1], + ['\\d', MAX_LENGTH], + [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], +] + +const makeSafeRegex = (value) => { + for (const [token, max] of safeRegexReplacements) { + value = value + .split(`${token}*`).join(`${token}{0,${max}}`) + .split(`${token}+`).join(`${token}{1,${max}}`) + } + return value +} + +const createToken = (name, value, isGlobal) => { + const safe = makeSafeRegex(value) + const index = R++ + debug(name, index, value) + t[name] = index + src[index] = value + re[index] = new RegExp(value, isGlobal ? 'g' : undefined) + safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) +} + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') +createToken('NUMERICIDENTIFIERLOOSE', '\\d+') + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) + +// ## Main Version +// Three dot-separated numeric identifiers. + +createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`) + +createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`) + +createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`) + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) + +createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`) + +createToken('FULL', `^${src[t.FULLPLAIN]}$`) + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`) + +createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) + +createToken('GTLT', '((?:<|>)?=?)') + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) +createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) + +createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) +createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +createToken('COERCEPLAIN', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) +createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) +createToken('COERCEFULL', src[t.COERCEPLAIN] + + `(?:${src[t.PRERELEASE]})?` + + `(?:${src[t.BUILD]})?` + + `(?:$|[^\\d])`) +createToken('COERCERTL', src[t.COERCE], true) +createToken('COERCERTLFULL', src[t.COERCEFULL], true) + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +createToken('LONETILDE', '(?:~>?)') + +createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) +exports.tildeTrimReplace = '$1~' + +createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) +createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +createToken('LONECARET', '(?:\\^)') + +createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) +exports.caretTrimReplace = '$1^' + +createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) +createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) +createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) +exports.comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`) + +createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`) + +// Star ranges basically just allow anything at all. +createToken('STAR', '(<|>)?=?\\s*\\*') +// >=0.0.0 is like a star +createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') +createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') diff --git a/node_modules/superagent/node_modules/semver/package.json b/node_modules/superagent/node_modules/semver/package.json new file mode 100644 index 000000000..f00c6bdda --- /dev/null +++ b/node_modules/superagent/node_modules/semver/package.json @@ -0,0 +1,78 @@ +{ + "name": "semver", + "version": "7.6.0", + "description": "The semantic version parser used by npm.", + "main": "index.js", + "scripts": { + "test": "tap", + "snap": "tap", + "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "postlint": "template-oss-check", + "lintfix": "npm run lint -- --fix", + "posttest": "npm run lint", + "template-oss-apply": "template-oss-apply --force" + }, + "devDependencies": { + "@npmcli/eslint-config": "^4.0.0", + "@npmcli/template-oss": "4.21.3", + "tap": "^16.0.0" + }, + "license": "ISC", + "repository": { + "type": "git", + "url": "https://github.com/npm/node-semver.git" + }, + "bin": { + "semver": "bin/semver.js" + }, + "files": [ + "bin/", + "lib/", + "classes/", + "functions/", + "internal/", + "ranges/", + "index.js", + "preload.js", + "range.bnf" + ], + "tap": { + "timeout": 30, + "coverage-map": "map.js", + "nyc-arg": [ + "--exclude", + "tap-snapshots/**" + ] + }, + "engines": { + "node": ">=10" + }, + "dependencies": { + "lru-cache": "^6.0.0" + }, + "author": "GitHub Inc.", + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "version": "4.21.3", + "engines": ">=10", + "distPaths": [ + "classes/", + "functions/", + "internal/", + "ranges/", + "index.js", + "preload.js", + "range.bnf" + ], + "allowPaths": [ + "/classes/", + "/functions/", + "/internal/", + "/ranges/", + "/index.js", + "/preload.js", + "/range.bnf" + ], + "publish": "true" + } +} diff --git a/node_modules/superagent/node_modules/semver/preload.js b/node_modules/superagent/node_modules/semver/preload.js new file mode 100644 index 000000000..947cd4f79 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/preload.js @@ -0,0 +1,2 @@ +// XXX remove in v8 or beyond +module.exports = require('./index.js') diff --git a/node_modules/superagent/node_modules/semver/range.bnf b/node_modules/superagent/node_modules/semver/range.bnf new file mode 100644 index 000000000..d4c6ae0d7 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | [1-9] ( [0-9] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/node_modules/superagent/node_modules/semver/ranges/gtr.js b/node_modules/superagent/node_modules/semver/ranges/gtr.js new file mode 100644 index 000000000..db7e35599 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/ranges/gtr.js @@ -0,0 +1,4 @@ +// Determine if version is greater than all the versions possible in the range. +const outside = require('./outside') +const gtr = (version, range, options) => outside(version, range, '>', options) +module.exports = gtr diff --git a/node_modules/superagent/node_modules/semver/ranges/intersects.js b/node_modules/superagent/node_modules/semver/ranges/intersects.js new file mode 100644 index 000000000..e0e9b7ce0 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/ranges/intersects.js @@ -0,0 +1,7 @@ +const Range = require('../classes/range') +const intersects = (r1, r2, options) => { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2, options) +} +module.exports = intersects diff --git a/node_modules/superagent/node_modules/semver/ranges/ltr.js b/node_modules/superagent/node_modules/semver/ranges/ltr.js new file mode 100644 index 000000000..528a885eb --- /dev/null +++ b/node_modules/superagent/node_modules/semver/ranges/ltr.js @@ -0,0 +1,4 @@ +const outside = require('./outside') +// Determine if version is less than all the versions possible in the range +const ltr = (version, range, options) => outside(version, range, '<', options) +module.exports = ltr diff --git a/node_modules/superagent/node_modules/semver/ranges/max-satisfying.js b/node_modules/superagent/node_modules/semver/ranges/max-satisfying.js new file mode 100644 index 000000000..6e3d993c6 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/ranges/max-satisfying.js @@ -0,0 +1,25 @@ +const SemVer = require('../classes/semver') +const Range = require('../classes/range') + +const maxSatisfying = (versions, range, options) => { + let max = null + let maxSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} +module.exports = maxSatisfying diff --git a/node_modules/superagent/node_modules/semver/ranges/min-satisfying.js b/node_modules/superagent/node_modules/semver/ranges/min-satisfying.js new file mode 100644 index 000000000..9b60974e2 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/ranges/min-satisfying.js @@ -0,0 +1,24 @@ +const SemVer = require('../classes/semver') +const Range = require('../classes/range') +const minSatisfying = (versions, range, options) => { + let min = null + let minSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} +module.exports = minSatisfying diff --git a/node_modules/superagent/node_modules/semver/ranges/min-version.js b/node_modules/superagent/node_modules/semver/ranges/min-version.js new file mode 100644 index 000000000..350e1f783 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/ranges/min-version.js @@ -0,0 +1,61 @@ +const SemVer = require('../classes/semver') +const Range = require('../classes/range') +const gt = require('../functions/gt') + +const minVersion = (range, loose) => { + range = new Range(range, loose) + + let minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let setMin = null + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt(compver, setMin)) { + setMin = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } + }) + if (setMin && (!minver || gt(minver, setMin))) { + minver = setMin + } + } + + if (minver && range.test(minver)) { + return minver + } + + return null +} +module.exports = minVersion diff --git a/node_modules/superagent/node_modules/semver/ranges/outside.js b/node_modules/superagent/node_modules/semver/ranges/outside.js new file mode 100644 index 000000000..ae99b10a5 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/ranges/outside.js @@ -0,0 +1,80 @@ +const SemVer = require('../classes/semver') +const Comparator = require('../classes/comparator') +const { ANY } = Comparator +const Range = require('../classes/range') +const satisfies = require('../functions/satisfies') +const gt = require('../functions/gt') +const lt = require('../functions/lt') +const lte = require('../functions/lte') +const gte = require('../functions/gte') + +const outside = (version, range, hilo, options) => { + version = new SemVer(version, options) + range = new Range(range, options) + + let gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisfies the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let high = null + let low = null + + comparators.forEach((comparator) => { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} + +module.exports = outside diff --git a/node_modules/superagent/node_modules/semver/ranges/simplify.js b/node_modules/superagent/node_modules/semver/ranges/simplify.js new file mode 100644 index 000000000..618d5b627 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/ranges/simplify.js @@ -0,0 +1,47 @@ +// given a set of versions and a range, create a "simplified" range +// that includes the same versions that the original range does +// If the original range is shorter than the simplified one, return that. +const satisfies = require('../functions/satisfies.js') +const compare = require('../functions/compare.js') +module.exports = (versions, range, options) => { + const set = [] + let first = null + let prev = null + const v = versions.sort((a, b) => compare(a, b, options)) + for (const version of v) { + const included = satisfies(version, range, options) + if (included) { + prev = version + if (!first) { + first = version + } + } else { + if (prev) { + set.push([first, prev]) + } + prev = null + first = null + } + } + if (first) { + set.push([first, null]) + } + + const ranges = [] + for (const [min, max] of set) { + if (min === max) { + ranges.push(min) + } else if (!max && min === v[0]) { + ranges.push('*') + } else if (!max) { + ranges.push(`>=${min}`) + } else if (min === v[0]) { + ranges.push(`<=${max}`) + } else { + ranges.push(`${min} - ${max}`) + } + } + const simplified = ranges.join(' || ') + const original = typeof range.raw === 'string' ? range.raw : String(range) + return simplified.length < original.length ? simplified : range +} diff --git a/node_modules/superagent/node_modules/semver/ranges/subset.js b/node_modules/superagent/node_modules/semver/ranges/subset.js new file mode 100644 index 000000000..1e5c26837 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/ranges/subset.js @@ -0,0 +1,247 @@ +const Range = require('../classes/range.js') +const Comparator = require('../classes/comparator.js') +const { ANY } = Comparator +const satisfies = require('../functions/satisfies.js') +const compare = require('../functions/compare.js') + +// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: +// - Every simple range `r1, r2, ...` is a null set, OR +// - Every simple range `r1, r2, ...` which is not a null set is a subset of +// some `R1, R2, ...` +// +// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: +// - If c is only the ANY comparator +// - If C is only the ANY comparator, return true +// - Else if in prerelease mode, return false +// - else replace c with `[>=0.0.0]` +// - If C is only the ANY comparator +// - if in prerelease mode, return true +// - else replace C with `[>=0.0.0]` +// - Let EQ be the set of = comparators in c +// - If EQ is more than one, return true (null set) +// - Let GT be the highest > or >= comparator in c +// - Let LT be the lowest < or <= comparator in c +// - If GT and LT, and GT.semver > LT.semver, return true (null set) +// - If any C is a = range, and GT or LT are set, return false +// - If EQ +// - If GT, and EQ does not satisfy GT, return true (null set) +// - If LT, and EQ does not satisfy LT, return true (null set) +// - If EQ satisfies every C, return true +// - Else return false +// - If GT +// - If GT.semver is lower than any > or >= comp in C, return false +// - If GT is >=, and GT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the GT.semver tuple, return false +// - If LT +// - If LT.semver is greater than any < or <= comp in C, return false +// - If LT is <=, and LT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the LT.semver tuple, return false +// - Else return true + +const subset = (sub, dom, options = {}) => { + if (sub === dom) { + return true + } + + sub = new Range(sub, options) + dom = new Range(dom, options) + let sawNonNull = false + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options) + sawNonNull = sawNonNull || isSub !== null + if (isSub) { + continue OUTER + } + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) { + return false + } + } + return true +} + +const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] +const minimumVersion = [new Comparator('>=0.0.0')] + +const simpleSubset = (sub, dom, options) => { + if (sub === dom) { + return true + } + + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) { + return true + } else if (options.includePrerelease) { + sub = minimumVersionWithPreRelease + } else { + sub = minimumVersion + } + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) { + return true + } else { + dom = minimumVersion + } + } + + const eqSet = new Set() + let gt, lt + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') { + gt = higherGT(gt, c, options) + } else if (c.operator === '<' || c.operator === '<=') { + lt = lowerLT(lt, c, options) + } else { + eqSet.add(c.semver) + } + } + + if (eqSet.size > 1) { + return null + } + + let gtltComp + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options) + if (gtltComp > 0) { + return null + } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { + return null + } + } + + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) { + return null + } + + if (lt && !satisfies(eq, String(lt), options)) { + return null + } + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) { + return false + } + } + + return true + } + + let higher, lower + let hasDomLT, hasDomGT + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options) + if (higher === c && higher !== gt) { + return false + } + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { + return false + } + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options) + if (lower === c && lower !== lt) { + return false + } + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { + return false + } + } + if (!c.operator && (lt || gt) && gtltComp !== 0) { + return false + } + } + + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) { + return false + } + + if (lt && hasDomGT && !gt && gtltComp !== 0) { + return false + } + + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) { + return false + } + + return true +} + +// >=1.2.3 is lower than >1.2.3 +const higherGT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a +} + +// <=1.2.3 is higher than <1.2.3 +const lowerLT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a +} + +module.exports = subset diff --git a/node_modules/superagent/node_modules/semver/ranges/to-comparators.js b/node_modules/superagent/node_modules/semver/ranges/to-comparators.js new file mode 100644 index 000000000..6c8bc7e6f --- /dev/null +++ b/node_modules/superagent/node_modules/semver/ranges/to-comparators.js @@ -0,0 +1,8 @@ +const Range = require('../classes/range') + +// Mostly just for testing and legacy API reasons +const toComparators = (range, options) => + new Range(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) + +module.exports = toComparators diff --git a/node_modules/superagent/node_modules/semver/ranges/valid.js b/node_modules/superagent/node_modules/semver/ranges/valid.js new file mode 100644 index 000000000..365f35689 --- /dev/null +++ b/node_modules/superagent/node_modules/semver/ranges/valid.js @@ -0,0 +1,11 @@ +const Range = require('../classes/range') +const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} +module.exports = validRange diff --git a/node_modules/superagent/package.json b/node_modules/superagent/package.json new file mode 100644 index 000000000..f03b0173b --- /dev/null +++ b/node_modules/superagent/package.json @@ -0,0 +1,222 @@ +{ + "name": "superagent", + "description": "elegant & feature rich browser / node HTTP with a fluent API", + "version": "5.3.1", + "author": "TJ Holowaychuk ", + "browser": { + "./src/node/index.js": "./src/client.js", + "./lib/node/index.js": "./lib/client.js", + "./test/support/server.js": "./test/support/blank.js" + }, + "bugs": { + "url": "https://github.com/visionmedia/superagent/issues" + }, + "commitlint": { + "extends": [ + "@commitlint/config-conventional" + ] + }, + "contributors": [ + "Kornel Lesiński ", + "Peter Lyons ", + "Hunter Loftis ", + "Nick Baugh " + ], + "dependencies": { + "component-emitter": "^1.3.0", + "cookiejar": "^2.1.2", + "debug": "^4.1.1", + "fast-safe-stringify": "^2.0.7", + "form-data": "^3.0.0", + "formidable": "^1.2.2", + "methods": "^1.1.2", + "mime": "^2.4.6", + "qs": "^6.9.4", + "readable-stream": "^3.6.0", + "semver": "^7.3.2" + }, + "devDependencies": { + "@babel/cli": "^7.10.3", + "@babel/core": "^7.10.3", + "@babel/preset-env": "^7.10.3", + "@commitlint/cli": "^9.0.1", + "@commitlint/config-conventional": "^9.0.1", + "Base64": "^1.1.0", + "babelify": "^10.0.0", + "basic-auth-connect": "^1.0.0", + "body-parser": "^1.19.0", + "browserify": "^16.5.1", + "codecov": "^3.7.0", + "cookie-parser": "^1.4.5", + "cross-env": "^7.0.2", + "eslint": "^6.7.2", + "eslint-config-xo-lass": "^1.0.3", + "eslint-plugin-compat": "^3.8.0", + "eslint-plugin-node": "^11.1.0", + "express": "^4.17.1", + "express-session": "^1.17.1", + "fixpack": "^3.0.6", + "husky": "^4.2.5", + "lint-staged": "^10.2.11", + "marked": "^1.1.0", + "mocha": "3.5.3", + "multer": "^1.4.2", + "nyc": "^15.1.0", + "remark-cli": "^8.0.0", + "remark-preset-github": "^2.0.0", + "rimraf": "^3.0.2", + "should": "^13.2.3", + "should-http": "^0.1.1", + "tinyify": "^2.5.2", + "uglify-js": "^3.10.0", + "xo": "0.25.3", + "zuul": "^3.12.0" + }, + "engines": { + "node": ">= 7.0.0" + }, + "homepage": "https://github.com/visionmedia/superagent", + "husky": { + "hooks": { + "pre-commit": "npm test", + "commit-msg": "commitlint -E HUSKY_GIT_PARAMS" + } + }, + "jsdelivr": "dist/superagent.min.js", + "keywords": [ + "agent", + "ajax", + "ajax", + "api", + "async", + "await", + "axios", + "cancel", + "client", + "frisbee", + "got", + "http", + "http", + "https", + "ky", + "promise", + "promise", + "promises", + "request", + "request", + "requests", + "response", + "rest", + "retry", + "super", + "superagent", + "timeout", + "transform", + "xhr", + "xmlhttprequest" + ], + "license": "MIT", + "lint-staged": { + "linters": { + "*.js": [ + "xo --fix", + "git add" + ], + "*.md": [ + "remark . -qfo", + "git add" + ], + "package.json": [ + "fixpack", + "git add" + ] + } + }, + "main": "lib/node/index.js", + "prettier": { + "singleQuote": true, + "bracketSpacing": true, + "trailingComma": "none" + }, + "remarkConfig": { + "plugins": [ + "preset-github" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/superagent.git" + }, + "scripts": { + "browserify": "browserify src/node/index.js -o dist/superagent.js -s superagent -g [ babelify --configFile ./.dist.babelrc ]", + "build": "npm run build:clean && npm run build:lib && npm run build:dist", + "build:clean": "rimraf lib dist", + "build:dist": "npm run browserify && npm run minify", + "build:lib": "babel --config-file ./.lib.babelrc src --out-dir lib", + "coverage": "nyc report --reporter=text-lcov > coverage.lcov && codecov", + "lint": "xo && remark . -qfo && eslint -c .lib.eslintrc lib && eslint -c .dist.eslintrc dist", + "minify": "cross-env NODE_ENV=production browserify src/node/index.js -o dist/superagent.min.js -s superagent -g [ babelify --configFile ./.dist.babelrc ] -p tinyify", + "nyc": "cross-env NODE_ENV=test nyc ava", + "test": "npm run build && npm run lint && make test", + "test-http2": "npm run build && npm run lint && make test-node-http2" + }, + "unpkg": "dist/superagent.min.js", + "xo": { + "prettier": true, + "space": true, + "extends": [ + "xo-lass" + ], + "env": [ + "node", + "browser" + ], + "overrides": [ + { + "files": "test/**/*.js", + "env": [ + "mocha" + ], + "rules": { + "block-scoped-var": "off", + "complexity": "off", + "default-case": "off", + "eqeqeq": "off", + "func-name-matching": "off", + "func-names": "off", + "guard-for-in": "off", + "handle-callback-err": "off", + "import/no-extraneous-dependencies": "off", + "import/no-unassigned-import": "off", + "import/order": "off", + "max-nested-callbacks": "off", + "new-cap": "off", + "no-eq-null": "off", + "no-extend-native": "off", + "no-implicit-coercion": "off", + "no-multi-assign": "off", + "no-negated-condition": "off", + "no-prototype-builtins": "off", + "no-redeclare": "off", + "no-undef": "off", + "no-unused-expressions": "off", + "no-unused-vars": "off", + "no-use-extend-native/no-use-extend-native": "off", + "no-useless-escape": "off", + "no-var": "off", + "no-void": "off", + "node/no-deprecated-api": "off", + "prefer-rest-params": "off", + "prefer-spread": "off", + "promise/prefer-await-to-then": "off", + "promise/valid-params": "off", + "unicorn/filename-case": "off", + "valid-jsdoc": "off" + } + } + ], + "globals": [ + "ActiveXObject" + ] + } +} diff --git a/node_modules/util-deprecate/History.md b/node_modules/util-deprecate/History.md new file mode 100644 index 000000000..acc867537 --- /dev/null +++ b/node_modules/util-deprecate/History.md @@ -0,0 +1,16 @@ + +1.0.2 / 2015-10-07 +================== + + * use try/catch when checking `localStorage` (#3, @kumavis) + +1.0.1 / 2014-11-25 +================== + + * browser: use `console.warn()` for deprecation calls + * browser: more jsdocs + +1.0.0 / 2014-04-30 +================== + + * initial commit diff --git a/node_modules/util-deprecate/LICENSE b/node_modules/util-deprecate/LICENSE new file mode 100644 index 000000000..6a60e8c22 --- /dev/null +++ b/node_modules/util-deprecate/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/util-deprecate/README.md b/node_modules/util-deprecate/README.md new file mode 100644 index 000000000..75622fa7c --- /dev/null +++ b/node_modules/util-deprecate/README.md @@ -0,0 +1,53 @@ +util-deprecate +============== +### The Node.js `util.deprecate()` function with browser support + +In Node.js, this module simply re-exports the `util.deprecate()` function. + +In the web browser (i.e. via browserify), a browser-specific implementation +of the `util.deprecate()` function is used. + + +## API + +A `deprecate()` function is the only thing exposed by this module. + +``` javascript +// setup: +exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead'); + + +// users see: +foo(); +// foo() is deprecated, use bar() instead +foo(); +foo(); +``` + + +## License + +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/util-deprecate/browser.js b/node_modules/util-deprecate/browser.js new file mode 100644 index 000000000..549ae2f06 --- /dev/null +++ b/node_modules/util-deprecate/browser.js @@ -0,0 +1,67 @@ + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} diff --git a/node_modules/util-deprecate/node.js b/node_modules/util-deprecate/node.js new file mode 100644 index 000000000..5e6fcff5d --- /dev/null +++ b/node_modules/util-deprecate/node.js @@ -0,0 +1,6 @@ + +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + +module.exports = require('util').deprecate; diff --git a/node_modules/util-deprecate/package.json b/node_modules/util-deprecate/package.json new file mode 100644 index 000000000..2e79f89a9 --- /dev/null +++ b/node_modules/util-deprecate/package.json @@ -0,0 +1,27 @@ +{ + "name": "util-deprecate", + "version": "1.0.2", + "description": "The Node.js `util.deprecate()` function with browser support", + "main": "node.js", + "browser": "browser.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/util-deprecate.git" + }, + "keywords": [ + "util", + "deprecate", + "browserify", + "browser", + "node" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/TooTallNate/util-deprecate/issues" + }, + "homepage": "https://github.com/TooTallNate/util-deprecate" +} diff --git a/package-lock.json b/package-lock.json index fb2d2d526..c000dc864 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,7 +12,7 @@ "@actions/core": "^1.2.6", "@actions/github": "^4.0.0", "@mobsuccess-devops/asana-magics": "^1.0.1-ci-4263876762.0", - "asana": "^0.18.5" + "asana": "^3.0.3" }, "devDependencies": { "eslint": "^7.22.0", @@ -44,11 +44,71 @@ "tunnel": "0.0.6" } }, + "node_modules/@babel/cli": { + "version": "7.24.1", + "resolved": "https://registry.npmjs.org/@babel/cli/-/cli-7.24.1.tgz", + "integrity": "sha512-HbmrtxyFUr34LwAlV9jS+sSIjUp4FpdtIMGwgufY3AsxrIfsh/HxlMTywsONAZsU0RMYbZtbZFpUCrSGs7o0EA==", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.25", + "commander": "^4.0.1", + "convert-source-map": "^2.0.0", + "fs-readdir-recursive": "^1.1.0", + "glob": "^7.2.0", + "make-dir": "^2.1.0", + "slash": "^2.0.0" + }, + "bin": { + "babel": "bin/babel.js", + "babel-external-helpers": "bin/babel-external-helpers.js" + }, + "engines": { + "node": ">=6.9.0" + }, + "optionalDependencies": { + "@nicolo-ribaudo/chokidar-2": "2.1.8-no-fsevents.3", + "chokidar": "^3.4.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/cli/node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==" + }, + "node_modules/@babel/cli/node_modules/make-dir": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-2.1.0.tgz", + "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==", + "dependencies": { + "pify": "^4.0.1", + "semver": "^5.6.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@babel/cli/node_modules/semver": { + "version": "5.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz", + "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==", + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/@babel/cli/node_modules/slash": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", + "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==", + "engines": { + "node": ">=6" + } + }, "node_modules/@babel/code-frame": { "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.13.tgz", "integrity": "sha512-HV1Cm0Q3ZrpCR93tkWOYiuYIgLxZXZFVG2VgK+MBWjUqZTundupbfx2aXarXuw5Ko5aMcjtJgbSs4vUGBS5v6g==", - "dev": true, "dependencies": { "@babel/highlight": "^7.12.13" } @@ -56,14 +116,12 @@ "node_modules/@babel/compat-data": { "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.13.12.tgz", - "integrity": "sha512-3eJJ841uKxeV8dcN/2yGEUy+RfgQspPEgQat85umsE1rotuquQ2AbIub4S6j7c50a2d+4myc+zSlnXeIHrOnhQ==", - "dev": true + "integrity": "sha512-3eJJ841uKxeV8dcN/2yGEUy+RfgQspPEgQat85umsE1rotuquQ2AbIub4S6j7c50a2d+4myc+zSlnXeIHrOnhQ==" }, "node_modules/@babel/core": { "version": "7.13.10", "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.13.10.tgz", "integrity": "sha512-bfIYcT0BdKeAZrovpMqX2Mx5NrgAckGbwT982AkdS5GNfn3KMGiprlBAtmBcFZRUmpaufS6WZFP8trvx8ptFDw==", - "dev": true, "dependencies": { "@babel/code-frame": "^7.12.13", "@babel/generator": "^7.13.9", @@ -94,7 +152,6 @@ "version": "0.5.7", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", - "dev": true, "engines": { "node": ">=0.10.0" } @@ -103,7 +160,6 @@ "version": "7.13.9", "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.13.9.tgz", "integrity": "sha512-mHOOmY0Axl/JCTkxTU6Lf5sWOg/v8nUa+Xkt4zMTftX0wqmb6Sh7J8gvcehBw7q0AhrhAR+FDacKjCZ2X8K+Sw==", - "dev": true, "dependencies": { "@babel/types": "^7.13.0", "jsesc": "^2.5.1", @@ -114,7 +170,6 @@ "version": "0.5.7", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", - "dev": true, "engines": { "node": ">=0.10.0" } @@ -123,7 +178,6 @@ "version": "7.13.10", "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.13.10.tgz", "integrity": "sha512-/Xju7Qg1GQO4mHZ/Kcs6Au7gfafgZnwm+a7sy/ow/tV1sHeraRUHbjdat8/UvDor4Tez+siGKDk6zIKtCPKVJA==", - "dev": true, "dependencies": { "@babel/compat-data": "^7.13.8", "@babel/helper-validator-option": "^7.12.17", @@ -138,7 +192,6 @@ "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.12.13.tgz", "integrity": "sha512-TZvmPn0UOqmvi5G4vvw0qZTpVptGkB1GL61R6lKvrSdIxGm5Pky7Q3fpKiIkQCAtRCBUwB0PaThlx9vebCDSwA==", - "dev": true, "dependencies": { "@babel/helper-get-function-arity": "^7.12.13", "@babel/template": "^7.12.13", @@ -149,7 +202,6 @@ "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.12.13.tgz", "integrity": "sha512-DjEVzQNz5LICkzN0REdpD5prGoidvbdYk1BVgRUOINaWJP2t6avB27X1guXK1kXNrX0WMfsrm1A/ZBthYuIMQg==", - "dev": true, "dependencies": { "@babel/types": "^7.12.13" } @@ -158,7 +210,6 @@ "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.13.12.tgz", "integrity": "sha512-48ql1CLL59aKbU94Y88Xgb2VFy7a95ykGRbJJaaVv+LX5U8wFpLfiGXJJGUozsmA1oEh/o5Bp60Voq7ACyA/Sw==", - "dev": true, "dependencies": { "@babel/types": "^7.13.12" } @@ -167,7 +218,6 @@ "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.13.12.tgz", "integrity": "sha512-4cVvR2/1B693IuOvSI20xqqa/+bl7lqAMR59R4iu39R9aOX8/JoYY1sFaNvUMyMBGnHdwvJgUrzNLoUZxXypxA==", - "dev": true, "dependencies": { "@babel/types": "^7.13.12" } @@ -176,7 +226,6 @@ "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.13.12.tgz", "integrity": "sha512-7zVQqMO3V+K4JOOj40kxiCrMf6xlQAkewBB0eu2b03OO/Q21ZutOzjpfD79A5gtE/2OWi1nv625MrDlGlkbknQ==", - "dev": true, "dependencies": { "@babel/helper-module-imports": "^7.13.12", "@babel/helper-replace-supers": "^7.13.12", @@ -192,7 +241,6 @@ "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.12.13.tgz", "integrity": "sha512-BdWQhoVJkp6nVjB7nkFWcn43dkprYauqtk++Py2eaf/GRDFm5BxRqEIZCiHlZUGAVmtwKcsVL1dC68WmzeFmiA==", - "dev": true, "dependencies": { "@babel/types": "^7.12.13" } @@ -207,7 +255,6 @@ "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.13.12.tgz", "integrity": "sha512-Gz1eiX+4yDO8mT+heB94aLVNCL+rbuT2xy4YfyNqu8F+OI6vMvJK891qGBTqL9Uc8wxEvRW92Id6G7sDen3fFw==", - "dev": true, "dependencies": { "@babel/helper-member-expression-to-functions": "^7.13.12", "@babel/helper-optimise-call-expression": "^7.12.13", @@ -219,7 +266,6 @@ "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.13.12.tgz", "integrity": "sha512-7FEjbrx5SL9cWvXioDbnlYTppcZGuCY6ow3/D5vMggb2Ywgu4dMrpTJX0JdQAIcRRUElOIxF3yEooa9gUb9ZbA==", - "dev": true, "dependencies": { "@babel/types": "^7.13.12" } @@ -228,7 +274,6 @@ "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.12.13.tgz", "integrity": "sha512-tCJDltF83htUtXx5NLcaDqRmknv652ZWCHyoTETf1CXYJdPC7nohZohjUgieXhv0hTJdRf2FjDueFehdNucpzg==", - "dev": true, "dependencies": { "@babel/types": "^7.12.13" } @@ -236,20 +281,17 @@ "node_modules/@babel/helper-validator-identifier": { "version": "7.12.11", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.12.11.tgz", - "integrity": "sha512-np/lG3uARFybkoHokJUmf1QfEvRVCPbmQeUQpKow5cQ3xWrV9i3rUHodKDJPQfTVX61qKi+UdYk8kik84n7XOw==", - "dev": true + "integrity": "sha512-np/lG3uARFybkoHokJUmf1QfEvRVCPbmQeUQpKow5cQ3xWrV9i3rUHodKDJPQfTVX61qKi+UdYk8kik84n7XOw==" }, "node_modules/@babel/helper-validator-option": { "version": "7.12.17", "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.12.17.tgz", - "integrity": "sha512-TopkMDmLzq8ngChwRlyjR6raKD6gMSae4JdYDB8bByKreQgG0RBTuKe9LRxW3wFtUnjxOPRKBDwEH6Mg5KeDfw==", - "dev": true + "integrity": "sha512-TopkMDmLzq8ngChwRlyjR6raKD6gMSae4JdYDB8bByKreQgG0RBTuKe9LRxW3wFtUnjxOPRKBDwEH6Mg5KeDfw==" }, "node_modules/@babel/helpers": { "version": "7.13.10", "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.13.10.tgz", "integrity": "sha512-4VO883+MWPDUVRF3PhiLBUFHoX/bsLTGFpFK/HqvvfBZz2D57u9XzPVNFVBTc0PW/CWR9BXTOKt8NF4DInUHcQ==", - "dev": true, "dependencies": { "@babel/template": "^7.12.13", "@babel/traverse": "^7.13.0", @@ -260,7 +302,6 @@ "version": "7.13.10", "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.13.10.tgz", "integrity": "sha512-5aPpe5XQPzflQrFwL1/QoeHkP2MsA4JCntcXHRhEsdsfPVkvPi2w7Qix4iV7t5S/oC9OodGrggd8aco1g3SZFg==", - "dev": true, "dependencies": { "@babel/helper-validator-identifier": "^7.12.11", "chalk": "^2.0.0", @@ -271,7 +312,6 @@ "version": "3.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, "dependencies": { "color-convert": "^1.9.0" }, @@ -283,7 +323,6 @@ "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, "dependencies": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", @@ -297,7 +336,6 @@ "version": "1.9.3", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, "dependencies": { "color-name": "1.1.3" } @@ -305,14 +343,12 @@ "node_modules/@babel/highlight/node_modules/color-name": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", - "dev": true + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" }, "node_modules/@babel/highlight/node_modules/has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", - "dev": true, "engines": { "node": ">=4" } @@ -321,7 +357,6 @@ "version": "5.5.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, "dependencies": { "has-flag": "^3.0.0" }, @@ -333,7 +368,6 @@ "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.13.12.tgz", "integrity": "sha512-4T7Pb244rxH24yR116LAuJ+adxXXnHhZaLJjegJVKSdoNCe4x1eDBaud5YIcQFcqzsaD5BHvJw5BQ0AZapdCRw==", - "dev": true, "bin": { "parser": "bin/babel-parser.js" }, @@ -489,7 +523,6 @@ "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.12.13.tgz", "integrity": "sha512-/7xxiGA57xMo/P2GVvdEumr8ONhFOhfgq2ihK3h1e6THqzTAkHbkXgB0xI9yeTfIUoH3+oAeHhqm/I43OTbbjA==", - "dev": true, "dependencies": { "@babel/code-frame": "^7.12.13", "@babel/parser": "^7.12.13", @@ -500,7 +533,6 @@ "version": "7.13.0", "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.13.0.tgz", "integrity": "sha512-xys5xi5JEhzC3RzEmSGrs/b3pJW/o87SypZ+G/PhaE7uqVQNv/jlmVIBXuoh5atqQ434LfXV+sf23Oxj0bchJQ==", - "dev": true, "dependencies": { "@babel/code-frame": "^7.12.13", "@babel/generator": "^7.13.0", @@ -517,7 +549,6 @@ "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.13.12.tgz", "integrity": "sha512-K4nY2xFN4QMvQwkQ+zmBDp6ANMbVNw6BbxWmYA4qNjhR9W+Lj/8ky5MEY2Me5r+B2c6/v6F53oMndG+f9s3IiA==", - "dev": true, "dependencies": { "@babel/helper-validator-identifier": "^7.12.11", "lodash": "^4.17.19", @@ -833,12 +864,40 @@ "node": ">= 10.14.2" } }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.4.15", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", + "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, "node_modules/@mobsuccess-devops/asana-magics": { "version": "1.0.1-ci-4263876762.0", "resolved": "https://npm.pkg.github.com/download/@mobsuccess-devops/asana-magics/1.0.1-ci-4263876762.0/a74d8aebb535cae437157e15b019a385eedb3c0c", "integrity": "sha512-77lub4Hu7iZVuxFU+CD50tJ+0rKTxqcNNYrfx8etHmWUdMWdgSHGZx7BfIex/leDW4oxkzY/FQUmHMpp0vnZeg==", "license": "UNLICENSED" }, + "node_modules/@nicolo-ribaudo/chokidar-2": { + "version": "2.1.8-no-fsevents.3", + "resolved": "https://registry.npmjs.org/@nicolo-ribaudo/chokidar-2/-/chokidar-2-2.1.8-no-fsevents.3.tgz", + "integrity": "sha512-s88O1aVtXftvp5bCPB7WnmXc5IwOZZ7YPuwNPt+GtOOXpPvad1LfbmjYv+qII7zP6RU2QGnqve27dnLycEnyEQ==", + "optional": true + }, "node_modules/@octokit/auth-token": { "version": "2.4.5", "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.4.5.tgz", @@ -1135,6 +1194,7 @@ "version": "6.12.6", "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", @@ -1207,10 +1267,10 @@ } }, "node_modules/anymatch": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.1.tgz", - "integrity": "sha512-mM8522psRCqzV+6LhomX5wgp25YVibjh8Wj23I5RPkPppSVSjyKD2A2mBJmWGa+KN7f2D6LNh9jkBCeyLktzjg==", - "dev": true, + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "devOptional": true, "dependencies": { "normalize-path": "^3.0.0", "picomatch": "^2.0.4" @@ -1265,21 +1325,19 @@ } }, "node_modules/asana": { - "version": "0.18.5", - "resolved": "https://registry.npmjs.org/asana/-/asana-0.18.5.tgz", - "integrity": "sha512-goV903J5mkC+Km53MODyxXY/EiUjvevaH1UUzI198zuJn/sGFzScNBMFC7Ild1fJg7POXbD0GgVCN9sBsrzUGg==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/asana/-/asana-3.0.3.tgz", + "integrity": "sha512-/1+dZlRnbsfCoXanFwfFqrekbBxD8aNcTrgz1OW95p45ZE2UvdHM9sYJ8whOHOMkvQ4ARHUcEtiLrw/yH/NpWQ==", "dependencies": { - "bluebird": "^3.7.2", - "browser-request": "^0.3.2", - "lodash": "^4.17.20", - "readline": "^1.3.0", - "request": "^2.88.2" + "@babel/cli": "^7.0.0", + "superagent": "^5.3.0" } }, "node_modules/asn1": { "version": "0.2.4", "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.4.tgz", "integrity": "sha512-jxwzQpLQjSmWXgwaCZE9Nz+glAG01yF1QnWgbhGwHI5A6FRIEY6IVqtHhIepHqI7/kyEyQEagBC5mBEFlIYvdg==", + "dev": true, "dependencies": { "safer-buffer": "~2.1.0" } @@ -1288,6 +1346,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=", + "dev": true, "engines": { "node": ">=0.8" } @@ -1331,6 +1390,7 @@ "version": "0.7.0", "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=", + "dev": true, "engines": { "node": "*" } @@ -1338,7 +1398,8 @@ "node_modules/aws4": { "version": "1.11.0", "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.11.0.tgz", - "integrity": "sha512-xh1Rl34h6Fi1DC2WWKfxUTVqRsNnr6LsKz2+hfwDxQJWmrx8+c7ylaqBMcHfl1U1r2dsifOvKX3LQuLNZ+XSvA==" + "integrity": "sha512-xh1Rl34h6Fi1DC2WWKfxUTVqRsNnr6LsKz2+hfwDxQJWmrx8+c7ylaqBMcHfl1U1r2dsifOvKX3LQuLNZ+XSvA==", + "dev": true }, "node_modules/babel-jest": { "version": "26.6.3", @@ -1435,8 +1496,7 @@ "node_modules/balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", - "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", - "dev": true + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" }, "node_modules/base": { "version": "0.11.2", @@ -1519,6 +1579,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", + "dev": true, "dependencies": { "tweetnacl": "^0.14.3" } @@ -1528,16 +1589,22 @@ "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.0.tgz", "integrity": "sha512-jH6rKQIfroBbhEXVmI7XmXe3ix5S/PgJqpzdDPnR8JGLHWNYLsYZ6tK5iWOF/Ra3oqEX0NobXGlzbiylIzVphQ==" }, - "node_modules/bluebird": { - "version": "3.7.2", - "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", - "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==" + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "optional": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } }, "node_modules/brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "dev": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -1547,7 +1614,7 @@ "version": "3.0.2", "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", - "dev": true, + "devOptional": true, "dependencies": { "fill-range": "^7.0.1" }, @@ -1561,19 +1628,10 @@ "integrity": "sha512-9o5UecI3GhkpM6DrXr69PblIuWxPKk9Y0jHBRhdocZ2y7YECBFCsHm79Pr3OyR2AvjhDkabFJaDJMYRazHgsow==", "dev": true }, - "node_modules/browser-request": { - "version": "0.3.3", - "resolved": "https://registry.npmjs.org/browser-request/-/browser-request-0.3.3.tgz", - "integrity": "sha1-ns5bWsqJopkyJC4Yv5M975h2zBc=", - "engines": [ - "node" - ] - }, "node_modules/browserslist": { "version": "4.16.3", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.16.3.tgz", "integrity": "sha512-vIyhWmIkULaq04Gt93txdh+j02yX/JzlyhLYbV3YQCn/zvES3JnY7TifHHvvr1w5hTDluNKMkV05cs4vy8Q7sw==", - "dev": true, "dependencies": { "caniuse-lite": "^1.0.30001181", "colorette": "^1.2.1", @@ -1636,6 +1694,24 @@ "node": ">=0.10.0" } }, + "node_modules/call-bind": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", + "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", @@ -1657,8 +1733,7 @@ "node_modules/caniuse-lite": { "version": "1.0.30001204", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001204.tgz", - "integrity": "sha512-JUdjWpcxfJ9IPamy2f5JaRDCaqJOxDzOSKtbdx4rH9VivMd1vIzoPumsJa9LoMIi4Fx2BV2KZOxWhNkBjaYivQ==", - "dev": true + "integrity": "sha512-JUdjWpcxfJ9IPamy2f5JaRDCaqJOxDzOSKtbdx4rH9VivMd1vIzoPumsJa9LoMIi4Fx2BV2KZOxWhNkBjaYivQ==" }, "node_modules/capture-exit": { "version": "2.0.0", @@ -1675,7 +1750,8 @@ "node_modules/caseless": { "version": "0.12.0", "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", - "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=" + "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=", + "dev": true }, "node_modules/chalk": { "version": "4.1.0", @@ -1702,6 +1778,30 @@ "node": ">=10" } }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "optional": true, + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, "node_modules/ci-info": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz", @@ -1811,8 +1911,7 @@ "node_modules/colorette": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/colorette/-/colorette-1.2.2.tgz", - "integrity": "sha512-MKGMzyfeuutC/ZJ1cba9NqcNpfeqMUcYmyF1ZFY6/Cn7CNSAKx6a+s48sqLqyAiZuaP2TcqMhoo+dlwFnVxT9w==", - "dev": true + "integrity": "sha512-MKGMzyfeuutC/ZJ1cba9NqcNpfeqMUcYmyF1ZFY6/Cn7CNSAKx6a+s48sqLqyAiZuaP2TcqMhoo+dlwFnVxT9w==" }, "node_modules/combined-stream": { "version": "1.0.8", @@ -1825,27 +1924,37 @@ "node": ">= 0.8" } }, + "node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "engines": { + "node": ">= 6" + } + }, "node_modules/component-emitter": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz", - "integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==", - "dev": true + "integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==" }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", - "dev": true + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" }, "node_modules/convert-source-map": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.7.0.tgz", "integrity": "sha512-4FJkXzKXEDB1snCFZlLP4gpC3JILicCpGbzG9f9G7tGqGCzETQ2hWPrcinA9oU4wtf2biUaEH5065UnMeR33oA==", - "dev": true, "dependencies": { "safe-buffer": "~5.1.1" } }, + "node_modules/cookiejar": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/cookiejar/-/cookiejar-2.1.4.tgz", + "integrity": "sha512-LDx6oHrK+PhzLKJU9j5S7/Y3jM/mUHvD/DeI1WQmJn652iPC5Y4TBzC9l+5OMOXlyTTA+SmVUPm0HQUwpD5Jqw==" + }, "node_modules/copy-descriptor": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz", @@ -1858,7 +1967,8 @@ "node_modules/core-util-is": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", - "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", + "dev": true }, "node_modules/cross-spawn": { "version": "6.0.5", @@ -1913,6 +2023,7 @@ "version": "1.14.1", "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", + "dev": true, "dependencies": { "assert-plus": "^1.0.0" }, @@ -1938,7 +2049,6 @@ "version": "4.3.1", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz", "integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==", - "dev": true, "dependencies": { "ms": "2.1.2" }, @@ -1990,6 +2100,22 @@ "node": ">=0.10.0" } }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/define-property": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/define-property/-/define-property-2.0.2.tgz", @@ -2118,6 +2244,7 @@ "version": "0.1.2", "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=", + "dev": true, "dependencies": { "jsbn": "~0.1.0", "safer-buffer": "^2.1.0" @@ -2126,8 +2253,7 @@ "node_modules/electron-to-chromium": { "version": "1.3.700", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.700.tgz", - "integrity": "sha512-wQtaxVZzpOeCjW1CGuC5W3bYjE2jglvk076LcTautBOB9UtHztty7wNzjVsndiMcSsdUsdMy5w76w5J1U7OPTQ==", - "dev": true + "integrity": "sha512-wQtaxVZzpOeCjW1CGuC5W3bYjE2jglvk076LcTautBOB9UtHztty7wNzjVsndiMcSsdUsdMy5w76w5J1U7OPTQ==" }, "node_modules/emittery": { "version": "0.7.2", @@ -2177,11 +2303,29 @@ "is-arrayish": "^0.2.1" } }, + "node_modules/es-define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", + "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "dependencies": { + "get-intrinsic": "^1.2.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/escalade": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", - "dev": true, "engines": { "node": ">=6" } @@ -2190,7 +2334,6 @@ "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true, "engines": { "node": ">=0.8.0" } @@ -2687,7 +2830,8 @@ "node_modules/extend": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", - "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "dev": true }, "node_modules/extend-shallow": { "version": "3.0.2", @@ -2820,6 +2964,7 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=", + "dev": true, "engines": [ "node >=0.6.0" ] @@ -2827,12 +2972,14 @@ "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true }, "node_modules/fast-json-stable-stringify": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==" + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true }, "node_modules/fast-levenshtein": { "version": "2.0.6", @@ -2840,6 +2987,11 @@ "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", "dev": true }, + "node_modules/fast-safe-stringify": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", + "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==" + }, "node_modules/fb-watchman": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.1.tgz", @@ -2865,7 +3017,7 @@ "version": "7.0.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", - "dev": true, + "devOptional": true, "dependencies": { "to-regex-range": "^5.0.1" }, @@ -2918,6 +3070,7 @@ "version": "0.6.1", "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=", + "dev": true, "engines": { "node": "*" } @@ -2926,6 +3079,7 @@ "version": "2.3.3", "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz", "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", + "dev": true, "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.6", @@ -2935,6 +3089,15 @@ "node": ">= 0.12" } }, + "node_modules/formidable": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/formidable/-/formidable-1.2.6.tgz", + "integrity": "sha512-KcpbcpuLNOwrEjnbpMC0gS+X8ciDoZE1kkqzat4a8vrprf+s9pKNQ/QIwWfbfs4ltgmFl3MD177SNTkve3BwGQ==", + "deprecated": "Please upgrade to latest, formidable@v2 or formidable@v3! Check these notes: https://bit.ly/2ZEqIau", + "funding": { + "url": "https://ko-fi.com/tunnckoCore/commissions" + } + }, "node_modules/fragment-cache": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/fragment-cache/-/fragment-cache-0.2.1.tgz", @@ -2947,17 +3110,20 @@ "node": ">=0.10.0" } }, + "node_modules/fs-readdir-recursive": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fs-readdir-recursive/-/fs-readdir-recursive-1.1.0.tgz", + "integrity": "sha512-GNanXlVr2pf02+sPN40XN8HG+ePaNcvM0q5mZBd668Obwb0yD5GiUbZOFgwn8kGMY6I3mdyDJzieUy3PTYyTRA==" + }, "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", - "dev": true + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" }, "node_modules/fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", - "dev": true, "hasInstallScript": true, "optional": true, "os": [ @@ -2968,10 +3134,12 @@ } }, "node_modules/function-bind": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", - "dev": true + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, "node_modules/functional-red-black-tree": { "version": "1.0.1", @@ -2983,7 +3151,6 @@ "version": "1.0.0-beta.2", "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", - "dev": true, "engines": { "node": ">=6.9.0" } @@ -2997,6 +3164,24 @@ "node": "6.* || 8.* || >= 10.*" } }, + "node_modules/get-intrinsic": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", + "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/get-package-type": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", @@ -3031,20 +3216,20 @@ "version": "0.1.7", "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", + "dev": true, "dependencies": { "assert-plus": "^1.0.0" } }, "node_modules/glob": { - "version": "7.1.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", - "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", - "dev": true, + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", - "minimatch": "^3.0.4", + "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" }, @@ -3059,7 +3244,7 @@ "version": "5.1.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "dev": true, + "devOptional": true, "dependencies": { "is-glob": "^4.0.1" }, @@ -3071,11 +3256,21 @@ "version": "11.12.0", "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", - "dev": true, "engines": { "node": ">=4" } }, + "node_modules/gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/graceful-fs": { "version": "4.2.6", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.6.tgz", @@ -3093,6 +3288,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=", + "dev": true, "engines": { "node": ">=4" } @@ -3102,6 +3298,7 @@ "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.5.tgz", "integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==", "deprecated": "this library is no longer supported", + "dev": true, "dependencies": { "ajv": "^6.12.3", "har-schema": "^2.0.0" @@ -3131,6 +3328,39 @@ "node": ">=8" } }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", + "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/has-value": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/has-value/-/has-value-1.0.0.tgz", @@ -3203,6 +3433,17 @@ "node": ">=0.10.0" } }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/hosted-git-info": { "version": "2.8.8", "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.8.tgz", @@ -3231,6 +3472,7 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=", + "dev": true, "dependencies": { "assert-plus": "^1.0.0", "jsprim": "^1.2.2", @@ -3325,7 +3567,6 @@ "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", - "dev": true, "dependencies": { "once": "^1.3.0", "wrappy": "1" @@ -3334,8 +3575,7 @@ "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, "node_modules/is-accessor-descriptor": { "version": "0.1.6", @@ -3367,6 +3607,18 @@ "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", "dev": true }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "optional": true, + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/is-buffer": { "version": "1.1.6", "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", @@ -3473,7 +3725,7 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", - "dev": true, + "devOptional": true, "engines": { "node": ">=0.10.0" } @@ -3500,7 +3752,7 @@ "version": "4.0.1", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", - "dev": true, + "devOptional": true, "dependencies": { "is-extglob": "^2.1.1" }, @@ -3512,7 +3764,7 @@ "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", - "dev": true, + "devOptional": true, "engines": { "node": ">=0.12.0" } @@ -3543,7 +3795,8 @@ "node_modules/is-typedarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", - "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=" + "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=", + "dev": true }, "node_modules/is-windows": { "version": "1.0.2", @@ -3582,7 +3835,8 @@ "node_modules/isstream": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", - "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=" + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", + "dev": true }, "node_modules/istanbul-lib-coverage": { "version": "3.0.0", @@ -4333,8 +4587,7 @@ "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" }, "node_modules/js-yaml": { "version": "3.14.1", @@ -4352,7 +4605,8 @@ "node_modules/jsbn": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", - "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=" + "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=", + "dev": true }, "node_modules/jsdom": { "version": "16.5.1", @@ -4458,7 +4712,6 @@ "version": "2.5.2", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", - "dev": true, "bin": { "jsesc": "bin/jsesc" }, @@ -4475,12 +4728,14 @@ "node_modules/json-schema": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", - "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=" + "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=", + "dev": true }, "node_modules/json-schema-traverse": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==" + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true }, "node_modules/json-stable-stringify-without-jsonify": { "version": "1.0.1", @@ -4491,13 +4746,13 @@ "node_modules/json-stringify-safe": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", - "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=" + "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=", + "dev": true }, "node_modules/json5": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.0.tgz", "integrity": "sha512-f+8cldu7X/y7RAJurMEJmdoKXGB/X550w2Nr3tTbezL6RwEE/iMcm+tZnXeoZtKuOq6ft8+CqzEkrIgx1fPoQA==", - "dev": true, "dependencies": { "minimist": "^1.2.5" }, @@ -4512,6 +4767,7 @@ "version": "1.4.1", "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz", "integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=", + "dev": true, "engines": [ "node >=0.6.0" ], @@ -4589,7 +4845,6 @@ "version": "6.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dev": true, "dependencies": { "yallist": "^4.0.0" }, @@ -4648,6 +4903,14 @@ "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", "dev": true }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/micromatch": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.2.tgz", @@ -4661,6 +4924,17 @@ "node": ">=8" } }, + "node_modules/mime": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz", + "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4.0.0" + } + }, "node_modules/mime-db": { "version": "1.46.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.46.0.tgz", @@ -4690,10 +4964,9 @@ } }, "node_modules/minimatch": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", - "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", - "dev": true, + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", "dependencies": { "brace-expansion": "^1.1.7" }, @@ -4704,8 +4977,7 @@ "node_modules/minimist": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", - "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", - "dev": true + "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==" }, "node_modules/mixin-deep": { "version": "1.3.2", @@ -4756,8 +5028,7 @@ "node_modules/ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "dev": true + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" }, "node_modules/nanomatch": { "version": "1.2.13", @@ -4866,8 +5137,7 @@ "node_modules/node-releases": { "version": "1.1.71", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-1.1.71.tgz", - "integrity": "sha512-zR6HoT6LrLCRBwukmrVbHv0EpEQjksO6GmFcZQQuCAy139BEsoVKPYnf3jongYW83fAa1torLGYwxxky/p28sg==", - "dev": true + "integrity": "sha512-zR6HoT6LrLCRBwukmrVbHv0EpEQjksO6GmFcZQQuCAy139BEsoVKPYnf3jongYW83fAa1torLGYwxxky/p28sg==" }, "node_modules/normalize-package-data": { "version": "2.5.0", @@ -4894,7 +5164,7 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true, + "devOptional": true, "engines": { "node": ">=0.10.0" } @@ -4921,6 +5191,7 @@ "version": "0.9.0", "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==", + "dev": true, "engines": { "node": "*" } @@ -4963,6 +5234,14 @@ "node": ">=0.10.0" } }, + "node_modules/object-inspect": { + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz", + "integrity": "sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/object-visit": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/object-visit/-/object-visit-1.0.1.tgz", @@ -5160,7 +5439,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", - "dev": true, "engines": { "node": ">=0.10.0" } @@ -5183,13 +5461,14 @@ "node_modules/performance-now": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", - "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=" + "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=", + "dev": true }, "node_modules/picomatch": { "version": "2.2.2", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.2.2.tgz", "integrity": "sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg==", - "dev": true, + "devOptional": true, "engines": { "node": ">=8.6" }, @@ -5197,6 +5476,14 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pify": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", + "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", + "engines": { + "node": ">=6" + } + }, "node_modules/pirates": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.1.tgz", @@ -5291,7 +5578,8 @@ "node_modules/psl": { "version": "1.8.0", "resolved": "https://registry.npmjs.org/psl/-/psl-1.8.0.tgz", - "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==" + "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==", + "dev": true }, "node_modules/pump": { "version": "3.0.0", @@ -5307,6 +5595,7 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "dev": true, "engines": { "node": ">=6" } @@ -5315,6 +5604,7 @@ "version": "6.5.2", "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz", "integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==", + "dev": true, "engines": { "node": ">=0.6" } @@ -5366,10 +5656,30 @@ "node": ">=8" } }, - "node_modules/readline": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/readline/-/readline-1.3.0.tgz", - "integrity": "sha1-xYDXfvLPyHUrEySYBg3JeTp6wBw=" + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "optional": true, + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } }, "node_modules/regex-not": { "version": "1.0.2", @@ -5425,6 +5735,8 @@ "resolved": "https://registry.npmjs.org/request/-/request-2.88.2.tgz", "integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==", "deprecated": "request has been deprecated, see https://github.com/request/request/issues/3142", + "dev": true, + "peer": true, "dependencies": { "aws-sign2": "~0.7.0", "aws4": "^1.8.0", @@ -5501,6 +5813,8 @@ "version": "2.5.0", "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz", "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", + "dev": true, + "peer": true, "dependencies": { "psl": "^1.1.28", "punycode": "^2.1.1" @@ -5514,6 +5828,8 @@ "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==", "deprecated": "Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.", + "dev": true, + "peer": true, "bin": { "uuid": "bin/uuid" } @@ -5633,7 +5949,8 @@ "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true }, "node_modules/sane": { "version": "4.1.0", @@ -5827,7 +6144,6 @@ "version": "6.3.0", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true, "bin": { "semver": "bin/semver.js" } @@ -5838,6 +6154,22 @@ "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", "dev": true }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/set-value": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.1.tgz", @@ -5914,6 +6246,23 @@ "dev": true, "optional": true }, + "node_modules/side-channel": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", + "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/signal-exit": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz", @@ -6210,6 +6559,7 @@ "version": "1.16.1", "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.16.1.tgz", "integrity": "sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==", + "dev": true, "dependencies": { "asn1": "~0.2.3", "assert-plus": "^1.0.0", @@ -6285,6 +6635,33 @@ "node": ">=0.10.0" } }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, "node_modules/string-length": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", @@ -6363,6 +6740,69 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/superagent": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/superagent/-/superagent-5.3.1.tgz", + "integrity": "sha512-wjJ/MoTid2/RuGCOFtlacyGNxN9QLMgcpYLDQlWFIhhdJ93kNscFonGvrpAHSCVjRVj++DGCglocF7Aej1KHvQ==", + "deprecated": "Please upgrade to v7.0.2+ of superagent. We have fixed numerous issues with streams, form-data, attach(), filesystem errors not bubbling up (ENOENT on attach()), and all tests are now passing. See the releases tab for more information at .", + "dependencies": { + "component-emitter": "^1.3.0", + "cookiejar": "^2.1.2", + "debug": "^4.1.1", + "fast-safe-stringify": "^2.0.7", + "form-data": "^3.0.0", + "formidable": "^1.2.2", + "methods": "^1.1.2", + "mime": "^2.4.6", + "qs": "^6.9.4", + "readable-stream": "^3.6.0", + "semver": "^7.3.2" + }, + "engines": { + "node": ">= 7.0.0" + } + }, + "node_modules/superagent/node_modules/form-data": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz", + "integrity": "sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/superagent/node_modules/qs": { + "version": "6.12.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.12.0.tgz", + "integrity": "sha512-trVZiI6RMOkO476zLGaBIzszOdFPnCCXHPG9kn0yuS1uz6xdVxPfZdB3vUig9pxPFDM9BRAgz/YUIVQ1/vuiUg==", + "dependencies": { + "side-channel": "^1.0.6" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/superagent/node_modules/semver": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.0.tgz", + "integrity": "sha512-EnwXhrlwXMk9gKu5/flx5sv/an57AkRplG3hTK68W7FRDN+k+OWBj65M7719OkA82XLBxrcX0KSHj+X5COhOVg==", + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/supports-color": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", @@ -6483,7 +6923,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=", - "dev": true, "engines": { "node": ">=4" } @@ -6531,7 +6970,7 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", - "dev": true, + "devOptional": true, "dependencies": { "is-number": "^7.0.0" }, @@ -6577,6 +7016,7 @@ "version": "0.6.0", "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", + "dev": true, "dependencies": { "safe-buffer": "^5.0.1" }, @@ -6587,7 +7027,8 @@ "node_modules/tweetnacl": { "version": "0.14.5", "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", - "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=" + "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=", + "dev": true }, "node_modules/type-check": { "version": "0.3.2", @@ -6718,6 +7159,7 @@ "version": "4.4.1", "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, "dependencies": { "punycode": "^2.1.0" } @@ -6738,6 +7180,11 @@ "node": ">=0.10.0" } }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" + }, "node_modules/uuid": { "version": "8.3.2", "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", @@ -6791,6 +7238,7 @@ "version": "1.10.0", "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", + "dev": true, "engines": [ "node >=0.6.0" ], @@ -6968,8 +7416,7 @@ "node_modules/yallist": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" }, "node_modules/yargs": { "version": "15.4.1", @@ -7032,11 +7479,52 @@ "tunnel": "0.0.6" } }, + "@babel/cli": { + "version": "7.24.1", + "resolved": "https://registry.npmjs.org/@babel/cli/-/cli-7.24.1.tgz", + "integrity": "sha512-HbmrtxyFUr34LwAlV9jS+sSIjUp4FpdtIMGwgufY3AsxrIfsh/HxlMTywsONAZsU0RMYbZtbZFpUCrSGs7o0EA==", + "requires": { + "@jridgewell/trace-mapping": "^0.3.25", + "@nicolo-ribaudo/chokidar-2": "2.1.8-no-fsevents.3", + "chokidar": "^3.4.0", + "commander": "^4.0.1", + "convert-source-map": "^2.0.0", + "fs-readdir-recursive": "^1.1.0", + "glob": "^7.2.0", + "make-dir": "^2.1.0", + "slash": "^2.0.0" + }, + "dependencies": { + "convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==" + }, + "make-dir": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-2.1.0.tgz", + "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==", + "requires": { + "pify": "^4.0.1", + "semver": "^5.6.0" + } + }, + "semver": { + "version": "5.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz", + "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==" + }, + "slash": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", + "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==" + } + } + }, "@babel/code-frame": { "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.13.tgz", "integrity": "sha512-HV1Cm0Q3ZrpCR93tkWOYiuYIgLxZXZFVG2VgK+MBWjUqZTundupbfx2aXarXuw5Ko5aMcjtJgbSs4vUGBS5v6g==", - "dev": true, "requires": { "@babel/highlight": "^7.12.13" } @@ -7044,14 +7532,12 @@ "@babel/compat-data": { "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.13.12.tgz", - "integrity": "sha512-3eJJ841uKxeV8dcN/2yGEUy+RfgQspPEgQat85umsE1rotuquQ2AbIub4S6j7c50a2d+4myc+zSlnXeIHrOnhQ==", - "dev": true + "integrity": "sha512-3eJJ841uKxeV8dcN/2yGEUy+RfgQspPEgQat85umsE1rotuquQ2AbIub4S6j7c50a2d+4myc+zSlnXeIHrOnhQ==" }, "@babel/core": { "version": "7.13.10", "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.13.10.tgz", "integrity": "sha512-bfIYcT0BdKeAZrovpMqX2Mx5NrgAckGbwT982AkdS5GNfn3KMGiprlBAtmBcFZRUmpaufS6WZFP8trvx8ptFDw==", - "dev": true, "requires": { "@babel/code-frame": "^7.12.13", "@babel/generator": "^7.13.9", @@ -7074,8 +7560,7 @@ "source-map": { "version": "0.5.7", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", - "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", - "dev": true + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" } } }, @@ -7083,7 +7568,6 @@ "version": "7.13.9", "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.13.9.tgz", "integrity": "sha512-mHOOmY0Axl/JCTkxTU6Lf5sWOg/v8nUa+Xkt4zMTftX0wqmb6Sh7J8gvcehBw7q0AhrhAR+FDacKjCZ2X8K+Sw==", - "dev": true, "requires": { "@babel/types": "^7.13.0", "jsesc": "^2.5.1", @@ -7093,8 +7577,7 @@ "source-map": { "version": "0.5.7", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", - "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", - "dev": true + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" } } }, @@ -7102,7 +7585,6 @@ "version": "7.13.10", "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.13.10.tgz", "integrity": "sha512-/Xju7Qg1GQO4mHZ/Kcs6Au7gfafgZnwm+a7sy/ow/tV1sHeraRUHbjdat8/UvDor4Tez+siGKDk6zIKtCPKVJA==", - "dev": true, "requires": { "@babel/compat-data": "^7.13.8", "@babel/helper-validator-option": "^7.12.17", @@ -7114,7 +7596,6 @@ "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.12.13.tgz", "integrity": "sha512-TZvmPn0UOqmvi5G4vvw0qZTpVptGkB1GL61R6lKvrSdIxGm5Pky7Q3fpKiIkQCAtRCBUwB0PaThlx9vebCDSwA==", - "dev": true, "requires": { "@babel/helper-get-function-arity": "^7.12.13", "@babel/template": "^7.12.13", @@ -7125,7 +7606,6 @@ "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.12.13.tgz", "integrity": "sha512-DjEVzQNz5LICkzN0REdpD5prGoidvbdYk1BVgRUOINaWJP2t6avB27X1guXK1kXNrX0WMfsrm1A/ZBthYuIMQg==", - "dev": true, "requires": { "@babel/types": "^7.12.13" } @@ -7134,7 +7614,6 @@ "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.13.12.tgz", "integrity": "sha512-48ql1CLL59aKbU94Y88Xgb2VFy7a95ykGRbJJaaVv+LX5U8wFpLfiGXJJGUozsmA1oEh/o5Bp60Voq7ACyA/Sw==", - "dev": true, "requires": { "@babel/types": "^7.13.12" } @@ -7143,7 +7622,6 @@ "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.13.12.tgz", "integrity": "sha512-4cVvR2/1B693IuOvSI20xqqa/+bl7lqAMR59R4iu39R9aOX8/JoYY1sFaNvUMyMBGnHdwvJgUrzNLoUZxXypxA==", - "dev": true, "requires": { "@babel/types": "^7.13.12" } @@ -7152,7 +7630,6 @@ "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.13.12.tgz", "integrity": "sha512-7zVQqMO3V+K4JOOj40kxiCrMf6xlQAkewBB0eu2b03OO/Q21ZutOzjpfD79A5gtE/2OWi1nv625MrDlGlkbknQ==", - "dev": true, "requires": { "@babel/helper-module-imports": "^7.13.12", "@babel/helper-replace-supers": "^7.13.12", @@ -7168,7 +7645,6 @@ "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.12.13.tgz", "integrity": "sha512-BdWQhoVJkp6nVjB7nkFWcn43dkprYauqtk++Py2eaf/GRDFm5BxRqEIZCiHlZUGAVmtwKcsVL1dC68WmzeFmiA==", - "dev": true, "requires": { "@babel/types": "^7.12.13" } @@ -7183,7 +7659,6 @@ "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.13.12.tgz", "integrity": "sha512-Gz1eiX+4yDO8mT+heB94aLVNCL+rbuT2xy4YfyNqu8F+OI6vMvJK891qGBTqL9Uc8wxEvRW92Id6G7sDen3fFw==", - "dev": true, "requires": { "@babel/helper-member-expression-to-functions": "^7.13.12", "@babel/helper-optimise-call-expression": "^7.12.13", @@ -7195,7 +7670,6 @@ "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.13.12.tgz", "integrity": "sha512-7FEjbrx5SL9cWvXioDbnlYTppcZGuCY6ow3/D5vMggb2Ywgu4dMrpTJX0JdQAIcRRUElOIxF3yEooa9gUb9ZbA==", - "dev": true, "requires": { "@babel/types": "^7.13.12" } @@ -7204,7 +7678,6 @@ "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.12.13.tgz", "integrity": "sha512-tCJDltF83htUtXx5NLcaDqRmknv652ZWCHyoTETf1CXYJdPC7nohZohjUgieXhv0hTJdRf2FjDueFehdNucpzg==", - "dev": true, "requires": { "@babel/types": "^7.12.13" } @@ -7212,20 +7685,17 @@ "@babel/helper-validator-identifier": { "version": "7.12.11", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.12.11.tgz", - "integrity": "sha512-np/lG3uARFybkoHokJUmf1QfEvRVCPbmQeUQpKow5cQ3xWrV9i3rUHodKDJPQfTVX61qKi+UdYk8kik84n7XOw==", - "dev": true + "integrity": "sha512-np/lG3uARFybkoHokJUmf1QfEvRVCPbmQeUQpKow5cQ3xWrV9i3rUHodKDJPQfTVX61qKi+UdYk8kik84n7XOw==" }, "@babel/helper-validator-option": { "version": "7.12.17", "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.12.17.tgz", - "integrity": "sha512-TopkMDmLzq8ngChwRlyjR6raKD6gMSae4JdYDB8bByKreQgG0RBTuKe9LRxW3wFtUnjxOPRKBDwEH6Mg5KeDfw==", - "dev": true + "integrity": "sha512-TopkMDmLzq8ngChwRlyjR6raKD6gMSae4JdYDB8bByKreQgG0RBTuKe9LRxW3wFtUnjxOPRKBDwEH6Mg5KeDfw==" }, "@babel/helpers": { "version": "7.13.10", "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.13.10.tgz", "integrity": "sha512-4VO883+MWPDUVRF3PhiLBUFHoX/bsLTGFpFK/HqvvfBZz2D57u9XzPVNFVBTc0PW/CWR9BXTOKt8NF4DInUHcQ==", - "dev": true, "requires": { "@babel/template": "^7.12.13", "@babel/traverse": "^7.13.0", @@ -7236,7 +7706,6 @@ "version": "7.13.10", "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.13.10.tgz", "integrity": "sha512-5aPpe5XQPzflQrFwL1/QoeHkP2MsA4JCntcXHRhEsdsfPVkvPi2w7Qix4iV7t5S/oC9OodGrggd8aco1g3SZFg==", - "dev": true, "requires": { "@babel/helper-validator-identifier": "^7.12.11", "chalk": "^2.0.0", @@ -7247,7 +7716,6 @@ "version": "3.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, "requires": { "color-convert": "^1.9.0" } @@ -7256,7 +7724,6 @@ "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", @@ -7267,7 +7734,6 @@ "version": "1.9.3", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, "requires": { "color-name": "1.1.3" } @@ -7275,20 +7741,17 @@ "color-name": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", - "dev": true + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", - "dev": true + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" }, "supports-color": { "version": "5.5.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, "requires": { "has-flag": "^3.0.0" } @@ -7298,8 +7761,7 @@ "@babel/parser": { "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.13.12.tgz", - "integrity": "sha512-4T7Pb244rxH24yR116LAuJ+adxXXnHhZaLJjegJVKSdoNCe4x1eDBaud5YIcQFcqzsaD5BHvJw5BQ0AZapdCRw==", - "dev": true + "integrity": "sha512-4T7Pb244rxH24yR116LAuJ+adxXXnHhZaLJjegJVKSdoNCe4x1eDBaud5YIcQFcqzsaD5BHvJw5BQ0AZapdCRw==" }, "@babel/plugin-syntax-async-generators": { "version": "7.8.4", @@ -7413,7 +7875,6 @@ "version": "7.12.13", "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.12.13.tgz", "integrity": "sha512-/7xxiGA57xMo/P2GVvdEumr8ONhFOhfgq2ihK3h1e6THqzTAkHbkXgB0xI9yeTfIUoH3+oAeHhqm/I43OTbbjA==", - "dev": true, "requires": { "@babel/code-frame": "^7.12.13", "@babel/parser": "^7.12.13", @@ -7424,7 +7885,6 @@ "version": "7.13.0", "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.13.0.tgz", "integrity": "sha512-xys5xi5JEhzC3RzEmSGrs/b3pJW/o87SypZ+G/PhaE7uqVQNv/jlmVIBXuoh5atqQ434LfXV+sf23Oxj0bchJQ==", - "dev": true, "requires": { "@babel/code-frame": "^7.12.13", "@babel/generator": "^7.13.0", @@ -7441,7 +7901,6 @@ "version": "7.13.12", "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.13.12.tgz", "integrity": "sha512-K4nY2xFN4QMvQwkQ+zmBDp6ANMbVNw6BbxWmYA4qNjhR9W+Lj/8ky5MEY2Me5r+B2c6/v6F53oMndG+f9s3IiA==", - "dev": true, "requires": { "@babel/helper-validator-identifier": "^7.12.11", "lodash": "^4.17.19", @@ -7703,11 +8162,36 @@ "chalk": "^4.0.0" } }, + "@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==" + }, + "@jridgewell/sourcemap-codec": { + "version": "1.4.15", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==" + }, + "@jridgewell/trace-mapping": { + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", + "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "requires": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, "@mobsuccess-devops/asana-magics": { "version": "1.0.1-ci-4263876762.0", "resolved": "https://npm.pkg.github.com/download/@mobsuccess-devops/asana-magics/1.0.1-ci-4263876762.0/a74d8aebb535cae437157e15b019a385eedb3c0c", "integrity": "sha512-77lub4Hu7iZVuxFU+CD50tJ+0rKTxqcNNYrfx8etHmWUdMWdgSHGZx7BfIex/leDW4oxkzY/FQUmHMpp0vnZeg==" }, + "@nicolo-ribaudo/chokidar-2": { + "version": "2.1.8-no-fsevents.3", + "resolved": "https://registry.npmjs.org/@nicolo-ribaudo/chokidar-2/-/chokidar-2-2.1.8-no-fsevents.3.tgz", + "integrity": "sha512-s88O1aVtXftvp5bCPB7WnmXc5IwOZZ7YPuwNPt+GtOOXpPvad1LfbmjYv+qII7zP6RU2QGnqve27dnLycEnyEQ==", + "optional": true + }, "@octokit/auth-token": { "version": "2.4.5", "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.4.5.tgz", @@ -7983,6 +8467,7 @@ "version": "6.12.6", "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, "requires": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", @@ -8029,10 +8514,10 @@ } }, "anymatch": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.1.tgz", - "integrity": "sha512-mM8522psRCqzV+6LhomX5wgp25YVibjh8Wj23I5RPkPppSVSjyKD2A2mBJmWGa+KN7f2D6LNh9jkBCeyLktzjg==", - "dev": true, + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "devOptional": true, "requires": { "normalize-path": "^3.0.0", "picomatch": "^2.0.4" @@ -8072,21 +8557,19 @@ "dev": true }, "asana": { - "version": "0.18.5", - "resolved": "https://registry.npmjs.org/asana/-/asana-0.18.5.tgz", - "integrity": "sha512-goV903J5mkC+Km53MODyxXY/EiUjvevaH1UUzI198zuJn/sGFzScNBMFC7Ild1fJg7POXbD0GgVCN9sBsrzUGg==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/asana/-/asana-3.0.3.tgz", + "integrity": "sha512-/1+dZlRnbsfCoXanFwfFqrekbBxD8aNcTrgz1OW95p45ZE2UvdHM9sYJ8whOHOMkvQ4ARHUcEtiLrw/yH/NpWQ==", "requires": { - "bluebird": "^3.7.2", - "browser-request": "^0.3.2", - "lodash": "^4.17.20", - "readline": "^1.3.0", - "request": "^2.88.2" + "@babel/cli": "^7.0.0", + "superagent": "^5.3.0" } }, "asn1": { "version": "0.2.4", "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.4.tgz", "integrity": "sha512-jxwzQpLQjSmWXgwaCZE9Nz+glAG01yF1QnWgbhGwHI5A6FRIEY6IVqtHhIepHqI7/kyEyQEagBC5mBEFlIYvdg==", + "dev": true, "requires": { "safer-buffer": "~2.1.0" } @@ -8094,7 +8577,8 @@ "assert-plus": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", - "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=" + "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=", + "dev": true }, "assign-symbols": { "version": "1.0.0", @@ -8122,12 +8606,14 @@ "aws-sign2": { "version": "0.7.0", "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", - "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=" + "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=", + "dev": true }, "aws4": { "version": "1.11.0", "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.11.0.tgz", - "integrity": "sha512-xh1Rl34h6Fi1DC2WWKfxUTVqRsNnr6LsKz2+hfwDxQJWmrx8+c7ylaqBMcHfl1U1r2dsifOvKX3LQuLNZ+XSvA==" + "integrity": "sha512-xh1Rl34h6Fi1DC2WWKfxUTVqRsNnr6LsKz2+hfwDxQJWmrx8+c7ylaqBMcHfl1U1r2dsifOvKX3LQuLNZ+XSvA==", + "dev": true }, "babel-jest": { "version": "26.6.3", @@ -8203,8 +8689,7 @@ "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", - "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", - "dev": true + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" }, "base": { "version": "0.11.2", @@ -8271,6 +8756,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", + "dev": true, "requires": { "tweetnacl": "^0.14.3" } @@ -8280,16 +8766,16 @@ "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.0.tgz", "integrity": "sha512-jH6rKQIfroBbhEXVmI7XmXe3ix5S/PgJqpzdDPnR8JGLHWNYLsYZ6tK5iWOF/Ra3oqEX0NobXGlzbiylIzVphQ==" }, - "bluebird": { - "version": "3.7.2", - "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", - "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==" + "binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "optional": true }, "brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "dev": true, "requires": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -8299,7 +8785,7 @@ "version": "3.0.2", "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", - "dev": true, + "devOptional": true, "requires": { "fill-range": "^7.0.1" } @@ -8310,16 +8796,10 @@ "integrity": "sha512-9o5UecI3GhkpM6DrXr69PblIuWxPKk9Y0jHBRhdocZ2y7YECBFCsHm79Pr3OyR2AvjhDkabFJaDJMYRazHgsow==", "dev": true }, - "browser-request": { - "version": "0.3.3", - "resolved": "https://registry.npmjs.org/browser-request/-/browser-request-0.3.3.tgz", - "integrity": "sha1-ns5bWsqJopkyJC4Yv5M975h2zBc=" - }, "browserslist": { "version": "4.16.3", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.16.3.tgz", "integrity": "sha512-vIyhWmIkULaq04Gt93txdh+j02yX/JzlyhLYbV3YQCn/zvES3JnY7TifHHvvr1w5hTDluNKMkV05cs4vy8Q7sw==", - "dev": true, "requires": { "caniuse-lite": "^1.0.30001181", "colorette": "^1.2.1", @@ -8368,6 +8848,18 @@ } } }, + "call-bind": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", + "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "requires": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + } + }, "callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", @@ -8383,8 +8875,7 @@ "caniuse-lite": { "version": "1.0.30001204", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001204.tgz", - "integrity": "sha512-JUdjWpcxfJ9IPamy2f5JaRDCaqJOxDzOSKtbdx4rH9VivMd1vIzoPumsJa9LoMIi4Fx2BV2KZOxWhNkBjaYivQ==", - "dev": true + "integrity": "sha512-JUdjWpcxfJ9IPamy2f5JaRDCaqJOxDzOSKtbdx4rH9VivMd1vIzoPumsJa9LoMIi4Fx2BV2KZOxWhNkBjaYivQ==" }, "capture-exit": { "version": "2.0.0", @@ -8398,7 +8889,8 @@ "caseless": { "version": "0.12.0", "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", - "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=" + "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=", + "dev": true }, "chalk": { "version": "4.1.0", @@ -8416,6 +8908,22 @@ "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", "dev": true }, + "chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "optional": true, + "requires": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "fsevents": "~2.3.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + } + }, "ci-info": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz", @@ -8508,8 +9016,7 @@ "colorette": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/colorette/-/colorette-1.2.2.tgz", - "integrity": "sha512-MKGMzyfeuutC/ZJ1cba9NqcNpfeqMUcYmyF1ZFY6/Cn7CNSAKx6a+s48sqLqyAiZuaP2TcqMhoo+dlwFnVxT9w==", - "dev": true + "integrity": "sha512-MKGMzyfeuutC/ZJ1cba9NqcNpfeqMUcYmyF1ZFY6/Cn7CNSAKx6a+s48sqLqyAiZuaP2TcqMhoo+dlwFnVxT9w==" }, "combined-stream": { "version": "1.0.8", @@ -8519,27 +9026,34 @@ "delayed-stream": "~1.0.0" } }, + "commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==" + }, "component-emitter": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz", - "integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==", - "dev": true + "integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==" }, "concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", - "dev": true + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" }, "convert-source-map": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.7.0.tgz", "integrity": "sha512-4FJkXzKXEDB1snCFZlLP4gpC3JILicCpGbzG9f9G7tGqGCzETQ2hWPrcinA9oU4wtf2biUaEH5065UnMeR33oA==", - "dev": true, "requires": { "safe-buffer": "~5.1.1" } }, + "cookiejar": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/cookiejar/-/cookiejar-2.1.4.tgz", + "integrity": "sha512-LDx6oHrK+PhzLKJU9j5S7/Y3jM/mUHvD/DeI1WQmJn652iPC5Y4TBzC9l+5OMOXlyTTA+SmVUPm0HQUwpD5Jqw==" + }, "copy-descriptor": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz", @@ -8549,7 +9063,8 @@ "core-util-is": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", - "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", + "dev": true }, "cross-spawn": { "version": "6.0.5", @@ -8599,6 +9114,7 @@ "version": "1.14.1", "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", + "dev": true, "requires": { "assert-plus": "^1.0.0" } @@ -8618,7 +9134,6 @@ "version": "4.3.1", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz", "integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==", - "dev": true, "requires": { "ms": "2.1.2" } @@ -8653,6 +9168,16 @@ "integrity": "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==", "dev": true }, + "define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "requires": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + } + }, "define-property": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/define-property/-/define-property-2.0.2.tgz", @@ -8752,6 +9277,7 @@ "version": "0.1.2", "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=", + "dev": true, "requires": { "jsbn": "~0.1.0", "safer-buffer": "^2.1.0" @@ -8760,8 +9286,7 @@ "electron-to-chromium": { "version": "1.3.700", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.700.tgz", - "integrity": "sha512-wQtaxVZzpOeCjW1CGuC5W3bYjE2jglvk076LcTautBOB9UtHztty7wNzjVsndiMcSsdUsdMy5w76w5J1U7OPTQ==", - "dev": true + "integrity": "sha512-wQtaxVZzpOeCjW1CGuC5W3bYjE2jglvk076LcTautBOB9UtHztty7wNzjVsndiMcSsdUsdMy5w76w5J1U7OPTQ==" }, "emittery": { "version": "0.7.2", @@ -8802,17 +9327,28 @@ "is-arrayish": "^0.2.1" } }, + "es-define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", + "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "requires": { + "get-intrinsic": "^1.2.4" + } + }, + "es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==" + }, "escalade": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", - "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", - "dev": true + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==" }, "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" }, "escodegen": { "version": "2.0.0", @@ -9183,7 +9719,8 @@ "extend": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", - "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "dev": true }, "extend-shallow": { "version": "3.0.2", @@ -9289,17 +9826,20 @@ "extsprintf": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", - "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=" + "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=", + "dev": true }, "fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true }, "fast-json-stable-stringify": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==" + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true }, "fast-levenshtein": { "version": "2.0.6", @@ -9307,6 +9847,11 @@ "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", "dev": true }, + "fast-safe-stringify": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", + "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==" + }, "fb-watchman": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.1.tgz", @@ -9329,7 +9874,7 @@ "version": "7.0.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", - "dev": true, + "devOptional": true, "requires": { "to-regex-range": "^5.0.1" } @@ -9369,18 +9914,25 @@ "forever-agent": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", - "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=" + "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=", + "dev": true }, "form-data": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz", "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", + "dev": true, "requires": { "asynckit": "^0.4.0", "combined-stream": "^1.0.6", "mime-types": "^2.1.12" } }, + "formidable": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/formidable/-/formidable-1.2.6.tgz", + "integrity": "sha512-KcpbcpuLNOwrEjnbpMC0gS+X8ciDoZE1kkqzat4a8vrprf+s9pKNQ/QIwWfbfs4ltgmFl3MD177SNTkve3BwGQ==" + }, "fragment-cache": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/fragment-cache/-/fragment-cache-0.2.1.tgz", @@ -9390,24 +9942,26 @@ "map-cache": "^0.2.2" } }, + "fs-readdir-recursive": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fs-readdir-recursive/-/fs-readdir-recursive-1.1.0.tgz", + "integrity": "sha512-GNanXlVr2pf02+sPN40XN8HG+ePaNcvM0q5mZBd668Obwb0yD5GiUbZOFgwn8kGMY6I3mdyDJzieUy3PTYyTRA==" + }, "fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", - "dev": true + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" }, "fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", - "dev": true, "optional": true }, "function-bind": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", - "dev": true + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==" }, "functional-red-black-tree": { "version": "1.0.1", @@ -9418,8 +9972,7 @@ "gensync": { "version": "1.0.0-beta.2", "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", - "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", - "dev": true + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==" }, "get-caller-file": { "version": "2.0.5", @@ -9427,6 +9980,18 @@ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", "dev": true }, + "get-intrinsic": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", + "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "requires": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + } + }, "get-package-type": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", @@ -9452,20 +10017,20 @@ "version": "0.1.7", "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", + "dev": true, "requires": { "assert-plus": "^1.0.0" } }, "glob": { - "version": "7.1.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", - "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", - "dev": true, + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", "requires": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", - "minimatch": "^3.0.4", + "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } @@ -9474,7 +10039,7 @@ "version": "5.1.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "dev": true, + "devOptional": true, "requires": { "is-glob": "^4.0.1" } @@ -9482,8 +10047,15 @@ "globals": { "version": "11.12.0", "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", - "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", - "dev": true + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==" + }, + "gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "requires": { + "get-intrinsic": "^1.1.3" + } }, "graceful-fs": { "version": "4.2.6", @@ -9501,12 +10073,14 @@ "har-schema": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", - "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=" + "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=", + "dev": true }, "har-validator": { "version": "5.1.5", "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.5.tgz", "integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==", + "dev": true, "requires": { "ajv": "^6.12.3", "har-schema": "^2.0.0" @@ -9527,6 +10101,24 @@ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true }, + "has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "requires": { + "es-define-property": "^1.0.0" + } + }, + "has-proto": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", + "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==" + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==" + }, "has-value": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/has-value/-/has-value-1.0.0.tgz", @@ -9587,6 +10179,14 @@ } } }, + "hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "requires": { + "function-bind": "^1.1.2" + } + }, "hosted-git-info": { "version": "2.8.8", "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.8.tgz", @@ -9612,6 +10212,7 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=", + "dev": true, "requires": { "assert-plus": "^1.0.0", "jsprim": "^1.2.2", @@ -9677,7 +10278,6 @@ "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", - "dev": true, "requires": { "once": "^1.3.0", "wrappy": "1" @@ -9686,8 +10286,7 @@ "inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, "is-accessor-descriptor": { "version": "0.1.6", @@ -9715,6 +10314,15 @@ "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", "dev": true }, + "is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "optional": true, + "requires": { + "binary-extensions": "^2.0.0" + } + }, "is-buffer": { "version": "1.1.6", "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", @@ -9795,7 +10403,7 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", - "dev": true + "devOptional": true }, "is-fullwidth-code-point": { "version": "3.0.0", @@ -9813,7 +10421,7 @@ "version": "4.0.1", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", - "dev": true, + "devOptional": true, "requires": { "is-extglob": "^2.1.1" } @@ -9822,7 +10430,7 @@ "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", - "dev": true + "devOptional": true }, "is-plain-object": { "version": "5.0.0", @@ -9844,7 +10452,8 @@ "is-typedarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", - "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=" + "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=", + "dev": true }, "is-windows": { "version": "1.0.2", @@ -9877,7 +10486,8 @@ "isstream": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", - "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=" + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", + "dev": true }, "istanbul-lib-coverage": { "version": "3.0.0", @@ -10463,8 +11073,7 @@ "js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" }, "js-yaml": { "version": "3.14.1", @@ -10479,7 +11088,8 @@ "jsbn": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", - "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=" + "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=", + "dev": true }, "jsdom": { "version": "16.5.1", @@ -10566,8 +11176,7 @@ "jsesc": { "version": "2.5.2", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", - "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", - "dev": true + "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==" }, "json-parse-even-better-errors": { "version": "2.3.1", @@ -10578,12 +11187,14 @@ "json-schema": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", - "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=" + "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=", + "dev": true }, "json-schema-traverse": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==" + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true }, "json-stable-stringify-without-jsonify": { "version": "1.0.1", @@ -10594,13 +11205,13 @@ "json-stringify-safe": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", - "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=" + "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=", + "dev": true }, "json5": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.0.tgz", "integrity": "sha512-f+8cldu7X/y7RAJurMEJmdoKXGB/X550w2Nr3tTbezL6RwEE/iMcm+tZnXeoZtKuOq6ft8+CqzEkrIgx1fPoQA==", - "dev": true, "requires": { "minimist": "^1.2.5" } @@ -10609,6 +11220,7 @@ "version": "1.4.1", "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz", "integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=", + "dev": true, "requires": { "assert-plus": "1.0.0", "extsprintf": "1.3.0", @@ -10668,7 +11280,6 @@ "version": "6.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dev": true, "requires": { "yallist": "^4.0.0" } @@ -10712,6 +11323,11 @@ "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", "dev": true }, + "methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==" + }, "micromatch": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.2.tgz", @@ -10722,6 +11338,11 @@ "picomatch": "^2.0.5" } }, + "mime": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz", + "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==" + }, "mime-db": { "version": "1.46.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.46.0.tgz", @@ -10742,10 +11363,9 @@ "dev": true }, "minimatch": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", - "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", - "dev": true, + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", "requires": { "brace-expansion": "^1.1.7" } @@ -10753,8 +11373,7 @@ "minimist": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", - "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", - "dev": true + "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==" }, "mixin-deep": { "version": "1.3.2", @@ -10795,8 +11414,7 @@ "ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "dev": true + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" }, "nanomatch": { "version": "1.2.13", @@ -10886,8 +11504,7 @@ "node-releases": { "version": "1.1.71", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-1.1.71.tgz", - "integrity": "sha512-zR6HoT6LrLCRBwukmrVbHv0EpEQjksO6GmFcZQQuCAy139BEsoVKPYnf3jongYW83fAa1torLGYwxxky/p28sg==", - "dev": true + "integrity": "sha512-zR6HoT6LrLCRBwukmrVbHv0EpEQjksO6GmFcZQQuCAy139BEsoVKPYnf3jongYW83fAa1torLGYwxxky/p28sg==" }, "normalize-package-data": { "version": "2.5.0", @@ -10913,7 +11530,7 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true + "devOptional": true }, "npm-run-path": { "version": "2.0.2", @@ -10933,7 +11550,8 @@ "oauth-sign": { "version": "0.9.0", "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", - "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==" + "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==", + "dev": true }, "object-copy": { "version": "0.1.0", @@ -10966,6 +11584,11 @@ } } }, + "object-inspect": { + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz", + "integrity": "sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==" + }, "object-visit": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/object-visit/-/object-visit-1.0.1.tgz", @@ -11109,8 +11732,7 @@ "path-is-absolute": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", - "dev": true + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" }, "path-key": { "version": "2.0.1", @@ -11127,13 +11749,19 @@ "performance-now": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", - "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=" + "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=", + "dev": true }, "picomatch": { "version": "2.2.2", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.2.2.tgz", "integrity": "sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg==", - "dev": true + "devOptional": true + }, + "pify": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", + "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==" }, "pirates": { "version": "4.0.1", @@ -11202,7 +11830,8 @@ "psl": { "version": "1.8.0", "resolved": "https://registry.npmjs.org/psl/-/psl-1.8.0.tgz", - "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==" + "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==", + "dev": true }, "pump": { "version": "3.0.0", @@ -11217,12 +11846,14 @@ "punycode": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", - "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==" + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "dev": true }, "qs": { "version": "6.5.2", "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz", - "integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==" + "integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==", + "dev": true }, "react-is": { "version": "17.0.2", @@ -11261,10 +11892,24 @@ "type-fest": "^0.8.1" } }, - "readline": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/readline/-/readline-1.3.0.tgz", - "integrity": "sha1-xYDXfvLPyHUrEySYBg3JeTp6wBw=" + "readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "requires": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + } + }, + "readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "optional": true, + "requires": { + "picomatch": "^2.2.1" + } }, "regex-not": { "version": "1.0.2", @@ -11304,6 +11949,8 @@ "version": "2.88.2", "resolved": "https://registry.npmjs.org/request/-/request-2.88.2.tgz", "integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==", + "dev": true, + "peer": true, "requires": { "aws-sign2": "~0.7.0", "aws4": "^1.8.0", @@ -11331,6 +11978,8 @@ "version": "2.5.0", "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz", "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", + "dev": true, + "peer": true, "requires": { "psl": "^1.1.28", "punycode": "^2.1.1" @@ -11339,7 +11988,9 @@ "uuid": { "version": "3.4.0", "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", - "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==" + "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==", + "dev": true, + "peer": true } } }, @@ -11462,7 +12113,8 @@ "safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true }, "sane": { "version": "4.1.0", @@ -11623,8 +12275,7 @@ "semver": { "version": "6.3.0", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==" }, "set-blocking": { "version": "2.0.0", @@ -11632,6 +12283,19 @@ "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", "dev": true }, + "set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "requires": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + } + }, "set-value": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.1.tgz", @@ -11692,6 +12356,17 @@ "dev": true, "optional": true }, + "side-channel": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", + "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "requires": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + } + }, "signal-exit": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz", @@ -11941,6 +12616,7 @@ "version": "1.16.1", "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.16.1.tgz", "integrity": "sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==", + "dev": true, "requires": { "asn1": "~0.2.3", "assert-plus": "^1.0.0", @@ -11997,6 +12673,21 @@ "integrity": "sha1-NbCYdbT/SfJqd35QmzCQoyJr8ks=", "dev": true }, + "string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "requires": { + "safe-buffer": "~5.2.0" + }, + "dependencies": { + "safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==" + } + } + }, "string-length": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", @@ -12051,6 +12742,52 @@ "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", "dev": true }, + "superagent": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/superagent/-/superagent-5.3.1.tgz", + "integrity": "sha512-wjJ/MoTid2/RuGCOFtlacyGNxN9QLMgcpYLDQlWFIhhdJ93kNscFonGvrpAHSCVjRVj++DGCglocF7Aej1KHvQ==", + "requires": { + "component-emitter": "^1.3.0", + "cookiejar": "^2.1.2", + "debug": "^4.1.1", + "fast-safe-stringify": "^2.0.7", + "form-data": "^3.0.0", + "formidable": "^1.2.2", + "methods": "^1.1.2", + "mime": "^2.4.6", + "qs": "^6.9.4", + "readable-stream": "^3.6.0", + "semver": "^7.3.2" + }, + "dependencies": { + "form-data": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz", + "integrity": "sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg==", + "requires": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + } + }, + "qs": { + "version": "6.12.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.12.0.tgz", + "integrity": "sha512-trVZiI6RMOkO476zLGaBIzszOdFPnCCXHPG9kn0yuS1uz6xdVxPfZdB3vUig9pxPFDM9BRAgz/YUIVQ1/vuiUg==", + "requires": { + "side-channel": "^1.0.6" + } + }, + "semver": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.0.tgz", + "integrity": "sha512-EnwXhrlwXMk9gKu5/flx5sv/an57AkRplG3hTK68W7FRDN+k+OWBj65M7719OkA82XLBxrcX0KSHj+X5COhOVg==", + "requires": { + "lru-cache": "^6.0.0" + } + } + } + }, "supports-color": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", @@ -12150,8 +12887,7 @@ "to-fast-properties": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", - "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=", - "dev": true + "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=" }, "to-object-path": { "version": "0.3.0", @@ -12189,7 +12925,7 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", - "dev": true, + "devOptional": true, "requires": { "is-number": "^7.0.0" } @@ -12223,6 +12959,7 @@ "version": "0.6.0", "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", + "dev": true, "requires": { "safe-buffer": "^5.0.1" } @@ -12230,7 +12967,8 @@ "tweetnacl": { "version": "0.14.5", "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", - "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=" + "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=", + "dev": true }, "type-check": { "version": "0.3.2", @@ -12335,6 +13073,7 @@ "version": "4.4.1", "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, "requires": { "punycode": "^2.1.0" } @@ -12351,6 +13090,11 @@ "integrity": "sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ==", "dev": true }, + "util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" + }, "uuid": { "version": "8.3.2", "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", @@ -12397,6 +13141,7 @@ "version": "1.10.0", "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", + "dev": true, "requires": { "assert-plus": "^1.0.0", "core-util-is": "1.0.2", @@ -12539,8 +13284,7 @@ "yallist": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" }, "yargs": { "version": "15.4.1", diff --git a/package.json b/package.json index 7dcbf331c..07c79d804 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,7 @@ "@actions/core": "^1.2.6", "@actions/github": "^4.0.0", "@mobsuccess-devops/asana-magics": "^1.0.1-ci-4263876762.0", - "asana": "^0.18.5" + "asana": "^3.0.3" }, "devDependencies": { "eslint": "^7.22.0",